diff --git a/3d-bin-packing/3d-bin-packing-tests.ts b/3d-bin-packing/3d-bin-packing-tests.ts index 319624d597..8e394e46bb 100644 --- a/3d-bin-packing/3d-bin-packing-tests.ts +++ b/3d-bin-packing/3d-bin-packing-tests.ts @@ -1,5 +1,5 @@ import packer = require("3d-bin-packing"); -import samchon = require("samchon-framework"); +import samchon = require("samchon"); function main(): void { diff --git a/3d-bin-packing/index.d.ts b/3d-bin-packing/index.d.ts index 14228f3141..8165ea513e 100644 --- a/3d-bin-packing/index.d.ts +++ b/3d-bin-packing/index.d.ts @@ -1,20 +1,22 @@ -// Type definitions for 3d-bin-packing +// Type definitions for 3d-bin-packing v1.1.2 // Project: https://github.com/betterwaysystems/packer // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 -/// -/// -/// -/// -/// +/// declare module "3d-bin-packing" { - export = bws.packer; + export = bws.packer; +} + +/// +/// +declare namespace bws.packer { + export import library = samchon.library; + export import protocol = samchon.protocol; + function _Test(): void; } -declare var ReactDataGrid: typeof AdazzleReactDataGrid.ReactDataGrid; declare namespace boxologic { /** *

An abstract instance of boxologic.

@@ -62,122 +64,6 @@ declare namespace boxologic { constructor(width: number, height: number, length: number); } } -declare namespace bws.packer { - /** - * @brief Packer, a solver of 3d bin packing with multiple wrappers. - * - * @details - *

Packer is a facade class supporting packing operations in user side. You can solve a packing problem - * by constructing Packer class with {@link WrapperArray wrappers} and {@link InstanceArray instances} to - * pack and executing {@link optimize Packer.optimize()} method.

- * - *

In background side, deducting packing solution, those algorithms are used.

- * - * - * @author Jeongho Nam - */ - class Packer extends samchon.protocol.Entity { - /** - * Candidate wrappers who can contain instances. - */ - protected wrapperArray: WrapperArray; - /** - * Instances trying to pack into the wrapper. - */ - protected instanceArray: InstanceArray; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from members. - * - * @param wrapperArray Candidate wrappers who can contain instances. - * @param instanceArray Instances to be packed into some wrappers. - */ - constructor(wrapperArray: WrapperArray, instanceArray: InstanceArray); - /** - * @inheritdoc - */ - construct(xml: samchon.library.XML): void; - /** - * Get wrapperArray. - */ - getWrapperArray(): WrapperArray; - /** - * Get instanceArray. - */ - getInstanceArray(): InstanceArray; - /** - *

Deduct - * - */ - optimize(): WrapperArray; - /** - * @brief Initialize sequence list (gene_array). - * - * @details - *

Deducts initial sequence list by such assumption:

- * - *
    - *
  • Cost of larger wrapper is less than smaller one, within framework of price per volume unit.
  • - *
      - *
    • Wrapper Larger: (price: $1,000, volume: 100cm^3 -> price per volume unit: $10 / cm^3)
    • - *
    • Wrapper Smaller: (price: $700, volume: 50cm^3 -> price per volume unit: $14 / cm^3)
    • - *
    • Larger's cost is less than Smaller, within framework of price per volume unit
    • - *
    - *
- * - *

Method {@link initGenes initGenes()} constructs {@link WrapperGroup WrapperGroups} corresponding - * with the {@link wrapperArray} and allocates {@link instanceArray instances} to a {@link WrapperGroup}, - * has the smallest cost between containbles.

- * - *

After executing packing solution by {@link WrapperGroup.optimize WrapperGroup.optimize()}, trying to - * {@link repack re-pack} each {@link WrapperGroup} to another type of {@link Wrapper}, deducts the best - * solution between them. It's the initial sequence list of genetic algorithm.

- * - * @return Initial sequence list. - */ - protected initGenes(): GAWrapperArray; - /** - * Try to repack each wrappers to another type. - * - * @param $wrappers Wrappers to repack. - * @return Re-packed wrappers. - */ - protected repack($wrappers: WrapperArray): WrapperArray; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - toXML(): samchon.library.XML; - } -} -declare namespace flex { - class TabNavigator extends React.Component { - render(): JSX.Element; - private handle_change(index, event); - } - class NavigatorContent extends React.Component { - render(): JSX.Element; - } - interface TabNavigatorProps extends React.Props { - selectedIndex?: number; - style?: React.CSSProperties; - } - interface NavigatorContentProps extends React.Props { - label: string; - } -} declare namespace boxologic { /** * A box, trying to pack into a {@link Pallet}. @@ -589,7 +475,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class PackerForm extends samchon.protocol.Entity { + class PackerForm extends protocol.Entity { /** * Form of Instances to pack. */ @@ -609,12 +495,12 @@ declare namespace bws.packer { * @param wrapperArray Type of Wrappers to be used. */ constructor(instanceFormArray: InstanceFormArray, wrapperArray: WrapperArray); - construct(xml: samchon.library.XML): void; + construct(xml: library.XML): void; optimize(): WrapperArray; getInstanceFormArray(): InstanceFormArray; getWrapperArray(): WrapperArray; TAG(): string; - toXML(): samchon.library.XML; + toXML(): library.XML; toPacker(): Packer; } /** @@ -622,12 +508,12 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class InstanceFormArray extends samchon.protocol.EntityArrayCollection { + class InstanceFormArray extends protocol.EntityArrayCollection { /** * Default Constructor. */ constructor(); - createChild(xml: samchon.library.XML): InstanceForm; + createChild(xml: library.XML): InstanceForm; TAG(): string; CHILD_TAG(): string; /** @@ -645,7 +531,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class InstanceForm extends samchon.protocol.Entity { + class InstanceForm extends protocol.Entity { /** * A duplicated Instance. */ @@ -661,7 +547,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - construct(xml: samchon.library.XML): void; + construct(xml: library.XML): void; private createInstance(xml); key(): any; getInstance(): Instance; @@ -679,7 +565,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - toXML(): samchon.library.XML; + toXML(): library.XML; /** *

Repeated {@link instance} to {@link InstanceArray}. * @@ -694,7 +580,7 @@ declare namespace bws.packer { } } declare namespace bws.packer { - class WrapperArray extends samchon.protocol.EntityArrayCollection { + class WrapperArray extends protocol.EntityArrayCollection { /** * Default Constructor. */ @@ -702,7 +588,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - createChild(xml: samchon.library.XML): Wrapper; + createChild(xml: library.XML): Wrapper; /** * Get (calculate) price. */ @@ -756,7 +642,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - interface Instance extends samchon.protocol.IEntity { + interface Instance extends protocol.IEntity { /** * Get name. */ @@ -813,7 +699,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class InstanceArray extends samchon.protocol.EntityArray { + class InstanceArray extends protocol.EntityArray { /** * Default Constructor. */ @@ -821,7 +707,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - createChild(xml: samchon.library.XML): Instance; + createChild(xml: library.XML): Instance; /** * @inheritdoc */ @@ -832,13 +718,113 @@ declare namespace bws.packer { CHILD_TAG(): string; } } +declare namespace bws.packer { + /** + * @brief Packer, a solver of 3d bin packing with multiple wrappers. + * + * @details + *

Packer is a facade class supporting packing operations in user side. You can solve a packing problem + * by constructing Packer class with {@link WrapperArray wrappers} and {@link InstanceArray instances} to + * pack and executing {@link optimize Packer.optimize()} method.

+ * + *

In background side, deducting packing solution, those algorithms are used.

+ * + * + * @author Jeongho Nam + */ + class Packer extends protocol.Entity { + /** + * Candidate wrappers who can contain instances. + */ + protected wrapperArray: WrapperArray; + /** + * Instances trying to pack into the wrapper. + */ + protected instanceArray: InstanceArray; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from members. + * + * @param wrapperArray Candidate wrappers who can contain instances. + * @param instanceArray Instances to be packed into some wrappers. + */ + constructor(wrapperArray: WrapperArray, instanceArray: InstanceArray); + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * Get wrapperArray. + */ + getWrapperArray(): WrapperArray; + /** + * Get instanceArray. + */ + getInstanceArray(): InstanceArray; + /** + *

Deduct + * + */ + optimize(): WrapperArray; + /** + * @brief Initialize sequence list (gene_array). + * + * @details + *

Deducts initial sequence list by such assumption:

+ * + *
    + *
  • Cost of larger wrapper is less than smaller one, within framework of price per volume unit.
  • + *
      + *
    • Wrapper Larger: (price: $1,000, volume: 100cm^3 -> price per volume unit: $10 / cm^3)
    • + *
    • Wrapper Smaller: (price: $700, volume: 50cm^3 -> price per volume unit: $14 / cm^3)
    • + *
    • Larger's cost is less than Smaller, within framework of price per volume unit
    • + *
    + *
+ * + *

Method {@link initGenes initGenes()} constructs {@link WrapperGroup WrapperGroups} corresponding + * with the {@link wrapperArray} and allocates {@link instanceArray instances} to a {@link WrapperGroup}, + * has the smallest cost between containbles.

+ * + *

After executing packing solution by {@link WrapperGroup.optimize WrapperGroup.optimize()}, trying to + * {@link repack re-pack} each {@link WrapperGroup} to another type of {@link Wrapper}, deducts the best + * solution between them. It's the initial sequence list of genetic algorithm.

+ * + * @return Initial sequence list. + */ + protected initGenes(): GAWrapperArray; + /** + * Try to repack each wrappers to another type. + * + * @param $wrappers Wrappers to repack. + * @return Re-packed wrappers. + */ + protected repack($wrappers: WrapperArray): WrapperArray; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} declare namespace bws.packer { /** * A product. * * @author Jeongho Nam */ - class Product extends samchon.protocol.Entity implements Instance { + class Product extends protocol.Entity implements Instance { /** *

Name, key of the Product.

* @@ -921,7 +907,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - toXML(): samchon.library.XML; + toXML(): library.XML; } } declare namespace bws.packer { @@ -937,7 +923,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class Wrap extends samchon.protocol.Entity { + class Wrap extends protocol.Entity { /** * A wrapper wrapping the {@link instance}. */ @@ -962,10 +948,6 @@ declare namespace bws.packer { * Placement orientation of wrapped {@link instance}. */ protected orientation: number; - /** - * - */ - protected color: number; /** * Construct from a Wrapper. * @@ -996,7 +978,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - construct(xml: samchon.library.XML): void; + construct(xml: library.XML): void; /** * Factory method of wrapped Instance. * @@ -1058,11 +1040,11 @@ declare namespace bws.packer { /** * Get width. */ - getWidth(): number; + getLayoutWidth(): number; /** * Get height. */ - getHeight(): number; + getLayoutHeight(): number; /** * Get length. */ @@ -1071,9 +1053,9 @@ declare namespace bws.packer { * Get volume. */ getVolume(): number; - $instanceName: string; - $layoutScale: string; - $position: string; + readonly $instanceName: string; + readonly $layoutScale: string; + readonly $position: string; /** * @inheritdoc */ @@ -1081,19 +1063,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - toXML(): samchon.library.XML; - /** - * Thickness of boundary lines of a shape represents the {@link instance}. - */ - private static BOUNDARY_THICKNESS; - /** - * - * - * @param geometry - * - * @return A shape and its boundary lines as 3D-objects. - */ - toDisplayObjects(geometry: THREE.Geometry): std.Vector; + toXML(): library.XML; } } declare namespace bws.packer { @@ -1102,7 +1072,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class Wrapper extends samchon.protocol.EntityDeque implements Instance { + class Wrapper extends protocol.EntityDeque implements Instance { /** *

Name, key of the Wrapper.

* @@ -1151,11 +1121,10 @@ declare namespace bws.packer { * @param thickness A thickness causes shrinkness on containable volume. */ constructor(name: string, price: number, width: number, height: number, length: number, thickness: number); - construct(xml: samchon.library.XML): void; /** * @inheritdoc */ - createChild(xml: samchon.library.XML): Wrap; + createChild(xml: library.XML): Wrap; /** * Key of a Wrapper is its name. */ @@ -1232,7 +1201,7 @@ declare namespace bws.packer { * @return utilization ratio. */ getUtilization(): number; - equal_to(obj: Wrapper): boolean; + equals(obj: Wrapper): boolean; /** *

Wrapper is enough greater?

* @@ -1272,8 +1241,8 @@ declare namespace bws.packer { $height: string; $length: string; $thickness: string; - $scale: string; - $spaceUtilization: string; + readonly $scale: string; + readonly $spaceUtilization: string; /** * @inheritdoc */ @@ -1289,25 +1258,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - toXML(): samchon.library.XML; - private static scene; - private static renderer; - private static camera; - private static trackball; - private static mouse; - private static BOUNDARY_THICKNESS; - /** - *

Convert to a canvas containing 3D elements.

- * - * @param endIndex - * - * @return A 3D-canvans printing the Wrapper and its children {@link Wrap wrapped} - * {@link Instance instances} with those boundary lines. - */ - toCanvas(endIndex?: number): HTMLCanvasElement; - private static handleMouseMove(event); - private static animate(); - private static render(); + toXML(): library.XML; } } declare namespace bws.packer { @@ -1430,72 +1381,3 @@ declare namespace bws.packer { TAG(): string; } } -declare namespace bws.packer { - abstract class Editor extends React.Component<{ - dataProvider: samchon.protocol.EntityArrayCollection; - }, {}> { - private columns; - private selected_index; - /** - * Default Constructor. - */ - constructor(); - protected abstract createColumns(): AdazzleReactDataGrid.Column[]; - private get_row(index); - private insert_instance(event); - private erase_instances(event); - private handle_data_change(event); - private handle_row_change(event); - private handle_select(event); - render(): JSX.Element; - } -} -declare namespace bws.packer { - interface ItemEditorProps extends React.Props { - application: PackerApplication; - instances: InstanceFormArray; - wrappers: WrapperArray; - } - class ItemEditor extends React.Component { - private clear(event); - private open(event); - private save(event); - private pack(event); - render(): JSX.Element; - } - class InstanceEditor extends Editor { - protected createColumns(): AdazzleReactDataGrid.Column[]; - } - class WrapperEditor extends Editor { - protected createColumns(): AdazzleReactDataGrid.Column[]; - } -} -declare namespace bws.packer { - class PackerApplication extends React.Component<{}, {}> { - private instances; - private wrappers; - private result; - /** - * Default Constructor. - */ - constructor(); - pack(): void; - drawWrapper(wrapper: Wrapper, index?: number): void; - render(): JSX.Element; - static main(): void; - } -} -declare namespace bws.packer { - class ResultViewer extends React.Component { - drawWrapper(wrapper: Wrapper, index?: number): void; - private clear(event); - private open(event); - private save(event); - refresh(): void; - render(): JSX.Element; - } - interface WrapperViewerProps extends React.Props { - application: PackerApplication; - wrappers: WrapperArray; - } -} diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 6e2c883f3a..c3218efb0a 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -811,8 +811,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](jquery.cookie/jquery.cookie.d.ts) [jQuery Cookie Plugin](https://github.com/carhartl/jquery-cookie) by [Roy Goode](https://github.com/RoyGoode), [Ben Lorantfy](https://github.com/BenLorantfy) * [:link:](jquery-cropbox/jquery-cropbox.d.ts) [jQuery cropbox](https://github.com/acornejo/jquery-cropbox) by [Per Kastman](https://github.com/PerKastman) * [:link:](jquery.cycle2/jquery.cycle2.d.ts) [jQuery Cycle2 version (build 20140216)](http://jquery.malsup.com/cycle2) by [Donny Nadolny](https://github.com/dnadolny) -* [:link:](jquery.dataTables/jquery.dataTables.d.ts) [JQuery DataTables](http://www.datatables.net) by [Kiarash Ghiaseddin](https://github.com/Silver-Connection/DefinitelyTyped), [Omid Rad](https://github.com/omidkrad), [Armin Sander](https://github.com/pragmatrix) -* [:link:](datatables-buttons/datatables-buttons.d.ts) [JQuery DataTables Buttons extension](http://datatables.net/extensions/buttons) by [Sam Germano](https://github.com/SammyG4Free) +* [:link:](datatables.net/index.d.ts) [JQuery DataTables](http://www.datatables.net) by [Kiarash Ghiaseddin](https://github.com/Silver-Connection/DefinitelyTyped), [Omid Rad](https://github.com/omidkrad), [Armin Sander](https://github.com/pragmatrix) +* [:link:](datatables.net-buttons/index.d.ts) [JQuery DataTables Buttons extension](http://datatables.net/extensions/buttons) by [Sam Germano](https://github.com/SammyG4Free) * [:link:](jquery.fileupload/jquery.fileupload.d.ts) [jQuery File Upload Plugin](https://github.com/blueimp/jQuery-File-Upload) by [Rob Alarcon](https://github.com/rob-alarcon) * [:link:](jquery.joyride/jquery.joyride.d.ts) [jQuery JoyRide Plugin](https://github.com/zurb/joyride) by [Vincent Bortone](https://github.com/vbortone) * [:link:](jqgrid/jqgrid.d.ts) [jQuery jqgrid Plugin](https://github.com/tonytomov/jqGrid) by [Lokesh Peta](https://github.com/lokeshpeta) diff --git a/README.md b/README.md index fd34c4ae33..23bb52f13c 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,9 @@ Your package should have this structure: | tsconfig.json | This allows you to run `tsc` within the package. | | tslint.json | Enables linting. | -Generate these by running `npm run new-package -- new-package-name`. +Generate these by running `npm run new-package -- --name my-package-name --template module`. +(Other templates are `module-class`, `module-function`, `module-plugin`, `global`, `global-plugin`, and `global-modifying-module`. +This just wraps [dts-gen](https://github.com/Microsoft/dts-gen), so it supports all options from that.) You may edit the `tsconfig.json` to add new files, to add `"target": "es6"` (needed for async functions), to add to `"lib"`, or to add the `"jsx"` compiler option. @@ -167,10 +169,8 @@ If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. (To indicate that a lint rule truly does not apply, use `// tslint:disable:rule-name` or better, `//tslint:disable-next-line:rule-name`.) -Only `.d.ts` files are linted. Test the linter by running `npm run lint -- package-name`. Do not use a globally installed tslint. - ## FAQ #### What exactly is the relationship between this repository and the `@types` packages on NPM? diff --git a/ably/ably-tests.ts b/ably/ably-tests.ts index da4714d21a..026ef48adc 100644 --- a/ably/ably-tests.ts +++ b/ably/ably-tests.ts @@ -1,5 +1,7 @@ import * as Ably from 'ably'; +declare var console: { log(message: any): void }; + const ApiKey = 'appId.keyId:secret'; const client = new Ably.Realtime(ApiKey); const restClient = new Ably.Rest(ApiKey); @@ -7,13 +9,13 @@ const restClient = new Ably.Rest(ApiKey); // Connection // Successful connection: -client.connection.on('connected', function() { +client.connection.on('connected', () => { // successful connection }); // Failed connection: -client.connection.on('failed', function() { +client.connection.on('failed', () => { // failed connection }); @@ -21,14 +23,14 @@ client.connection.on('failed', function() { // Subscribing to a channel var channel = client.channels.get('test'); -channel.subscribe(function(message) { +channel.subscribe(message => { message.name; // 'greeting' message.data; // 'Hello World!' }); // Only certain events: -channel.subscribe('myEvent', function(message) { +channel.subscribe('myEvent', message => { message.name; // 'myEvent' message.data; // 'myData' }); @@ -39,30 +41,30 @@ channel.subscribe('myEvent', function(message) { channel.publish('greeting', 'Hello World!'); // Optionally, you can use a callback to be notified of success or failure -channel.publish('greeting', 'Hello World!', function(err) { - if(err) { +channel.publish('greeting', 'Hello World!', err => { + if (err) { console.log('publish failed with error ' + err); } else { console.log('publish succeeded'); } -}) +}); // Publish several messages at once -channel.publish([{name: 'greeting', data: 'Hello World!'}], function() { }); +channel.publish([{name: 'greeting', data: 'Hello World!'}], () => { }); // Querying the History -channel.history(function(err, messagesPage) { +channel.history((err, messagesPage) => { messagesPage.items; // array of Message messagesPage.items[0].data; // payload for first message messagesPage.items.length; // number of messages in the current page of history messagesPage.hasNext(); // true if there are further pages messagesPage.isLast(); // true if this page is the last page - messagesPage.next(function(nextPage) { nextPage; }); // retrieves the next page as PaginatedResult + messagesPage.next(nextPage => { nextPage; }); // retrieves the next page as PaginatedResult }); // Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history -channel.history({ start: Date.now()-10000, end: Date.now(), limit: 100, direction: 'forwards'}, function(err, messagesPage) { +channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards'}, (err, messagesPage) => { console.log(messagesPage.items.length); }); @@ -70,7 +72,7 @@ channel.history({ start: Date.now()-10000, end: Date.now(), limit: 100, directio // Presence on a channel // Getting presence: -channel.presence.get(function(presenceSet) { +channel.presence.get(presenceSet => { presenceSet; // array of PresenceMessages }); @@ -78,46 +80,47 @@ channel.presence.get(function(presenceSet) { // Entering (and leaving) the presence set: -channel.presence.enter('my status', function(err) { +channel.presence.enter('my status', err => { // now I am entered }); -channel.presence.update('new status', function(err) { +channel.presence.update('new status', err => { // my presence data is updated }); -channel.presence.leave(null, function(err) { +channel.presence.leave(null, err => { // I've left the presence set }); -channel.presence.enterClient('myClientId', 'status', function(err) { +channel.presence.enterClient('myClientId', 'status', err => { }); // and similiarly, updateClient and leaveClient // Querying the Presence History -channel.presence.history(function(err, messagesPage) { // PaginatedResult +channel.presence.history((err, messagesPage) => { // PaginatedResult messagesPage.items; // array of PresenceMessage messagesPage.items[0].data; // payload for first message messagesPage.items.length; // number of messages in the current page of history messagesPage.hasNext(); // true if there are further pages messagesPage.isLast(); // true if this page is the last page - messagesPage.next(function(nextPage) { }); // retrieves the next page as PaginatedResult + messagesPage.next(nextPage => { }); // retrieves the next page as PaginatedResult }); // Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history -channel.history({ start: Date.now()-10000, end: Date.now(), limit: 100, direction: 'forwards' }, function(err, messagesPage) {}); +channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {}); // Symmetrical end-to-end encrypted payloads on a channel -// When a 128 bit or 256 bit key is provided to the library, the data attributes of all messages are encrypted and decrypted automatically using that key. The secret key is never transmitted to Ably. See https://www.ably.io/documentation/realtime/encryption +// When a 128 bit or 256 bit key is provided to the library, the data attributes of all messages are encrypted and decrypted automatically using that key. +// The secret key is never transmitted to Ably. See https://www.ably.io/documentation/realtime/encryption // Generate a random 256-bit key for demonstration purposes (in // practice you need to create one and distribute it to clients yourselves) -Ably.Realtime.Crypto.generateRandomKey(function(err, key) { - var channel = client.channels.get('channelName', { cipher: { key: key } }); +Ably.Realtime.Crypto.generateRandomKey((err, key) => { + var channel = client.channels.get('channelName', { cipher: { key } }); - channel.subscribe(function(message) { + channel.subscribe(message => { message.name; // 'name is not encrypted' message.data; // 'sensitive data is encrypted' }); @@ -127,7 +130,7 @@ Ably.Realtime.Crypto.generateRandomKey(function(err, key) { // You can also change the key on an existing channel using setOptions (which takes a callback which is called after the new encryption settings have taken effect): -channel.setOptions({cipher: {key: ''}}, function() { +channel.setOptions({cipher: {key: ''}}, () => { // New encryption settings are in effect }); @@ -141,56 +144,56 @@ var restChannel = restClient.channels.get('test'); restChannel.publish('greeting', 'Hello World!'); // Optionally, you can use a callback to be notified of success or failure -restChannel.publish('greeting', 'Hello World!', function(err) { - if(err) { +restChannel.publish('greeting', 'Hello World!', err => { + if (err) { console.log('publish failed with error ' + err); } else { console.log('publish succeeded'); } -}) +}); // Publish several messages at once -restChannel.publish([{name: 'greeting', data: 'Hello World!'}], function() {}); +restChannel.publish([{name: 'greeting', data: 'Hello World!'}], () => {}); // Querying the History -restChannel.history(function(err, messagesPage) { +restChannel.history((err, messagesPage) => { messagesPage; // PaginatedResult messagesPage.items; // array of Message messagesPage.items[0].data; // payload for first message messagesPage.items.length; // number of messages in the current page of history messagesPage.hasNext(); // true if there are further pages messagesPage.isLast(); // true if this page is the last page - messagesPage.next(function(nextPage) {}); // retrieves the next page as PaginatedResult + messagesPage.next(nextPage => {}); // retrieves the next page as PaginatedResult }); // Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history -restChannel.history({ start: Date.now()-10000, end: Date.now(), limit: 100, direction: 'forwards' }, function(err, messagesPage) {}); +restChannel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {}); // Presence on a channel -restChannel.presence.get(function(err, presencePage) { // PaginatedResult +restChannel.presence.get((err, presencePage) => { // PaginatedResult presencePage.items; // array of PresenceMessage presencePage.items[0].data; // payload for first message presencePage.items.length; // number of messages in the current page of members presencePage.hasNext(); // true if there are further pages presencePage.isLast(); // true if this page is the last page - presencePage.next(function(nextPage) {}); // retrieves the next page as PaginatedResult + presencePage.next(nextPage => {}); // retrieves the next page as PaginatedResult }); // Querying the Presence History -restChannel.presence.history(function(err, messagesPage) { // PaginatedResult +restChannel.presence.history((err, messagesPage) => { // PaginatedResult messagesPage.items; // array of PresenceMessage messagesPage.items[0].data; // payload for first message messagesPage.items.length; // number of messages in the current page of history messagesPage.hasNext(); // true if there are further pages messagesPage.isLast(); // true if this page is the last page - messagesPage.next(function(nextPage) { }); // retrieves the next page as PaginatedResult + messagesPage.next(nextPage => { }); // retrieves the next page as PaginatedResult }); // Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history -restChannel.history({ start: Date.now()-10000, end: Date.now(), limit: 100, direction: 'forwards' }, function(err, messagesPage) {}); +restChannel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {}); // Generate Token and Token Request @@ -198,7 +201,7 @@ restChannel.history({ start: Date.now()-10000, end: Date.now(), limit: 100, dire // Requesting a token: -client.auth.requestToken(function(err, tokenDetails) { +client.auth.requestToken((err, tokenDetails) => { // tokenDetails is instance of TokenDetails // see https://www.ably.io/documentation/rest/authentication/#token-details for its properties @@ -209,11 +212,11 @@ client.auth.requestToken(function(err, tokenDetails) { // requestToken can take two optional params // tokenParams: https://www.ably.io/documentation/rest/authentication/#token-params // authOptions: https://www.ably.io/documentation/rest/authentication/#auth-options -client.auth.requestToken({}, {}, function(err, tokenDetails) { }); +client.auth.requestToken({}, {}, (err, tokenDetails) => { }); // Creating a token request (for example, on a server in response to a request by a client using the authCallback or authUrl mechanisms): -client.auth.createTokenRequest(function(err, tokenRequest) { +client.auth.createTokenRequest((err, tokenRequest) => { // now send the tokenRequest back to the client, which will // use it to request a token and connect to Ably }); @@ -221,22 +224,22 @@ client.auth.createTokenRequest(function(err, tokenRequest) { // createTokenRequest can take two optional params // tokenParams: https://www.ably.io/documentation/rest/authentication/#token-params // authOptions: https://www.ably.io/documentation/rest/authentication/#auth-options -client.auth.createTokenRequest({}, {}, function(err, tokenRequest) { }); +client.auth.createTokenRequest({}, {}, (err, tokenRequest) => { }); // Fetching your application's stats -client.stats({ limit: 50 }, function(err, statsPage) { // statsPage as PaginatedResult +client.stats({ limit: 50 }, (err, statsPage) => { // statsPage as PaginatedResult statsPage.items; // array of Stats statsPage.items[0].inbound.rest.messages.count; // total messages published over REST statsPage.items.length; // number of stats in the current page of history - statsPage.hasNext(); // true if there are further pages + statsPage.hasNext(); // true if there are wrther pages statsPage.isLast(); // true if this page is the last page - statsPage.next(function(nextPage) {}); // retrieves the next page as PaginatedResult + statsPage.next((nextPage) => {}); // retrieves the next page as PaginatedResult }); // Fetching the Ably service time -client.time({}, function(err, time) {}); // time is in ms since epoch +client.time({}, (err, time) => {}); // time is in ms since epoch // Getting decoded Message objects from JSON var messages = Ably.Realtime.Message.fromEncodedArray([{ id: 'foo' }]); diff --git a/ably/index.d.ts b/ably/index.d.ts index bf69daafc3..a6ea5785ac 100644 --- a/ably/index.d.ts +++ b/ably/index.d.ts @@ -25,7 +25,8 @@ declare namespace ablyLib { type CLOSED = "closed"; type FAILED = "failed"; } - type ConnectionState = ConnectionState.INITIALIZED | ConnectionState.CONNECTED | ConnectionState.CONNECTING | ConnectionState.DISCONNECTED | ConnectionState.SUSPENDED | ConnectionState.CLOSED | ConnectionState.CLOSING | ConnectionState.FAILED; + type ConnectionState = ConnectionState.INITIALIZED | ConnectionState.CONNECTED | ConnectionState.CONNECTING | ConnectionState.DISCONNECTED | + ConnectionState.SUSPENDED | ConnectionState.CLOSED | ConnectionState.CLOSING | ConnectionState.FAILED; namespace ConnectionEvent { type INITIALIZED = "initialized"; @@ -38,7 +39,8 @@ declare namespace ablyLib { type FAILED = "failed"; type UPDATE = "update"; } - type ConnectionEvent = ConnectionEvent.INITIALIZED | ConnectionEvent.CONNECTED | ConnectionEvent.CONNECTING | ConnectionEvent.DISCONNECTED | ConnectionEvent.SUSPENDED | ConnectionEvent.CLOSED | ConnectionEvent.CLOSING | ConnectionEvent.FAILED | ConnectionEvent.UPDATE; + type ConnectionEvent = ConnectionEvent.INITIALIZED | ConnectionEvent.CONNECTED | ConnectionEvent.CONNECTING | ConnectionEvent.DISCONNECTED | + ConnectionEvent.SUSPENDED | ConnectionEvent.CLOSED | ConnectionEvent.CLOSING | ConnectionEvent.FAILED | ConnectionEvent.UPDATE; namespace PresenceAction { type ABSENT = "absent"; diff --git a/ably/tsconfig.json b/ably/tsconfig.json index 0dce6c6c1d..86c7bc0114 100644 --- a/ably/tsconfig.json +++ b/ably/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "ably-tests.ts" ] -} +} \ No newline at end of file diff --git a/abs/tslint.json b/abs/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/abs/tslint.json +++ b/abs/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/accounting/tslint.json b/accounting/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/accounting/tslint.json +++ b/accounting/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/acorn/acorn-tests.ts b/acorn/acorn-tests.ts index fb79d23718..bda6844c84 100644 --- a/acorn/acorn-tests.ts +++ b/acorn/acorn-tests.ts @@ -67,3 +67,6 @@ acorn.getLineInfo('string', 56); acorn.plugins['test'] = function (p: acorn.Parser, config: any) { } + +acorn.tokenizer('console.log("hello world)', {locations: true}).getToken(); +acorn.tokenizer('console.log("hello world)', {locations: true})[Symbol.iterator]().next(); diff --git a/acorn/index.d.ts b/acorn/index.d.ts index 1944abc257..441deb29c3 100644 --- a/acorn/index.d.ts +++ b/acorn/index.d.ts @@ -238,9 +238,12 @@ declare namespace acorn { function parseExpressionAt(input: string, pos?: number, options?: Options): ESTree.Expression; - // todo: here the tokenizer function returns a Parser instance, that is targeting the detail of - // Parser prototype. Someone need this please reade README.md first. - // function tokenizer(options: Options, input: string): Parser; + interface ITokenizer { + getToken() : Token, + [Symbol.iterator](): Iterator + } + + function tokenizer(input: string, options: Options): ITokenizer; let parse_dammit: IParse | undefined; let LooseParser: ILooseParserClass | undefined; diff --git a/amplify-deferred/amplify-deferred-tests.ts b/amplify-deferred/amplify-deferred-tests.ts index a4c7c656c4..5a65dd9dde 100644 --- a/amplify-deferred/amplify-deferred-tests.ts +++ b/amplify-deferred/amplify-deferred-tests.ts @@ -1,5 +1,5 @@ amplify.request({ resourceId: "statusExample1" -}).done(function (data, status) { -}).fail(function (data, status) { -}).always(function (data, status) { }); +}).done((data, status) => { +}).fail((data, status) => { +}).always((data, status) => { }); diff --git a/amplify-deferred/tslint.json b/amplify-deferred/tslint.json index 0f47deabb4..f05741c59b 100644 --- a/amplify-deferred/tslint.json +++ b/amplify-deferred/tslint.json @@ -3,4 +3,4 @@ "rules": { "forbidden-types": false } -} \ No newline at end of file +} diff --git a/amplify/amplify-tests.ts b/amplify/amplify-tests.ts index f844642b8e..edf2988122 100644 --- a/amplify/amplify-tests.ts +++ b/amplify/amplify-tests.ts @@ -7,7 +7,7 @@ import amplify = require("amplify"); // Subscribe and publish with no data -amplify.subscribe("nodataexample", function () { +amplify.subscribe("nodataexample", () => { alert("nodataexample topic published!"); }); @@ -15,24 +15,24 @@ amplify.subscribe("nodataexample", function () { amplify.publish("nodataexample"); -amplify.subscribe("dataexample", function (data) { +amplify.subscribe("dataexample", data => { alert(data.foo); // bar }); amplify.publish("dataexample", { foo: "bar" }); -amplify.subscribe("dataexample2", function (param1, param2) { +amplify.subscribe("dataexample2", (param1, param2) => { alert(param1 + param2); // barbaz }); -//... +// ... amplify.publish("dataexample2", "bar", "baz"); // Subscribe and publish with context and data -amplify.subscribe("datacontextexample", $("p:first"), function (data) { +amplify.subscribe("datacontextexample", $("p:first"), data => { this.text(data.exampleText); // first p element would have "foo bar baz" as text }); @@ -40,11 +40,11 @@ amplify.publish("datacontextexample", { exampleText: "foo bar baz" }); // Subscribe to a topic with high priority -amplify.subscribe("priorityexample", function (data) { +amplify.subscribe("priorityexample", data => { alert(data.foo); }); -amplify.subscribe("priorityexample", function (data) { +amplify.subscribe("priorityexample", data => { if (data.foo === "oops") { return false; } @@ -87,7 +87,7 @@ amplify.request.define("ajaxExample1", "ajax", { }); // later in code -amplify.request("ajaxExample1", function (data) { +amplify.request("ajaxExample1", data => { data.foo; // bar }); @@ -101,21 +101,21 @@ amplify.request.define("ajaxExample2", "ajax", { }); // later in code -amplify.request("ajaxExample2", function (data) { +amplify.request("ajaxExample2", data => { data.foo; // bar }); // a second call will result in pulling from the cache -amplify.request("ajaxExample2", function (data) { +amplify.request("ajaxExample2", data => { data.baz; // qux -}) +}); // Set up and use a RESTful request utilizing Ajax amplify.request.define("ajaxRESTFulExample", "ajax", { url: "/myRestFulApi/{type}/{id}", type: "GET" -}) +}); // later in code amplify.request("ajaxRESTFulExample", @@ -123,7 +123,7 @@ amplify.request("ajaxRESTFulExample", type: "foo", id: "bar" }, - function (data) { + data => { // /myRESTFulApi/foo/bar was the URL used data.foo; // bar } @@ -132,9 +132,9 @@ amplify.request("ajaxRESTFulExample", // POST data with Ajax amplify.request.define("ajaxPostExample", "ajax", { - url: "/myRestFulApi", - type: "POST" - }) + url: "/myRestFulApi", + type: "POST" +}); // later in code amplify.request("ajaxPostExample", @@ -142,7 +142,7 @@ amplify.request("ajaxPostExample", type: "foo", id: "bar" }, - function (data) { + data => { data.foo; // bar } ); @@ -165,7 +165,7 @@ amplify.request("twitter-search", { term: "amplifyjs" } ); amplify.request.define("twitter-mentions", "ajax", { url: "http://search.twitter.com/search.json", dataType: "jsonp", - dataMap: function (data) { + dataMap: data => { return { q: "@" + data.user }; @@ -176,9 +176,9 @@ amplify.request("twitter-mentions", { user: "amplifyjs" }); // Setting up and using decoders -//Example: +// Example: -var appEnvelopeDecoder: amplify.Decoder = function (data, status, xhr, success, error) { +var appEnvelopeDecoder: amplify.Decoder = (data, status, xhr, success, error) => { if (data.status === "success") { success(data.data); } else if (data.status === "fail" || data.status === "error") { @@ -188,7 +188,7 @@ var appEnvelopeDecoder: amplify.Decoder = function (data, status, xhr, success, } }; -//a new decoder can be added to the amplifyDecoders interface +// a new decoder can be added to the amplifyDecoders interface declare module "amplify" { interface Decoders { appEnvelope: amplify.Decoder; @@ -197,7 +197,7 @@ declare module "amplify" { amplify.request.decoders.appEnvelope = appEnvelopeDecoder; -//but you can also just add it via an index +// but you can also just add it via an index amplify.request.decoders['appEnvelopeStr'] = appEnvelopeDecoder; @@ -209,10 +209,10 @@ amplify.request.define("decoderExample", "ajax", { amplify.request({ resourceId: "decoderExample", - success: function (data) { + success(data) { data.foo; // bar }, - error: function (message, level) { + error(message, level) { alert("always handle errors with alerts."); } }); @@ -224,7 +224,7 @@ amplify.request({ amplify.request.define("decoderSingleExample", "ajax", { url: "/myAjaxUrl", type: "POST", - decoder: function (data, status, xhr, success, error) { + decoder(data, status, xhr, success, error) { if (data.status === "success") { success(data.data); } else if (data.status === "fail" || data.status === "error") { @@ -237,10 +237,10 @@ amplify.request.define("decoderSingleExample", "ajax", { amplify.request({ resourceId: "decoderSingleExample", - success: function (data) { + success: data => { data.foo; // bar }, - error: function (message, level) { + error: (message, level) => { alert("always handle errors with alerts."); } }); @@ -250,14 +250,14 @@ amplify.request({ // amplify.request comes with built in support for status.The status parameter appears in the default success or error callbacks when using an ajax definition. amplify.request.define("statusExample1", "ajax", { - //... + // ... }); amplify.request({ resourceId: "statusExample1", - success: function (data, status) { + success: (data, status) => { }, - error: function (data, status) { + error: (data, status) => { } }); diff --git a/amplify/index.d.ts b/amplify/index.d.ts index d0e8d5b620..1e62e57a01 100644 --- a/amplify/index.d.ts +++ b/amplify/index.d.ts @@ -162,7 +162,9 @@ declare namespace amplify { * Publish a message. * topic: The name of the message to publish. * Any additional parameters will be passed to the subscriptions. - * amplify.publish returns a boolean indicating whether any subscriptions returned false. The return value is true if none of the subscriptions returned false, and false otherwise. Note that only one subscription can return false because doing so will prevent additional subscriptions from being invoked. + * amplify.publish returns a boolean indicating whether any subscriptions returned false. + * The return value is true if none of the subscriptions returned false, and false otherwise. + * Note that only one subscription can return false because doing so will prevent additional subscriptions from being invoked. */ publish(topic: string, ...args: any[]): boolean; diff --git a/amplify/tslint.json b/amplify/tslint.json index 2d6cd90f81..fe03bea79d 100644 --- a/amplify/tslint.json +++ b/amplify/tslint.json @@ -4,4 +4,4 @@ "forbidden-types": false, "unified-signatures": false } -} \ No newline at end of file +} diff --git a/amqplib/amqplib-tests.ts b/amqplib/amqplib-tests.ts index b17128653a..24dade85dc 100644 --- a/amqplib/amqplib-tests.ts +++ b/amqplib/amqplib-tests.ts @@ -31,11 +31,11 @@ var anqpAssertExchangeReplies: amqp.Replies.AssertExchange; import amqpcb = require('amqplib/callback_api'); amqpcb.connect('amqp://localhost', (err, connection) => { - if(!err) { + if (!err) { connection.createChannel((err, channel) => { if (!err) { channel.assertQueue('myQueue', {}, (err, ok) => { - if(!err) { + if (!err) { channel.sendToQueue('myQueue', new Buffer(msg)); } }); @@ -45,11 +45,11 @@ amqpcb.connect('amqp://localhost', (err, connection) => { }); amqpcb.connect('amqp://localhost', (err, connection) => { - if(!err) { + if (!err) { connection.createChannel((err, channel) => { if (!err) { channel.assertQueue('myQueue', {}, (err, ok) => { - if(!err) { + if (!err) { channel.consume('myQueue', newMsg => console.log('New Message: ' + newMsg.content.toString())); } }); diff --git a/amqplib/tslint.json b/amqplib/tslint.json index 9bc375c06b..105f5736e6 100644 --- a/amqplib/tslint.json +++ b/amqplib/tslint.json @@ -3,4 +3,4 @@ "rules": { "no-empty-interface": false } -} \ No newline at end of file +} diff --git a/angular-gridster/angular-gridster-tests.ts b/angular-gridster/angular-gridster-tests.ts index 7333a20f4d..7af4908d2d 100644 --- a/angular-gridster/angular-gridster-tests.ts +++ b/angular-gridster/angular-gridster-tests.ts @@ -21,7 +21,7 @@ myApp.run(["gridsterConfig", (gridsterConfig: angular.gridster.GridsterConfig) = gridsterConfig.floating = true; gridsterConfig.swapping = true; gridsterConfig.draggable = { enabled: true}; - gridsterConfig.resizable = { enabled: true, + gridsterConfig.resizable = { enabled: true, handles: ["n", "s", "e", "w", "ne", "se", "sw", "nw"]}; } ]); \ No newline at end of file diff --git a/angular-gridster/tslint.json b/angular-gridster/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/angular-gridster/tslint.json +++ b/angular-gridster/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/angular-oauth2/angular-oauth2-tests.ts b/angular-oauth2/angular-oauth2-tests.ts new file mode 100644 index 0000000000..2b2328d5ee --- /dev/null +++ b/angular-oauth2/angular-oauth2-tests.ts @@ -0,0 +1,10 @@ +import * as angular from 'angular'; + +angular.module('angular-oauth2-test', ['angular-oauth2']) + .config(['OAuthProvider', function(OAuthProvider:angular.oauth2.OAuthProvider){ + OAuthProvider.configure({ + baseUrl: 'https://api.website.com', + clientId: 'CLIENT_ID', + clientSecret: 'CLIENT_SECRET' // optional + }); + }]); \ No newline at end of file diff --git a/angular-oauth2/index.d.ts b/angular-oauth2/index.d.ts new file mode 100644 index 0000000000..e6b9592874 --- /dev/null +++ b/angular-oauth2/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for angular-oauth2 4.1 +// Project: https://github.com/oauthjs/angular-oauth2 +// Definitions by: Antério Vieira +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as angular from 'angular'; + +declare module 'angular' { + export namespace oauth2 { + interface OAuthConfig { + baseUrl: string; + clientId: string; + clientSecret?: string; + grantPath?: string; + revokePath?: string; + } + + interface OAuthProvider { + configure(params: OAuthConfig): OAuthConfig; + } + + interface Data { + username: string; + password: string; + } + + interface OAuth { + isAuthenticated(): boolean; + getAccessToken(data: Data, options?: any): angular.IPromise; + getRefreshToken(data?: Data, options?: any): angular.IPromise; + revokeToken(data?: Data, options?: any): angular.IPromise; + } + + interface OAuthTokenConfig { + name: string; + options: any; + } + + interface OAuthTokenOptions { + secure: boolean; + } + + interface OAuthTokenProvider { + configure(params: OAuthTokenConfig): OAuthTokenConfig; + } + + } +} + diff --git a/angular-oauth2/tsconfig.json b/angular-oauth2/tsconfig.json new file mode 100644 index 0000000000..717721bf79 --- /dev/null +++ b/angular-oauth2/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "angular-oauth2-tests.ts" + ] +} diff --git a/gaea-model/tslint.json b/angular-oauth2/tslint.json similarity index 100% rename from gaea-model/tslint.json rename to angular-oauth2/tslint.json diff --git a/angular-translate/index.d.ts b/angular-translate/index.d.ts index 19e1962fab..3b911ba313 100644 --- a/angular-translate/index.d.ts +++ b/angular-translate/index.d.ts @@ -51,8 +51,8 @@ declare module 'angular' { cloakClassName(name: string): ITranslateProvider; fallbackLanguage(langKey?: string): string; fallbackLanguage(langKey?: string[]): string; - instant(translationId: string, interpolateParams?: any, interpolationId?: string): string; - instant(translationId: string[], interpolateParams?: any, interpolationId?: string): { [key: string]: string }; + instant(translationId: string, interpolateParams?: any, interpolationId?: string, forceLanguage?: string, sanitizeStrategy?: string): string; + instant(translationId: string[], interpolateParams?: any, interpolationId?: string, forceLanguage?: string, sanitizeStrategy?: string): { [key: string]: string }; isPostCompilingEnabled(): boolean; preferredLanguage(langKey?: string): string; proposedLanguage(): string; diff --git a/angular-ui-router/angular-ui-router-tests.ts b/angular-ui-router/angular-ui-router-tests.ts index 38ddcca26b..174c319f97 100644 --- a/angular-ui-router/angular-ui-router-tests.ts +++ b/angular-ui-router/angular-ui-router-tests.ts @@ -143,7 +143,7 @@ class UrlLocatorTestService implements IUrlLocatorTestService { private $state: ng.ui.IStateService ) { $rootScope.$on("$locationChangeSuccess", (event: ng.IAngularEvent) => this.onLocationChangeSuccess(event)); - $rootScope.$on('$stateNotFound', (event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) => + $rootScope.$on('$stateNotFound', (event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) => this.onStateNotFound(event, unfoundState, fromState, fromParams)); } @@ -157,8 +157,8 @@ class UrlLocatorTestService implements IUrlLocatorTestService { // Note that we do not concern ourselves with what to do if this request fails, // because if it fails, the web page will be redirected away to the login screen. - this.$http({ url: "/api/me", method: "GET" }).success((user: any) => { - this.currentUser = user; + this.$http({ url: "/api/me", method: "GET" }).then((response: ng.IHttpPromiseCallbackArg) => { + this.currentUser = response.data; // sync the ui-state with the location in the browser, which effectively // restarts the state change that was stopped previously @@ -166,14 +166,14 @@ class UrlLocatorTestService implements IUrlLocatorTestService { }); } } - + private onStateNotFound(event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) { var unfoundTo: string = unfoundState.to; var unfoundToParams: {} = unfoundState.toParams; - var unfoundOptions: ng.ui.IStateOptions = unfoundState.options + var unfoundOptions: ng.ui.IStateOptions = unfoundState.options } private stateServiceTest() { diff --git a/angular-wizard/index.d.ts b/angular-wizard/index.d.ts index 862a6e3ae8..81af2e80c7 100644 --- a/angular-wizard/index.d.ts +++ b/angular-wizard/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mgonto/angular-wizard // Definitions by: Marko Jurisic , Ronald Wildenberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as angular from 'angular'; diff --git a/angular/angular-tests.ts b/angular/angular-tests.ts index cca4dfc420..4e1f33ce47 100644 --- a/angular/angular-tests.ts +++ b/angular/angular-tests.ts @@ -19,19 +19,19 @@ class AuthService { * Required by HTTP interceptor. * Function is attached to provider to be invisible for regular users of this service. */ - pushToBuffer = function(config: ng.IRequestConfig, deferred: ng.IDeferred) { + pushToBuffer = (config: ng.IRequestConfig, deferred: ng.IDeferred) => { this.buffer.push({ config, deferred }); - }; + } $get = [ - '$rootScope', '$injector', function($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) { - let $http: ng.IHttpService; //initialized later because of circular dependency problem + '$rootScope', '$injector', ($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) => { + let $http: ng.IHttpService; // initialized later because of circular dependency problem function retry(config: ng.IRequestConfig, deferred: ng.IDeferred) { $http = $http || $injector.get('$http'); - $http(config).then(function(response) { + $http(config).then(response => { deferred.resolve(response); }); } @@ -49,7 +49,7 @@ class AuthService { retryAll(); } }; - } as any + } ]; } @@ -61,13 +61,13 @@ angular.module('http-auth-interceptor', []) * $http interceptor. * On 401 response - it stores the request and broadcasts 'event:angular-auth-loginRequired'. */ - .config(['$httpProvider', 'authServiceProvider', function($httpProvider: ng.IHttpProvider, authServiceProvider: any) { + .config(['$httpProvider', 'authServiceProvider', ($httpProvider: ng.IHttpProvider, authServiceProvider: any) => { $httpProvider.defaults.headers.common = {Authorization: 'Bearer token'}; $httpProvider.defaults.headers.get['Authorization'] = 'Bearer token'; - $httpProvider.defaults.headers.post['Authorization'] = function(config: ng.IRequestConfig): string { return 'Bearer token'; }; + $httpProvider.defaults.headers.post['Authorization'] = (config: ng.IRequestConfig) => 'Bearer token'; - const interceptor = ['$rootScope', '$q', function($rootScope: ng.IScope, $q: ng.IQService) { + const interceptor = ['$rootScope', '$q', ($rootScope: ng.IScope, $q: ng.IQService) => { function success(response: ng.IHttpPromiseCallbackArg) { return response; } @@ -83,13 +83,10 @@ angular.module('http-auth-interceptor', []) return $q.reject(response); } - return function(promise: ng.IHttpPromise) { - return promise.then(success, error); - }; - - } as any]; + return (promise: ng.IHttpPromise) => promise.then(success, error); + }]; $httpProvider.interceptors.push(interceptor); - } as any]); + }]); namespace HttpAndRegularPromiseTests { interface Person { @@ -108,11 +105,6 @@ namespace HttpAndRegularPromiseTests { } function someController($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) { - $http.get('http://somewhere/some/resource') - .success((data: ExpectedResponse) => { - $scope.person = data; - }); - $http.get('http://somewhere/some/resource') .then((response: ng.IHttpPromiseCallbackArg) => { // typing lost, so something like @@ -156,21 +148,6 @@ namespace HttpAndRegularPromiseTests { $scope.nothing = 'really nothing'; }); } - - // Test that we can pass around a type-checked success/error Promise Callback - function anotherController($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) { - function buildFooData(): ng.IRequestShortcutConfig { - return {}; - } - - function doFoo(callback: ng.IHttpPromiseCallback) { - $http - .get('/foo', buildFooData()) - .success(callback); - }; - - doFoo((data: any) => console.log(data)); - }; } // Test for AngularJS Syntax @@ -181,8 +158,8 @@ namespace My.Namespace { // IModule Registering Test let mod = angular.module('tests', []); -mod.controller('name', function($scope: ng.IScope) { }); -mod.controller('name', ['$scope', function($scope: ng.IScope) { }]); +mod.controller('name', ($scope: ng.IScope) => { }); +mod.controller('name', ['$scope', ($scope: ng.IScope) => { }]); mod.controller('name', class { // Uncommenting the next line should lead to a type error because this signature isn't compatible // with the signature of the `$onChanges` hook: @@ -190,8 +167,8 @@ mod.controller('name', class { }); mod.controller({ MyCtrl: class{}, - MyCtrl2: function() {}, // tslint:disable-line:object-literal-shorthand - MyCtrl3: ['$fooService', function($fooService: any) { }] + MyCtrl2() {}, + MyCtrl3: ['$fooService', ($fooService: any) => { }] }); mod.directive('myDirectiveA', ($rootScope: ng.IRootScopeService) => { return (scope, el, attrs) => { @@ -203,7 +180,7 @@ mod.directive('myDirectiveA', ($rootScope: ng.IRootScopeService) => { scope.$watch(() => foo, () => el.text(foo)); }; }); -mod.directive('myDirectiveB', ['$rootScope', function($rootScope: ng.IRootScopeService) { +mod.directive('myDirectiveB', ['$rootScope', ($rootScope: ng.IRootScopeService) => { return { link(scope, el, attrs) { el.click(e => { @@ -220,28 +197,28 @@ mod.directive({ template: 'my-bar-dir.tpl.html' })] }); -mod.factory('name', function($scope: ng.IScope) { }); -mod.factory('name', ['$scope', function($scope: ng.IScope) { }]); +mod.factory('name', ($scope: ng.IScope) => {}); +mod.factory('name', ['$scope', ($scope: ng.IScope) => {}]); mod.factory({ - name1: function(foo: any) { }, // tslint:disable-line:object-literal-shorthand - name2: ['foo', function(foo: any) { }] + name1(foo: any) {}, + name2: ['foo', (foo: any) => {}] }); -mod.filter('name', function($scope: ng.IScope) { }); -mod.filter('name', ['$scope', function($scope: ng.IScope) { }]); +mod.filter('name', ($scope: ng.IScope) => {}); +mod.filter('name', ['$scope', ($scope: ng.IScope) => {}]); mod.filter({ - name1: function(foo: any) { }, // tslint:disable-line:object-literal-shorthand - name2: ['foo', function(foo: any) { }] + name1(foo: any) {}, + name2: ['foo', (foo: any) => {}] }); -mod.provider('name', function($scope: ng.IScope) { return { $get: () => { } }; }); +mod.provider('name', ($scope: ng.IScope) => ({ $get: () => { } })); mod.provider('name', TestProvider); -mod.provider('name', ['$scope', function($scope: ng.IScope) { } as any]); +mod.provider('name', ['$scope', ($scope: ng.IScope) => {}]); mod.provider(My.Namespace); -mod.service('name', function($scope: ng.IScope) { }); -mod.service('name', ['$scope', function($scope: ng.IScope) { } as any]); +mod.service('name', ($scope: ng.IScope) => {}); +mod.service('name', ['$scope', ($scope: ng.IScope) => {}]); mod.service({ MyCtrl: class{}, - MyCtrl2: function() {}, // tslint:disable-line:object-literal-shorthand - MyCtrl3: ['$fooService', function($fooService: any) { }] + MyCtrl2: () => {}, // tslint:disable-line:object-literal-shorthand + MyCtrl3: ['$fooService', ($fooService: any) => {}] }); mod.constant('name', 23); mod.constant('name', '23'); @@ -249,8 +226,8 @@ mod.constant(My.Namespace); mod.value('name', 23); mod.value('name', '23'); mod.value(My.Namespace); -mod.decorator('name', function($scope: ng.IScope) {}); -mod.decorator('name', ['$scope', function($scope: ng.IScope) {} as any]); +mod.decorator('name', ($scope: ng.IScope) => {}); +mod.decorator('name', ['$scope', ($scope: ng.IScope) => {}]); class TestProvider implements ng.IServiceProvider { constructor(private $scope: ng.IScope) { @@ -262,7 +239,7 @@ class TestProvider implements ng.IServiceProvider { // QProvider tests angular.module('qprovider-test', []) - .config(['$qProvider', function($qProvider: ng.IQProvider) { + .config(['$qProvider', ($qProvider: ng.IQProvider) => { const provider: ng.IQProvider = $qProvider.errorOnUnhandledRejections(false); const currentValue: boolean = $qProvider.errorOnUnhandledRejections(); }]); @@ -298,7 +275,7 @@ foo.then((x) => { }).then((x) => { // Object is inferred here x.a = 123; - //Try a promise + // Try a promise var y: ng.IPromise; var condition: boolean; return condition ? y : x.a; // IPromise | T, both are good for the 1st arg of .then() @@ -441,10 +418,10 @@ httpFoo.then((x) => { x.toFixed(); }); -httpFoo.success((data, status, headers, config) => { - const h = headers('test'); +httpFoo.then((response: ng.IHttpPromiseCallbackArg) => { + const h = response.headers('test'); h.charAt(0); - const hs = headers(); + const hs = response.headers(); hs['content-type'].charAt(1); }); @@ -557,7 +534,6 @@ namespace TestPromise { (reason) => anyOf3(reject, tresult, tresultPromise) )); - assertPromiseType>(promise.then((result) => tresultHttpPromise)); assertPromiseType(promise.then((result) => result, (any) => tother)); @@ -611,10 +587,10 @@ namespace TestPromise { function test_angular_forEach() { const values: { [key: string]: string } = { name: 'misko', gender: 'male' }; const log: string[] = []; - angular.forEach(values, function(value, key) { + angular.forEach(values, (value, key) => { this.push(key + ': ' + value); }, log); - //expect(log).toEqual(['name: misko', 'gender: male']); + // expect(log).toEqual(['name: misko', 'gender: male']); } // angular.element() tests @@ -729,19 +705,12 @@ angular.module('AnotherSampleDirective', []).directive('myDirective', ['$interpo const defer = $q.defer(); defer.reject(); defer.resolve(); - defer.promise.then(function(d) { - return d; - }).then(function(): any { - return null; - }, function(): any { - return null; - }) - .catch((): any => { - return null; - }) - .finally((): any => { - return null; - }); + defer.promise.then(d => d) + .then( + (): any => null, + (): any => null) + .catch((): any => null) + .finally((): any => null); let promise = new $q((resolve) => { resolve(); }); @@ -761,39 +730,39 @@ angular.module('AnotherSampleDirective', []).directive('myDirective', ['$interpo // test from https://docs.angularjs.org/guide/directive angular.module('docsSimpleDirective', []) - .controller('Controller', ['$scope', function($scope: any) { + .controller('Controller', ['$scope', ($scope: any) => { $scope.customer = { name: 'Naomi', address: '1600 Amphitheatre' }; }]) - .directive('myCustomer', function() { + .directive('myCustomer', () => { return { template: 'Name: {{customer.name}} Address: {{customer.address}}' }; }); angular.module('docsTemplateUrlDirective', []) - .controller('Controller', ['$scope', function($scope: any) { + .controller('Controller', ['$scope', ($scope: any) => { $scope.customer = { name: 'Naomi', address: '1600 Amphitheatre' }; }]) - .directive('myCustomer', function() { + .directive('myCustomer', () => { return { templateUrl: 'my-customer.html' }; }); angular.module('docsRestrictDirective', []) - .controller('Controller', ['$scope', function($scope: any) { + .controller('Controller', ['$scope', ($scope: any) => { $scope.customer = { name: 'Naomi', address: '1600 Amphitheatre' }; }]) - .directive('myCustomer', function() { + .directive('myCustomer', () => { return { restrict: 'E', templateUrl: 'my-customer.html' @@ -801,19 +770,19 @@ angular.module('docsRestrictDirective', []) }); angular.module('docsScopeProblemExample', []) - .controller('NaomiController', ['$scope', function($scope: any) { + .controller('NaomiController', ['$scope', ($scope: any) => { $scope.customer = { name: 'Naomi', address: '1600 Amphitheatre' }; }]) - .controller('IgorController', ['$scope', function($scope: any) { + .controller('IgorController', ['$scope', ($scope: any) => { $scope.customer = { name: 'Igor', address: '123 Somewhere' }; }]) - .directive('myCustomer', function() { + .directive('myCustomer', () => { return { restrict: 'E', templateUrl: 'my-customer.html' @@ -821,11 +790,11 @@ angular.module('docsScopeProblemExample', []) }); angular.module('docsIsolateScopeDirective', []) - .controller('Controller', ['$scope', function($scope: any) { + .controller('Controller', ['$scope', ($scope: any) => { $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; $scope.igor = { name: 'Igor', address: '123 Somewhere' }; }]) - .directive('myCustomer', function() { + .directive('myCustomer', () => { return { restrict: 'E', scope: { @@ -836,11 +805,11 @@ angular.module('docsIsolateScopeDirective', []) }); angular.module('docsIsolationExample', []) - .controller('Controller', ['$scope', function($scope: any) { + .controller('Controller', ['$scope', ($scope: any) => { $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; }]) - .directive('myCustomer', function() { + .directive('myCustomer', () => { return { restrict: 'E', scope: { @@ -851,10 +820,10 @@ angular.module('docsIsolationExample', []) }); angular.module('docsTimeDirective', []) - .controller('Controller', ['$scope', function($scope: any) { + .controller('Controller', ['$scope', ($scope: any) => { $scope.format = 'M/d/yy h:mm:ss a'; }]) - .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any) { + .directive('myCurrentTime', ['$interval', 'dateFilter', ($interval: any, dateFilter: any) => { return { link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) { @@ -865,17 +834,17 @@ angular.module('docsTimeDirective', []) element.text(dateFilter(new Date(), format)); } - scope.$watch(attrs['myCurrentTime'], function(value: any) { + scope.$watch(attrs['myCurrentTime'], (value: any) => { format = value; updateTime(); }); - element.on('$destroy', function() { + element.on('$destroy', () => { $interval.cancel(timeoutId); }); // start the UI update process; save the timeoutId for canceling - timeoutId = $interval(function() { + timeoutId = $interval(() => { updateTime(); // update DOM }, 1000); } @@ -883,10 +852,10 @@ angular.module('docsTimeDirective', []) }]); angular.module('docsTransclusionDirective', []) - .controller('Controller', ['$scope', function($scope: any) { + .controller('Controller', ['$scope', ($scope: any) => { $scope.name = 'Tobias'; }]) - .directive('myDialog', function() { + .directive('myDialog', () => { return { restrict: 'E', transclude: true, @@ -895,10 +864,10 @@ angular.module('docsTransclusionDirective', []) }); angular.module('docsTransclusionExample', []) - .controller('Controller', ['$scope', function($scope: any) { + .controller('Controller', ['$scope', ($scope: any) => { $scope.name = 'Tobias'; }]) - .directive('myDialog', function() { + .directive('myDialog', () => { return { restrict: 'E', transclude: true, @@ -911,16 +880,16 @@ angular.module('docsTransclusionExample', []) }); angular.module('docsIsoFnBindExample', []) - .controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) { + .controller('Controller', ['$scope', '$timeout', ($scope: any, $timeout: any) => { $scope.name = 'Tobias'; - $scope.hideDialog = function() { + $scope.hideDialog = () => { $scope.dialogIsHidden = true; - $timeout(function() { + $timeout(() => { $scope.dialogIsHidden = false; }, 2000); }; }]) - .directive('myDialog', function() { + .directive('myDialog', () => { return { restrict: 'E', transclude: true, @@ -932,8 +901,8 @@ angular.module('docsIsoFnBindExample', []) }); angular.module('dragModule', []) - .directive('myDraggable', ['$document', function($document: any) { - return function(scope: any, element: any, attr: any) { + .directive('myDraggable', ['$document', ($document: any) => { + return (scope: any, element: any, attr: any) => { let startX = 0, startY = 0, x = 0, y = 0; element.css({ @@ -943,7 +912,7 @@ angular.module('dragModule', []) cursor: 'pointer' }); - element.on('mousedown', function(event: any) { + element.on('mousedown', (event: any) => { // Prevent default dragging of selected content event.preventDefault(); startX = event.pageX - x; @@ -969,7 +938,7 @@ angular.module('dragModule', []) }]); angular.module('docsTabsExample', []) - .directive('myTabs', function() { + .directive('myTabs', () => { return { restrict: 'E', transclude: true, @@ -977,14 +946,14 @@ angular.module('docsTabsExample', []) controller($scope: ng.IScope) { const panes: any = $scope['panes'] = []; - $scope['select'] = function(pane: any) { - angular.forEach(panes, function(pane: any) { + $scope['select'] = (pane: any) => { + angular.forEach(panes, (pane: any) => { pane.selected = false; }); pane.selected = true; }; - this.addPane = function(pane: any) { + this.addPane = (pane: any) => { if (panes.length === 0) { $scope['select'](pane); } @@ -994,7 +963,7 @@ angular.module('docsTabsExample', []) templateUrl: 'my-tabs.html' }; }) - .directive('myPane', function() { + .directive('myPane', () => { return { require: '^myTabs', restrict: 'E', @@ -1010,7 +979,7 @@ angular.module('docsTabsExample', []) }); angular.module('multiSlotTranscludeExample', []) - .directive('dropDownMenu', function() { + .directive('dropDownMenu', () => { return { transclude: { button: 'button', @@ -1068,15 +1037,15 @@ interface ICopyExampleScope { } angular.module('copyExample', []) - .controller('ExampleController', ['$scope', function($scope: ICopyExampleScope) { + .controller('ExampleController', ['$scope', ($scope: ICopyExampleScope) => { $scope.master = { }; - $scope.update = function(user) { + $scope.update = user => { // Example with 1 argument $scope.master = angular.copy(user); }; - $scope.reset = function() { + $scope.reset = () => { // Example with 2 arguments angular.copy($scope.master, $scope.user); }; @@ -1149,7 +1118,7 @@ function NgModelControllerTyping() { var $q: angular.IQService; // See https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$validators - ngModel.$validators['validCharacters'] = function(modelValue, viewValue) { + ngModel.$validators['validCharacters'] = (modelValue, viewValue) => { const value = modelValue || viewValue; return /[0-9]+/.test(value) && /[a-z]+/.test(value) && @@ -1157,7 +1126,7 @@ function NgModelControllerTyping() { /\W+/.test(value); }; - ngModel.$asyncValidators['uniqueUsername'] = function(modelValue, viewValue) { + ngModel.$asyncValidators['uniqueUsername'] = (modelValue, viewValue) => { const value = modelValue || viewValue; return $http.get('/api/users/' + value). then(function resolved() { @@ -1271,8 +1240,8 @@ function parseWithParams() { function doBootstrap(element: Element | JQuery, mode: string): ng.auto.IInjectorService { if (mode === 'debug') { - return angular.bootstrap(element, ['main', function($provide: ng.auto.IProvideService) { - $provide.decorator('$rootScope', function($delegate: ng.IRootScopeService) { + return angular.bootstrap(element, ['main', ($provide: ng.auto.IProvideService) => { + $provide.decorator('$rootScope', ($delegate: ng.IRootScopeService) => { $delegate['debug'] = true; }); }, 'debug-helpers'], { @@ -1292,12 +1261,12 @@ function testIHttpParamSerializerJQLikeProvider() { } function anyOf2(v1: T1, v2: T2) { - return Math.random() < 1/2 ? v1 : v2; + return Math.random() < 0.5 ? v1 : v2; } function anyOf3(v1: T1, v2: T2, v3: T3) { const rnd = Math.random(); - return rnd < 1/3 ? v1 : rnd < 2/3 ? v2 : v3; + return rnd < 0.33 ? v1 : rnd < 0.66 ? v2 : v3; } function toPromise(val: T): ng.IPromise { diff --git a/angular/index.d.ts b/angular/index.d.ts index 099ac2fc27..bbbbdb021a 100644 --- a/angular/index.d.ts +++ b/angular/index.d.ts @@ -411,8 +411,8 @@ declare namespace angular { $invalid: boolean; } - //Allows tuning how model updates are done. - //https://docs.angularjs.org/api/ng/directive/ngModelOptions + // Allows tuning how model updates are done. + // https://docs.angularjs.org/api/ng/directive/ngModelOptions interface INgModelOptions { updateOn?: string; debounce?: any; @@ -1192,7 +1192,7 @@ declare namespace angular { */ size: number; - //...: any additional properties from the options object when creating the cache. + // ...: any additional properties from the options object when creating the cache. }; /** @@ -1505,18 +1505,6 @@ declare namespace angular { } interface IHttpPromise extends IPromise> { - /** - * The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. - * If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error. - * @deprecated - */ - success?(callback: IHttpPromiseCallback): IHttpPromise; - /** - * The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. - * If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error. - * @deprecated - */ - error?(callback: IHttpPromiseCallback): IHttpPromise; } // See the jsdoc for transformData() at https://github.com/angular/angular.js/blob/master/src/ng/http.js#L228 @@ -2047,7 +2035,7 @@ declare namespace angular { declare global { interface JQuery { // TODO: events, how to define? - //$destroy + // $destroy find(element: any): JQuery; find(obj: JQuery): JQuery; diff --git a/angular/tslint.json b/angular/tslint.json index 75f86620b4..7ba374959e 100644 --- a/angular/tslint.json +++ b/angular/tslint.json @@ -1,20 +1,33 @@ { - "extends": "../tslint.json", - "rules": { - "class-name": true, - "curly": true, - "no-consecutive-blank-lines": true, - "no-shadowed-variable": true, - "quotemark": [true, "single"], - "align": true, - "callable-types": false, - "forbidden-types": false, - "indent": [true, "spaces"], - "interface-name": false, - "linebreak-style": [true, "LF"], - "no-empty-interface": false, - "unified-signatures": false, - "variable-name": [true, "check-format"], - "void-return": false - } + "extends": "../tslint.json", + "rules": { + "class-name": true, + "curly": true, + "max-line-length": false, + "no-consecutive-blank-lines": true, + "no-shadowed-variable": true, + "quotemark": [ + true, + "single" + ], + "align": true, + "callable-types": false, + "forbidden-types": false, + "indent": [ + true, + "spaces" + ], + "interface-name": false, + "linebreak-style": [ + true, + "LF" + ], + "no-empty-interface": false, + "unified-signatures": false, + "variable-name": [ + true, + "check-format" + ], + "void-return": false + } } diff --git a/apex.js/tslint.json b/apex.js/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/apex.js/tslint.json +++ b/apex.js/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/applicationinsights-js/applicationinsights-js-tests.ts b/applicationinsights-js/applicationinsights-js-tests.ts index f77bab2b0a..06a7d06bc5 100644 --- a/applicationinsights-js/applicationinsights-js-tests.ts +++ b/applicationinsights-js/applicationinsights-js-tests.ts @@ -1,4 +1,3 @@ - // More samples on: https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md var config: Microsoft.ApplicationInsights.IConfig = { @@ -24,7 +23,11 @@ var config: Microsoft.ApplicationInsights.IConfig = { disableCorrelationHeaders: true, disableFlushOnBeforeUnload: false, enableSessionStorageBuffer: false, - cookieDomain: "" + cookieDomain: "", + isCookieUseDisabled: true, + isRetryDisabled: true, + isPerfAnalyzerEnabled: true, + isStorageUseDisabled: true }; var appInsights: Microsoft.ApplicationInsights.IAppInsights = { @@ -35,17 +38,17 @@ var appInsights: Microsoft.ApplicationInsights.IAppInsights = { startTrackPage(name?: string) { return null; }, stopTrackPage(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, trackPageView(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, duration?: number) { return null; }, - startTrackEvent(name: string) { return null }, - stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null }, - trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null }, - trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string) { return null }, - trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null }, - trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null }, - trackTrace(message: string, properties?: { [name: string]: string; }) { return null }, - flush() { return null }, - setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string) { return null }, - clearAuthenticatedUserContext() { return null }, - _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error) { return null } + startTrackEvent(name: string) { return null; }, + stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, + trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, + trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number) { return null; }, + trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null; }, + trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null; }, + trackTrace(message: string, properties?: { [name: string]: string; }) { return null; }, + flush() { return null; }, + setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string) { return null; }, + clearAuthenticatedUserContext() { return null; }, + _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error) { return null; } }; // trackPageView @@ -75,6 +78,9 @@ appInsights.trackException(new Error("sample error"), "handledAt", null, null); appInsights.trackTrace("message"); appInsights.trackTrace("message", null); +// trackDependency +appInsights.trackDependency("id", "POST", "http://example.com/test/abc", "/test/abc", null, true, null); + // flush appInsights.flush(); diff --git a/applicationinsights-js/index.d.ts b/applicationinsights-js/index.d.ts index ba154e5fe6..c032919618 100644 --- a/applicationinsights-js/index.d.ts +++ b/applicationinsights-js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ApplicationInsights-JS v0.23.2 +// Type definitions for ApplicationInsights-JS 1.0 // Project: https://github.com/Microsoft/ApplicationInsights-JS // Definitions by: Kamil Szostak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -323,7 +323,7 @@ declare module Microsoft.ApplicationInsights.Telemetry { /** * Constructs a new instance of the EventTelemetry object */ - constructor(name: string, properties?: Object, measurements?: Object); + constructor(name: string, properties?: any, measurements?: any); } class Exception implements Microsoft.ApplicationInsights.ISerializable { @@ -348,7 +348,7 @@ declare module Microsoft.ApplicationInsights.Telemetry { /** * Constructs a new isntance of the ExceptionTelemetry object */ - constructor(exception: Error, handledAt?: string, properties?: Object, measurements?: Object, severityLevel?: AI.SeverityLevel); + constructor(exception: Error, handledAt?: string, properties?: any, measurements?: any, severityLevel?: AI.SeverityLevel); /** * Creates a simple exception with 1 stack frame. Useful for manual constracting of exception. */ @@ -369,7 +369,7 @@ declare module Microsoft.ApplicationInsights.Telemetry { /** * Constructs a new instance of the MetricTelemetry object */ - constructor(name: string, value: number, count?: number, min?: number, max?: number, properties?: Object); + constructor(name: string, value: number, count?: number, min?: number, max?: number, properties?: any); } class PageView extends AI.PageViewData implements Microsoft.ApplicationInsights.ISerializable { @@ -477,7 +477,7 @@ declare module Microsoft.ApplicationInsights.Telemetry { /** * Constructs a new instance of the MetricTelemetry object */ - constructor(message: string, properties?: Object); + constructor(message: string, properties?: any); } } @@ -567,8 +567,12 @@ declare module Microsoft.ApplicationInsights { disableCorrelationHeaders?: boolean; disableFlushOnBeforeUnload?: boolean; enableSessionStorageBuffer?: boolean; + isCookieUseDisabled?: boolean; cookieDomain?: string; + isRetryDisabled?: boolean; + isPerfAnalyzerEnabled?: boolean; url?: string; + isStorageUseDisabled?: boolean; } /** @@ -657,7 +661,7 @@ declare module Microsoft.ApplicationInsights { interface IAppInsights { config: IConfig; context: ITelemetryContext; - queue: (() => void)[]; + queue: Array<() => void>; /** * Starts timing how long the user views a page or other item. Call this when the page opens. * This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes. @@ -717,16 +721,16 @@ declare module Microsoft.ApplicationInsights { [name: string]: number; }): any; /** - * Log an AJAX request - * @param id Event id - * @param absoluteUrl Full url - * @param pathName Leave this parameter blank - * @param totalTime Total time it took for AJAX request to complete - * @param success Whether AJAX request succeeded or failed - * @param resultCode Result code returned from AJAX call - * @param method HTTP verb that was used (GET, POST) - */ - trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string): any; + * Log a dependency call + * @param id unique id, this is used by the backend o correlate server requests. Use Util.newId() to generate a unique Id. + * @param method represents request verb (GET, POST, etc.) + * @param absoluteUrl absolute url used to make the dependency request + * @param pathName the path part of the absolute url + * @param totalTime total request time + * @param success indicates if the request was sessessful + * @param resultCode response code returned by the dependency request + */ + trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number): any; /** * Log an exception you have caught. * @param exception An Error from a catch clause, or the string error message. @@ -755,7 +759,7 @@ declare module Microsoft.ApplicationInsights { /** * Log a diagnostic message. * @param message A message string - * @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty. + * @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty. */ trackTrace(message: string, properties?: { [name: string]: string; @@ -776,7 +780,7 @@ declare module Microsoft.ApplicationInsights { * Clears the authenticated user id and the account id from the user context. */ clearAuthenticatedUserContext(): any; - downloadAndSetup?(config: Microsoft.ApplicationInsights.IConfig): void; + downloadAndSetup?(config: Microsoft.ApplicationInsights.IConfig): any; /** * The custom error handler for Application Insights * @param {string} message - The error message diff --git a/applicationinsights-js/tslint.json b/applicationinsights-js/tslint.json new file mode 100644 index 0000000000..119a5839d0 --- /dev/null +++ b/applicationinsights-js/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "../tslint.json", + "rules": { + "interface-name": [ false ], + "no-internal-module": false, + "no-single-declare-module": false + } +} \ No newline at end of file diff --git a/arcgis-rest-api/index.d.ts b/arcgis-rest-api/index.d.ts index 2b28b32fac..65a02a4367 100644 --- a/arcgis-rest-api/index.d.ts +++ b/arcgis-rest-api/index.d.ts @@ -135,7 +135,8 @@ export type esriGeometryType = "esriGeometryPoint" | "esriGeometryMultipoint" | export type Color = [number, number, number, number]; export type SimpleMarkerSymbolStyle = "esriSMSCircle" | "esriSMSCross" | "esriSMSDiamond" | "esriSMSSquare" | "esriSMSX" | "esriSMSTriangle"; export type SimpleLineSymbolStyle = "esriSLSDash" | "esriSLSDashDot" | "esriSLSDashDotDot" | "esriSLSDot" | "esriSLSNull" | "esriSLSSolid"; -export type SimpleFillSymbolStyle = "esriSFSBackwardDiagonal" | "esriSFSCross" | "esriSFSDiagonalCross" | "esriSFSForwardDiagonal" | "esriSFSHorizontal" | "esriSFSNull" | "esriSFSSolid" | "esriSFSVertical"; +export type SimpleFillSymbolStyle = + "esriSFSBackwardDiagonal" | "esriSFSCross" | "esriSFSDiagonalCross" | "esriSFSForwardDiagonal" | "esriSFSHorizontal" | "esriSFSNull" | "esriSFSSolid" | "esriSFSVertical"; export type SymbolType = "esriSLS" | "esriSMS" | "esriSFS" | "esriPMS" | "esriPFS" | "esriTS"; export interface Symbol { @@ -168,12 +169,12 @@ export interface SimpleFillSymbol extends Symbol { "type": "esriSFS"; "style"?: SimpleFillSymbolStyle; "color"?: Color; - "outline"?: SimpleLineSymbol; //if outline has been specified + "outline"?: SimpleLineSymbol; // if outline has been specified } export interface PictureSourced { - "url"?: string; //Relative URL for static layers and full URL for dynamic layers. Access relative URL using http:////images/ - "imageData"?: string; //""; + "url"?: string; // Relative URL for static layers and full URL for dynamic layers. Access relative URL using http:////images/ + "imageData"?: string; // ""; "contentType"?: string; "width"?: number; "height"?: number; @@ -189,14 +190,14 @@ export interface PictureMarkerSymbol extends MarkerSymbol, PictureSourced { export interface PictureFillSymbol extends Symbol, PictureSourced { "type": "esriPFS"; - "outline"?: SimpleLineSymbol; //if outline has been specified + "outline"?: SimpleLineSymbol; // if outline has been specified "xscale"?: number; "yscale"?: number; } export interface Font { - "family"?: string; //""; - "size"?: number; //; + "family"?: string; // ""; + "size"?: number; // ; "style"?: "italic" | "normal" | "oblique"; "weight"?: "bold" | "bolder" | "lighter" | "normal"; "decoration"?: "line-through" | "underline" | "none"; @@ -215,5 +216,5 @@ export interface TextSymbol extends MarkerSymbol { "rightToLeft"?: boolean; "kerning"?: boolean; "font"?: Font; - "text"?: string; //only applicable when specified as a client-side graphic. + "text"?: string; // only applicable when specified as a client-side graphic. } \ No newline at end of file diff --git a/arcgis-rest-api/tslint.json b/arcgis-rest-api/tslint.json index 2149d13884..377cc837d4 100644 --- a/arcgis-rest-api/tslint.json +++ b/arcgis-rest-api/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/arcgis-to-geojson-utils/arcgis-to-geojson-utils-tests.ts b/arcgis-to-geojson-utils/arcgis-to-geojson-utils-tests.ts index 48a06fcd02..2e9337793a 100644 --- a/arcgis-to-geojson-utils/arcgis-to-geojson-utils-tests.ts +++ b/arcgis-to-geojson-utils/arcgis-to-geojson-utils-tests.ts @@ -1,14 +1,14 @@ import utils = require("arcgis-to-geojson-utils"); import arcgisApi = require("arcgis-rest-api"); -let arcgisPoint: arcgisApi.Point = { +const arcgisPoint: arcgisApi.Point = { x: -122.6764, y: 45.5165, spatialReference: { wkid: 4326 } }; -let geojsonPoint: GeoJSON.Point = { +const geojsonPoint: GeoJSON.Point = { type: "Point", coordinates: [45.5165, -122.6764] }; diff --git a/arcgis-to-geojson-utils/tslint.json b/arcgis-to-geojson-utils/tslint.json index 2149d13884..377cc837d4 100644 --- a/arcgis-to-geojson-utils/tslint.json +++ b/arcgis-to-geojson-utils/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/array-find-index/array-find-index-tests.ts b/array-find-index/array-find-index-tests.ts index 1443c50b77..0c7508af5e 100644 --- a/array-find-index/array-find-index-tests.ts +++ b/array-find-index/array-find-index-tests.ts @@ -3,6 +3,6 @@ import arrayFindIndex = require("array-find-index"); arrayFindIndex(['rainbow', 'unicorn', 'pony'], x => x === 'unicorn'); const ctx = {foo: 'rainbow'}; -arrayFindIndex(['rainbow', 'unicorn', 'pony'], function (x) { +arrayFindIndex(['rainbow', 'unicorn', 'pony'], function(x) { return x === this.foo; }, ctx); diff --git a/array-find-index/tslint.json b/array-find-index/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/array-find-index/tslint.json +++ b/array-find-index/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/artyom.js/artyom.js-tests.ts b/artyom.js/artyom.js-tests.ts index e70704ad4e..67e5908883 100644 --- a/artyom.js/artyom.js-tests.ts +++ b/artyom.js/artyom.js-tests.ts @@ -1,7 +1,7 @@ import artyomjs = require('artyom.js'); // Get an unique ArtyomJS instance -let artyom = artyomjs.ArtyomBuilder.getInstance(); +const artyom = artyomjs.ArtyomBuilder.getInstance(); // Add a command (not smart) artyom.addCommands({ diff --git a/artyom.js/index.d.ts b/artyom.js/index.d.ts index d96880395f..0b0f253827 100644 --- a/artyom.js/index.d.ts +++ b/artyom.js/index.d.ts @@ -403,7 +403,7 @@ declare namespace Artyom { /** * Says a random quote and returns it's object. - * @param data + * @param data */ sayRandom(data: any): any; @@ -423,14 +423,14 @@ declare namespace Artyom { artyomHey(): any; /** - * This function will return the webkitSpeechRecognition object used by artyom retrieve it only to debug on it or get some + * This function will return the webkitSpeechRecognition object used by artyom retrieve it only to debug on it or get some * values, do not make changes directly. */ getNativeApi(): any; /** * This function returns a boolean according to the SpeechRecognition status if artyom is listening, will return true. - * Note: This is not a feature of SpeechRecognition, therefore this value hangs on the fiability of the onStart and onEnd + * Note: This is not a feature of SpeechRecognition, therefore this value hangs on the fiability of the onStart and onEnd * events of the SpeechRecognition * @returns {Boolean} */ @@ -438,14 +438,14 @@ declare namespace Artyom { /** * This function returns a boolean according to the speechSynthesis status if artyom is speaking, will return true. - * Note: This is not a feature of speechSynthesis, therefore this value hangs on the fiability of the onStart and onEnd + * Note: This is not a feature of speechSynthesis, therefore this value hangs on the fiability of the onStart and onEnd * events of the speechSynthesis. * @returns {Boolean} */ isSpeaking(): boolean; /** - * The SpeechSynthesisUtterance objects are stored in the artyom_garbage_collector variable to prevent the wrong behaviour + * The SpeechSynthesisUtterance objects are stored in the artyom_garbage_collector variable to prevent the wrong behaviour * of artyom.say. Use this method to clear all spoken SpeechSynthesisUtterance unused objects. * @returns {Boolean} */ @@ -487,7 +487,7 @@ declare namespace Artyom { getVersion(): string; /** - * Add commands like an artisan. If you use artyom for simple + * Add commands like an artisan. If you use artyom for simple * tasks then probably you don't like to write a lot to achieve it. * Use the artisan syntax to write less, but with the same accuracy. * @disclaimer Not a promise-based implementation, just syntax. @@ -508,6 +508,6 @@ declare namespace Artyom { } -//tslint:disable-next-line:export-just-namespace +// tslint:disable-next-line:export-just-namespace export = Artyom; export as namespace Artyom; diff --git a/assert-plus/assert-plus-tests.ts b/assert-plus/assert-plus-tests.ts index ec1036e56f..f9f0b2fe3b 100644 --- a/assert-plus/assert-plus-tests.ts +++ b/assert-plus/assert-plus-tests.ts @@ -1,5 +1,5 @@ import * as assert from 'assert-plus'; -let arr = ['one', 'two']; +const arr = ['one', 'two']; assert.array(arr, ''); diff --git a/assert-plus/index.d.ts b/assert-plus/index.d.ts index e2bafe4eae..5de187cb85 100644 --- a/assert-plus/index.d.ts +++ b/assert-plus/index.d.ts @@ -7,262 +7,115 @@ import {Stream} from 'stream'; -/** - * - */ export function array(arr: any[], message ?: string): void; -/** - * - */ export function bool(bool: boolean, message ?: string): void; -/** - * - */ export function buffer(buffer: Buffer, message ?: string): void; -/** - * - */ export function func(func: any, message ?: string): void; -/** - * - */ export function number(number: number, message ?: string): void; -/** - * - */ export function finite(finite: number, message ?: string): void; -/** - * - */ export function object(obj: any, message ?: string): void; -/** - * - */ export function string(str: string, message ?: string): void; -/** - * - */ export function stream(stream: Stream, message ?: string): void; -/** - * - */ export function date(date: Date, message ?: string): void; -/** - * - */ export function regexp(regexp: RegExp, message ?: string): void; -/** - * - */ export function uuid(uuid: string, message ?: string): void; -/** - * - */ export function arrayOfArray(arr: any[][], message ?: string): void; -/** - * - */ export function arrayOfBool(arr: boolean[], message ?: string): void; -/** - * - */ export function arrayOfBuffer(arr: Buffer[], message ?: string): void; -/** - * - */ export function arrayOfFunc(arr: any[], message ?: string): void; -/** - * - */ export function arrayOfNumber(arr: number[], message ?: string): void; -/** - * - */ export function arrayOfFinite(arr: number[], message ?: string): void; -/** - * - */ export function arrayOfObject(arr: any[], message ?: string): void; -/** - * - */ export function arrayOfString(arr: string[], message ?: string): void; -/** - * - */ export function arrayOfStream(arr: Stream[], message ?: string): void; -/** - * - */ export function arrayOfDate(arr: Date[], message ?: string): void; -/** - * - */ export function arrayOfRegexp(arr: RegExp[], message ?: string): void; -/** - * - */ export function arrayOfUuid(arr: string[], message ?: string): void; -/** - * - */ export function optionalArray(arr: any[] | undefined, message ?: string): void; -/** - * - */ export function optionalBool(bool: boolean | undefined, message ?: string): void; -/** - * - */ export function optionalBuffer(buffer: Buffer | undefined, message ?: string): void; -/** - * - */ export function optionalFunc(options: any, message ?: string): void; -/** - * - */ export function optionalNumber(options: number | undefined, message ?: string): void; -/** - * - */ export function optionalFinite(options: number | undefined, message ?: string): void; -/** - * - */ export function optionalObject(options: any, message ?: string): void; -/** - * - */ export function optionalString(options: string | undefined, message ?: string): void; -/** - * - */ export function optionalStream(options: Stream | undefined, message ?: string): void; -/** - * - */ export function optionalDate(options: Date | undefined, message ?: string): void; -/** - * - */ export function optionalRegexp(options: RegExp | undefined, message ?: string): void; -/** - * - */ export function optionalUuid(options: string | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfArray(arr: any[][] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfBool(arr: boolean[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfBuffer(arr: Buffer[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfFunc(arr: any[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfNumber(arr: number[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfFinite(arr: number[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfObject(arr: any[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfString(arr: string[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfStream(arr: Stream[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfDate(arr: Date[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfRegexp(arr: RegExp[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfUuid(arr: string[] | undefined, message ?: string): void; -/** - * - */ export function AssertionError(options: any, message ?: string): void; /** * Throws an `AssertionError`. If `message` is falsy, the error message is set * as the values of `actual` and `expected` separated by the provided `operator`. * Otherwise, the error message is the value of `message`. - * + * * ```js * const assert = require('assert'); - * + * * assert.fail(1, 2, undefined, '>'); * // AssertionError: 1 > 2 - * + * * assert.fail(1, 2, 'whoops', '>'); * // AssertionError: whoops * ``` @@ -272,14 +125,14 @@ export function fail(actual: any, expected: any, message: any, operator: any): v /** * Tests if `value` is truthy. It is equivalent to `assert.equal(!!value, true, message)`. - * + * * If `value` is not truthy, an `AssertionError` is thrown with a `message` property * set equal to the value of the `message` parameter. * If the `message` parameter is `undefined`, a default error message is assigned. - * + * * ```js * const assert = require('assert'); - * + * * assert.ok(true); * // OK * assert.ok(1); @@ -297,21 +150,21 @@ export function ok(options: any, message ?: string): void; /** * Tests shallow, coercive equality between the actual and expected parameters * using the equal comparison operator ( `==` ). - * + * * ```js * const assert = require('assert'); - * + * * assert.equal(1, 1); * // OK, 1 == 1 * assert.equal(1, '1'); * // OK, 1 == '1' - * + * * assert.equal(1, 2); * // AssertionError: 1 == 2 * assert.equal({a: {b: 1}}, {a: {b: 1}}); * //AssertionError: { a: { b: 1 } } == { a: { b: 1 } } * ``` - * + * * If the values are not equal, an `AssertionError` is thrown with * a `message` property set equal to the value of the `message` parameter. * If the `message` parameter is undefined, a default error message is assigned. @@ -320,20 +173,20 @@ export function equal(actual: any, expected: any, message ?: string): void; /** * Tests shallow, coercive inequality with the not equal comparison operator ( `!=` ). - * + * * ```js * const assert = require('assert'); - * + * * assert.notEqual(1, 2); * // OK - * + * * assert.notEqual(1, 1); * // AssertionError: 1 != 1 - * + * * assert.notEqual(1, '1'); * // AssertionError: 1 != '1' * ``` - * + * * If the values are equal, an `AssertionError` is thrown with * a `message` property set equal to the value of the `message` parameter. * If the `message` parameter is undefined, a default error message is assigned. @@ -343,20 +196,20 @@ export function notEqual(actual: any, expected: any, message ?: string): void; /** * Tests for deep equality between the `actual` and `expected` parameters. * Primitive values are compared with the equal comparison operator ( `==` ). - * + * * Only enumerable "own" properties are considered. * The `deepEqual()` implementation does not test object prototypes, attached symbols, * or non-enumerable properties. This can lead to some potentially surprising results. * For example, the following example does not throw an `AssertionError` because * the properties on the Error object are non-enumerable: - * + * * ```js * // WARNING: This does not throw an AssertionError! * assert.deepEqual(Error('a'), Error('b')); * ``` - * + * * "Deep" equality means that the enumerable "own" properties of child objects are evaluated also. - * + * * If the values are not equal, an `AssertionError` is thrown with a `message` property * set equal to the value of the `message` parameter. If the `message` parameter is undefined, * a default error message is assigned. @@ -365,28 +218,28 @@ export function deepEqual(actual: T, expected: T, message ?: string): void; /** * Tests for any deep inequality. Opposite of `assert.deepEqual()`. - * + * * ```js * const assert = require('assert'); - * + * * const obj1 = { a : { b : 1 } }; * const obj2 = { a : { b : 2 } }; * const obj3 = { a : { b : 1 } }; * const obj4 = Object.create(obj1); - * + * * assert.notDeepEqual(obj1, obj1); * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } - * + * * assert.notDeepEqual(obj1, obj2); * // OK, obj1 and obj2 are not deeply equal - * + * * assert.notDeepEqual(obj1, obj3); * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } - * + * * assert.notDeepEqual(obj1, obj4); * // OK, obj1 and obj2 are not deeply equal * ``` - * + * * If the values are deeply equal, an `AssertionError` is thrown with * a `message` property set equal to the value of the `message` parameter. * If the `message` parameter is undefined, a default error message is assigned. @@ -395,20 +248,20 @@ export function notDeepEqual(actual: any, expected: any, message ?: string): voi /** * Tests strict equality as determined by the strict equality operator ( `===` ). - * + * * ```js * const assert = require('assert'); - * + * * assert.strictEqual(1, 2); * // AssertionError: 1 === 2 - * + * * assert.strictEqual(1, 1); * // OK - * + * * assert.strictEqual(1, '1'); * // AssertionError: 1 === '1' * ``` - * + * * If the values are not strictly equal, an `AssertionError` is thrown with * a `message` property set equal to the value of the `message` parameter. * If the `message` parameter is undefined, a default error message is assigned. @@ -417,40 +270,37 @@ export function strictEqual(actual: T, expected: T, message ?: string): void; /** * Tests strict inequality as determined by the strict not equal operator ( `!==` ). - * + * * ```js * const assert = require('assert'); - * + * * assert.notStrictEqual(1, 2); * // OK - * + * * assert.notStrictEqual(1, 1); * // AssertionError: 1 !== 1 - * + * * assert.notStrictEqual(1, '1'); * // OK * ``` - * + * * If the values are strictly equal, an `AssertionError` is thrown with a `message` property * set equal to the value of the `message` parameter. If the `message` parameter is undefined, * a default error message is assigned. */ export function notStrictEqual(actual: any, expected: any, message ?: string): void; -/** - * - */ export function throws(block: any, error ?: any, message ?: string): void; /** * Asserts that the function `block` does not throw an error. See `assert.throws()` for more details. - * + * * When `assert.doesNotThrow()` is called, it will immediately call the `block` function. - * + * * If an error is thrown and it is the same type as that specified by the `error` parameter, * then an `AssertionError` is thrown. If the error is of a different type, * or if the `error` parameter is undefined, the error is propagated back to the caller. - * + * * The following, for instance, will throw the TypeError because there is no matching error type in the assertion: * ```js * assert.doesNotThrow( @@ -460,7 +310,7 @@ export function throws(block: any, error ?: any, message ?: string): void; * SyntaxError * ); * ``` - * + * * However, the following will result in an `AssertionError` with the message 'Got unwanted exception (TypeError)..': * ```js * assert.doesNotThrow( @@ -470,7 +320,7 @@ export function throws(block: any, error ?: any, message ?: string): void; * TypeError * ); * ``` - * + * * If an `AssertionError` is thrown and a value is provided for the `message` parameter, * the value of `message` will be appended to the `AssertionError` message: * ```js @@ -490,7 +340,7 @@ export function doesNotThrow(block: any, error ?: any, message ?: string): void; * Throws `value` if `value` is truthy. This is useful when testing the `error` argument in callbacks. * ```js * const assert = require('assert'); - * + * * assert.ifError(0); * // OK * assert.ifError(1); diff --git a/auth0-js/auth0-js-tests.ts b/auth0-js/auth0-js-tests.ts index 68d4e1797b..7c910d1765 100644 --- a/auth0-js/auth0-js-tests.ts +++ b/auth0-js/auth0-js-tests.ts @@ -1,4 +1,4 @@ -/// +import 'auth0-js'; let webAuth = new auth0.WebAuth({ domain: 'mine.auth0.com', diff --git a/auth0-js/index.d.ts b/auth0-js/index.d.ts index 0a0e004303..11cf16a3ed 100644 --- a/auth0-js/index.d.ts +++ b/auth0-js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Auth0.js v8.1.3 +// Type definitions for Auth0.js 8.1 // Project: https://github.com/auth0/auth0.js // Definitions by: Adrian Chia // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -409,7 +409,7 @@ declare namespace auth0 { interface Auth0Error { error: any; - errorDescription: string + errorDescription: string; } interface Auth0DecodedHash { @@ -442,7 +442,7 @@ declare namespace auth0 { connection: string; send: string; phoneNumber?: string; - email?: string, + email?: string; authParams?: any; } diff --git a/auth0-js/tsconfig.json b/auth0-js/tsconfig.json index a2e16e19e0..62bab1e208 100644 --- a/auth0-js/tsconfig.json +++ b/auth0-js/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "auth0-js-tests.ts" ] -} \ No newline at end of file +} diff --git a/auth0-js/v7/auth0-js-tests.ts b/auth0-js/v7/auth0-js-tests.ts index d5ca0250d4..a68b17cb69 100644 --- a/auth0-js/v7/auth0-js-tests.ts +++ b/auth0-js/v7/auth0-js-tests.ts @@ -1,4 +1,5 @@ -/// +import 'auth0-js'; + var auth0 = new Auth0({ domain: 'mine.auth0.com', clientID: 'dsa7d77dsa7d7', diff --git a/auth0-js/v7/index.d.ts b/auth0-js/v7/index.d.ts index ee834d5c61..a93e979f2b 100644 --- a/auth0-js/v7/index.d.ts +++ b/auth0-js/v7/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Auth0.js v7.x +// Type definitions for Auth0.js 7.0 // Project: https://github.com/auth0/auth0.js // Definitions by: Robert McLaws // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -13,20 +13,20 @@ interface Window { interface Auth0Static { new(options: Auth0ClientOptions): Auth0Static; - changePassword(options: any, callback?: Function): void; + changePassword(options: any, callback?: (error?: Auth0Error, valid?: any) => void): void; decodeJwt(jwt: string): any; login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void; loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; logout(query: string): void; - getConnections(callback?: Function): void; + getConnections(callback?: (error?: Auth0Error, valid?: any) => void): void; refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; getDelegationToken(options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; - getProfile(id_token: string, callback?: Function): Auth0UserProfile; - getSSOData(withActiveDirectories: any, callback?: Function): void; + getProfile(id_token: string, callback?: (error?: Auth0Error, valid?: any) => void): Auth0UserProfile; + getSSOData(withActiveDirectories: any, callback?: (error?: Auth0Error, valid?: any) => void): void; parseHash(hash: string): Auth0DecodedHash; - signup(options: Auth0SignupOptions, callback: Function): void; + signup(options: Auth0SignupOptions, callback: (error?: Auth0Error, valid?: any) => void): void; validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void; } @@ -132,5 +132,5 @@ interface Auth0DelegationToken { declare const Auth0: Auth0Static; declare module "auth0-js" { - export = Auth0 + export = Auth0; } diff --git a/auth0-js/v7/tsconfig.json b/auth0-js/v7/tsconfig.json index 7413e97f44..bdabf7ef7f 100644 --- a/auth0-js/v7/tsconfig.json +++ b/auth0-js/v7/tsconfig.json @@ -12,12 +12,11 @@ "typeRoots": [ "../../" ], - "paths": { - "auth0-js": [ - "auth0-js/v7" - ] - }, "types": [], + "paths": { + "auth0-js": ["auth0-js/v7"], + "auth0-js/*": ["auth0-js/v7/*"] + }, "noEmit": true, "forceConsistentCasingInFileNames": true }, diff --git a/auth0-lock/auth0-lock-tests.ts b/auth0-lock/auth0-lock-tests.ts index 4b72edcfa1..8045386586 100644 --- a/auth0-lock/auth0-lock-tests.ts +++ b/auth0-lock/auth0-lock-tests.ts @@ -1,5 +1,5 @@ -/// -/// +import 'auth0-js/v7'; +import Auth0Lock from 'auth0-lock'; const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID"; const DOMAIN = "YOUR_DOMAIN_AT.auth0.com"; diff --git a/auth0-lock/package.json b/auth0-lock/package.json new file mode 100644 index 0000000000..2d730992af --- /dev/null +++ b/auth0-lock/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "@types/auth0-js": "latest" + } +} diff --git a/auth0-lock/tsconfig.json b/auth0-lock/tsconfig.json index 367445041e..09c9f8233c 100644 --- a/auth0-lock/tsconfig.json +++ b/auth0-lock/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "auth0-lock-tests.ts" ] -} \ No newline at end of file +} diff --git a/auth0.widget/auth0.widget-tests.ts b/auth0.widget/auth0.widget-tests.ts index 6277d4cc3a..f2ddda2146 100644 --- a/auth0.widget/auth0.widget-tests.ts +++ b/auth0.widget/auth0.widget-tests.ts @@ -1,5 +1,4 @@ -/// - +import 'auth0-js/v7'; var widget: Auth0WidgetStatic = new Auth0Widget({ domain: 'mine.auth0.com', diff --git a/auth0.widget/index.d.ts b/auth0.widget/index.d.ts index cdefd9e0fd..36d99c9009 100644 --- a/auth0.widget/index.d.ts +++ b/auth0.widget/index.d.ts @@ -5,7 +5,6 @@ /// - interface Auth0WidgetStatic { new(params: Auth0Constructor): Auth0WidgetStatic; diff --git a/auth0.widget/package.json b/auth0.widget/package.json new file mode 100644 index 0000000000..2d730992af --- /dev/null +++ b/auth0.widget/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "@types/auth0-js": "latest" + } +} diff --git a/auth0.widget/tsconfig.json b/auth0.widget/tsconfig.json index 7bba7e763f..8ceb7b3d73 100644 --- a/auth0.widget/tsconfig.json +++ b/auth0.widget/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "auth0.widget-tests.ts" ] -} \ No newline at end of file +} diff --git a/auth0/index.d.ts b/auth0/index.d.ts index b24b808529..a8a6242bb4 100644 --- a/auth0/index.d.ts +++ b/auth0/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for auth0 v2.3.1 +// Type definitions for auth0 2.4 // Project: https://github.com/auth0/node-auth0 -// Definitions by: Seth Westphal +// Definitions by: Wilson Hobbs , Seth Westphal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as Promise from 'bluebird'; @@ -10,8 +10,8 @@ export interface ManagementClientOptions { domain?: string; } -export type UserMetadata = {}; -export type AppMetadata = {}; +export interface UserMetadata { } +export interface AppMetadata { } export interface UserData { connection: string; @@ -71,34 +71,353 @@ export interface UpdateUserParameters { id: string; } -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; - updateUser(params: UpdateUserParameters, data: User): Promise; - updateUser(params: UpdateUserParameters, data: User, cb: (err: Error, data: User) => void): void; - updateUserMetadata(params: UpdateUserParameters, data: UserMetadata): Promise; - updateUserMetadata(params: UpdateUserParameters, data: UserMetadata, cb: (err: Error, data: User) => void): void - updateAppMetadata(params: UpdateUserParameters, data: AppMetadata): Promise; - updateAppMetadata(params: UpdateUserParameters, data: AppMetadata, cb: (err: Error, data: User) => void): void -} - export interface AuthenticationClientOptions { clientId?: string; domain: string; } -export interface RequestChangePasswordEmailData { +interface Environment { + name: string; + version: string; +} + +export interface ClientInfo { + name: string; + version: string; + dependencies: any[]; + environment: Environment[]; +} + +export interface RequestEmailOptions { + email: string; + authParams: {}; +} + +export interface RequestSMSOptions { + phone_number: string; +} + +export interface VerifyOptions { + username: string; + password: string; +} + +export interface DelegationTokenOptions { + id_token: string; + api_type: string; + scope: string; + target: string; + grant_type: string; +} + +export interface ResetPasswordOptions { connection: string; email: string; + password: string; } +export interface ResetPasswordEmailOptions { + email: string; + connection: string; +} + +export interface ObjectWithId { + id: string; +} + +export interface Data { + name?: string; + [propName: string]: any; +} + +export interface ClientParams { + client_id: string; +} + +export interface DeleteMultifactorParams { + id: string; + provider: string; +} + +export interface LinkAccountsParams { + id: string; + provider: string; + user_id: string; +} + +export interface LinkAccountsData { + user_id: string; + connection_id: string; +} + +export interface Token { + aud: string; + jti: string; +} + +export interface StatsParams { + from: string; + to: string; +} + +export interface ImportUsersOptions { + connection_id: string; + users: string; +} + +export interface UserIdParams { + user_id: string; +} + +export interface PasswordChangeTicketParams { + result_url: string; + user_id: string; + email: string; + new_password: string; +} + +export interface EmailVerificationTicketOptions { + user_id: string; + result_url: string; +} + + + export class AuthenticationClient { constructor(options: AuthenticationClientOptions); + getClientInfo(): ClientInfo; + + requestMagicLink(data: RequestEmailOptions): Promise; + requestMagicLink(data: RequestEmailOptions, cb: (err: Error, message: string) => void): void; + + requestEmailCode(data: RequestEmailOptions): Promise; + requestEmailCode(data: RequestEmailOptions, cb: (err: Error, message: string) => void): void; + + requestSMSCode(data: RequestSMSOptions): Promise; + requestSMSCode(data: RequestSMSOptions, cb: (err: Error, message: string) => void): void; + + verifyEmailCode(data: VerifyOptions): Promise; + verifyEmailCode(data: VerifyOptions, cb: (err: Error, message: string) => void): void; + + verifySMSCode(data: VerifyOptions): Promise; + verifySMSCode(data: VerifyOptions, cb: (err: Error, message: string) => void): void; + + getDelegationToken(data: DelegationTokenOptions): Promise; + getDelegationToken(data: DelegationTokenOptions, cb: (err: Error, message: string) => void): void; + + changePassword(data: ResetPasswordOptions): Promise; + changePassword(data: ResetPasswordOptions, cb: (err: Error, message: string) => void): void; + + requestChangePasswordEmail(data: ResetPasswordEmailOptions): Promise; + requestChangePasswordEmail(data: ResetPasswordEmailOptions, cb: (err: Error, message: string) => void): void; + + getProfile(accessToken: string): Promise; + getProfile(accessToken: string, cb: (err: Error, message: string) => void): void; + + getCredentialsGrant(scope: string): Promise; + getCredentialsGrant(scope: string, cb: (err: Error, message: string) => void): void; + +} + + +export class ManagementClient { + constructor(options: ManagementClientOptions); + + getClientInfo(): ClientInfo; + + // Connections + getConnections(): Promise; + getConnections(cb: (err: Error, data: any) => void): void; + + createConnection(data: ObjectWithId): Promise; + createConnection(data: ObjectWithId, cb: (err: Error, data: any) => void): void; + + getConnection(params: ObjectWithId, cb: (err: Error, data: any) => void): void; + getConnection(params: ObjectWithId): Promise; + + deleteConnection(params: ObjectWithId, cb: (err: Error, data: any) => void): void; + deleteConnection(params: ObjectWithId): Promise; + + deleteConnection(params: ObjectWithId, cb: (err: Error, data: any) => void): void; + deleteConnection(params: ObjectWithId): Promise; + + updateConnection(params: ObjectWithId, data: Data, cb: (err: Error, data: any) => void): void; + updateConnection(params: ObjectWithId, data: Data): Promise; + + + // Clients + getClients(): Promise; + getClients(cb: (err: Error, data: any) => void): void; + + getClient(params: ClientParams): Promise; + getClient(params: ClientParams, cb: (err: Error, data: any) => void): void; + + createClient(data: Data): Promise; + createClient(data: Data, cb: (err: Error, data: any) => void): void; + + updateClient(params: ClientParams, data: Data): Promise; + updateClient(params: ClientParams, data: Data, cb: (err: Error, data: any) => void): void; + + deleteClient(params: ClientParams): Promise; + deleteClient(params: ClientParams, cb: (err: Error, data: any) => void): void; + + // Client Grants + getClientGrants(): Promise; + getClientGrants(cb: (err: Error, data: any) => void): void; + + createClientGrant(data: Data): Promise; + createClientGrant(data: Data, cb: (err: Error, data: any) => void): void; + + updateClientGrant(params: ObjectWithId, data: Data): Promise; + updateClientGrant(params: ObjectWithId, data: Data, cb: (err: Error, data: any) => void): void; + + deleteClientGrant(params: ObjectWithId): Promise; + deleteClientGrant(params: ObjectWithId, cb: (err: Error, data: any) => void): void; + + + // Device Keys + getDeviceCredentials(): Promise; + getDeviceCredentials(cb: (err: Error, data: any) => void): void; + + createDevicePublicKey(data: Data): Promise; + createDevicePublicKey(data: Data, cb: (err: Error, data: any) => void): void; + + deleteDeviceCredential(params: ClientParams): Promise; + deleteDeviceCredential(params: ClientParams, cb: (err: Error, data: any) => void): void; + + + // Rules + getRules(): Promise; + getRules(cb: (err: Error, data: any) => void): void; + + getRule(params: ClientParams): Promise; + getRule(params: ClientParams, cb: (err: Error, data: any) => void): void; + + createRules(data: Data): Promise; + createRules(data: Data, cb: (err: Error, data: any) => void): void; + + updateRule(params: ObjectWithId, data: Data): Promise; + updateRule(params: ObjectWithId, data: Data, cb: (err: Error, data: any) => void): void; + + deleteRule(params: ObjectWithId): Promise; + deleteRule(params: ObjectWithId, cb: (err: Error, data: any) => void): void; + + + // Users + getUsers(params?: GetUsersData): Promise; + getUsers(params?: GetUsersData, cb?: (err: Error, users: User[]) => void): void; + + getUser(params?: ObjectWithId): Promise; + getUser(params?: ObjectWithId, cb?: (err: Error, users: User[]) => void): void; + + createUser(data: UserData): Promise; + createUser(data: UserData, cb: (err: Error, data: User) => void): void; + + updateUser(params: UpdateUserParameters, data: User): Promise; + updateUser(params: UpdateUserParameters, data: User, cb: (err: Error, data: User) => void): void; + + updateUserMetadata(params: UpdateUserParameters, data: UserMetadata): Promise; + updateUserMetadata(params: UpdateUserParameters, data: UserMetadata, cb: (err: Error, data: User) => void): void; + + deleteAllUsers(): Promise; + deleteAllUsers(cb: (err: Error, data: any) => void): void; + + deleteUser(params?: ObjectWithId): Promise; + deleteUser(params?: ObjectWithId, cb?: (err: Error, users: User[]) => void): void; + + updateAppMetadata(params: UpdateUserParameters, data: AppMetadata): Promise; + updateAppMetadata(params: UpdateUserParameters, data: AppMetadata, cb: (err: Error, data: User) => void): void; + + deleteUserMultifactor(params: DeleteMultifactorParams): Promise; + deleteUserMultifactor(params: DeleteMultifactorParams, cb: (err: Error, data: any) => void): void; + + unlinkUsers(params: LinkAccountsParams): Promise; + unlinkUsers(params: LinkAccountsParams, cb: (err: Error, data: any) => void): void; + + linkUsers(params: ObjectWithId, data: LinkAccountsData): Promise; + linkUsers(params: ObjectWithId, data: LinkAccountsData, cb: (err: Error, data: any) => void): void; + + + // Tokens + getBlacklistedTokens(): Promise; + getBlacklistedTokens(cb?: (err: Error, data: any) => void): void; + + blacklistToken(token: Token): Promise; + blacklistToken(token: Token, cb: (err: Error, data: any) => void): void; + + + // Providers + getEmailProvider(): Promise; + getEmailProvider(cb?: (err: Error, data: any) => void): void; + + configureEmailProvider(data: Data): Promise; + configureEmailProvider(data: Data, cb: (err: Error, data: any) => void): void; + + deleteEmailProvider(): Promise; + deleteEmailProvider(cb?: (err: Error, data: any) => void): void; + + updateEmailProvider(data: Data): Promise; + updateEmailProvider(data: Data, cb?: (err: Error, data: any) => void): void; + + + // Statistics + getActiveUsersCount(): Promise; + getActiveUsersCount(cb?: (err: Error, data: any) => void): void; + + getDailyStats(data: StatsParams): Promise; + getDailyStats(data: StatsParams, cb: (err: Error, data: any) => void): void; + + + // Tenant + getTenantSettings(): Promise; + getTenantSettings(cb?: (err: Error, data: any) => void): void; + + updateTenantSettings(data: Data): Promise; + updateTenantSettings(data: Data, cb?: (err: Error, data: any) => void): void; + + + // Jobs + getJob(params: ObjectWithId): Promise; + getJob(params: ObjectWithId, cb?: (err: Error, data: any) => void): void; + + importUsers(data: ImportUsersOptions): Promise; + importUsers(data: ImportUsersOptions, cb?: (err: Error, data: any) => void): void; + + sendEmailVerification(data: UserIdParams): Promise; + sendEmailVerification(data: UserIdParams, cb?: (err: Error, data: any) => void): void; + + // Tickets + createPasswordChangeTicket(params: PasswordChangeTicketParams): Promise; + createPasswordChangeTicket(params: PasswordChangeTicketParams, cb?: (err: Error, data: any) => void): void; + + createEmailVerificationTicket(data: EmailVerificationTicketOptions): Promise; + createEmailVerificationTicket(data: EmailVerificationTicketOptions, cb?: (err: Error, data: any) => void): void; + + // Logs + getLog(params: ObjectWithId): Promise; + getLog(params: ObjectWithId, cb?: (err: Error, data: any) => void): void; + + getLogs(): Promise; + getLogs(cb?: (err: Error, data: any) => void): void; + + + // Resource Server + createResourceServer(data: Data): Promise; + createResourceServer(data: Data, cb?: (err: Error, data: any) => void): void; + + getResourceServers(): Promise; + getResourceServers(cb?: (err: Error, data: any) => void): void; + + getResourceServer(data: ObjectWithId): Promise; + getResourceServer(data: ObjectWithId, cb?: (err: Error, data: any) => void): void; + + deleteResourceServer(params: ObjectWithId): Promise; + deleteResourceServer(params: ObjectWithId, cb?: (err: Error, data: any) => void): void; + + updateResourceServer(params: ObjectWithId, data: Data): Promise; + updateResourceServer(params: ObjectWithId, data: Data, cb?: (err: Error, data: any) => void): void; + + + - requestChangePasswordEmail(data: RequestChangePasswordEmailData): Promise; - requestChangePasswordEmail(data: RequestChangePasswordEmailData, cb: (err: Error, message: string) => void): void; } diff --git a/b_/b_-tests.ts b/b_/b_-tests.ts new file mode 100644 index 0000000000..c0a92a4c7d --- /dev/null +++ b/b_/b_-tests.ts @@ -0,0 +1,52 @@ +import b_ = require("b_"); + +const blockClass: string = b_("block"); +const blockWithModsClass: string = b_("block", {stringMod: "string", boolMod: true, numberMod: 5}); +const elemClass: string = b_("block", "elem"); +const elemWithModsClass: string = b_("block", "elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const withBlock = b_.with("block"); +const withBlockClass: string = withBlock(); +const withBlockWithModsClass: string = withBlock({stringMod: "string", boolMod: true, numberMod: 5}); +const withBlockElemClass: string = withBlock("elem"); +const withBlockElemWithModsClass: string = withBlock("elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const lockBlock = b_.lock("block"); +const lockBlockClass: string = lockBlock(); +const lockBlockWithModsClass: string = lockBlock({stringMod: "string", boolMod: true, numberMod: 5}); +const lockBlockElemClass: string = lockBlock("elem"); +const lockBlockElemWithModsClass: string = lockBlock("elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const withElem = b_.with("block", "elem"); +const withElemClass: string = withElem(); +const withElemWithModsClass: string = withElem({stringMod: "string", boolMod: true, numberMod: 5}); + +const parameterizedB_ = b_.B({ + tailSpace: " ", + elementSeparator: "-", + modSeparator: "_", + modValueSeparator: "-", + classSeparator: " ", + isFullModifier: true +}); + +const parameterizedBlockClass: string = parameterizedB_("block"); +const parameterizedBlockWithModsClass: string = parameterizedB_("block", {stringMod: "string", boolMod: true, numberMod: 5}); +const parameterizedElemClass: string = parameterizedB_("block", "elem"); +const parameterizedElemWithModsClass: string = parameterizedB_("block", "elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const parameterizedWithBlock = parameterizedB_.with("block"); +const parameterizedWithBlockClass: string = parameterizedWithBlock(); +const parameterizedWithBlockWithModsClass: string = parameterizedWithBlock({stringMod: "string", boolMod: true, numberMod: 5}); +const parameterizedWithBlockElemClass: string = parameterizedWithBlock("elem"); +const parameterizedWithBlockElemWithModsClass: string = parameterizedWithBlock("elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const parameterizedLockBlock = parameterizedB_.lock("block"); +const parameterizedLockBlockClass: string = parameterizedLockBlock(); +const parameterizedLockBlockWithModsClass: string = parameterizedLockBlock({stringMod: "string", boolMod: true, numberMod: 5}); +const parameterizedLockBlockElemClass: string = parameterizedLockBlock("elem"); +const parameterizedLockBlockElemWithModsClass: string = parameterizedLockBlock("elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const parameterizedWithElem = parameterizedB_.with("block", "elem"); +const parameterizedWithElemClass: string = parameterizedWithElem(); +const parameterizedWithElemWithModsClass: string = parameterizedWithElem({stringMod: "string", boolMod: true, numberMod: 5}); diff --git a/b_/index.d.ts b/b_/index.d.ts new file mode 100644 index 0000000000..fe59f2d72e --- /dev/null +++ b/b_/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for b_ 1.3 +// Project: https://github.com/azproduction/b_ +// Definitions by: Vasya Aksyonov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Options { + tailSpace?: string; + elementSeparator?: string; + modSeparator?: string; + modValueSeparator?: string; + classSeparator?: string; + isFullModifier?: boolean; +} + +interface Mods { + [name: string]: any; +} + +interface Formatter { + (block: string, mods?: Mods): string; + (block: string, elem: string, mods?: Mods): string; + + with(block: string): BlockFormatter; + with(block: string, elem: string): ElemFormatter; + + lock(block: string): BlockFormatter; + lock(block: string, elem: string): ElemFormatter; + + B(options: Options): Formatter; +} + +interface BlockFormatter { + (mods?: Mods): string; + (elem: string, mods?: Mods): string; +} + +type ElemFormatter = (mods?: Mods) => string; + +declare const formatter: Formatter; +export = formatter; diff --git a/b_/tsconfig.json b/b_/tsconfig.json new file mode 100644 index 0000000000..5271d3aeeb --- /dev/null +++ b/b_/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "b_-tests.ts" + ] +} diff --git a/b_/tslint.json b/b_/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/b_/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/babel-code-frame/tslint.json b/babel-code-frame/tslint.json index ec365f164b..377cc837d4 100644 --- a/babel-code-frame/tslint.json +++ b/babel-code-frame/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/backlog-js/index.d.ts b/backlog-js/index.d.ts index b548241e2f..d06f764baa 100644 --- a/backlog-js/index.d.ts +++ b/backlog-js/index.d.ts @@ -23,9 +23,9 @@ declare class Request { method: string; path: string; params?: Params | FormData; - }): Promise; - checkStatus(response: ResponseInterface): Promise; - parseJSON(response: ResponseInterface): Promise; + }): Promise; + checkStatus(response: Response): Promise; + parseJSON(response: Response): Promise; private toFormData(params); private toQueryString(params); webAppBaseURL: string; @@ -49,7 +49,7 @@ export class Backlog extends Request { putSpaceNotification(params: Option.Space.PutSpaceNotificationParams): Promise; getSpaceDiskUsage(): Promise; getSpaceIcon(): Promise; - postSpaceAttachment(form: FormData): Promise; + postSpaceAttachment(form: FormData): Promise; getUsers(): Promise; getUser(userId: number): Promise; postUser(params: Option.User.PostUserParams): Promise; @@ -656,7 +656,7 @@ export namespace Error { private _status; private _body; private _response; - constructor(name: BacklogErrorNameType, response: ResponseInterface, body?: { + constructor(name: BacklogErrorNameType, response: Response, body?: { errors: BacklogErrorMessage[]; }); name: BacklogErrorNameType; @@ -665,20 +665,20 @@ export namespace Error { body: { errors: BacklogErrorMessage[]; }; - response: ResponseInterface; + response: Response; } export class BacklogApiError extends BacklogError { - constructor(response: ResponseInterface, body?: { + constructor(response: Response, body?: { errors: BacklogErrorMessage[]; }); } export class BacklogAuthError extends BacklogError { - constructor(response: ResponseInterface, body?: { + constructor(response: Response, body?: { errors: BacklogErrorMessage[]; }); } export class UnexpectedError extends BacklogError { - constructor(response: ResponseInterface); + constructor(response: Response); } export interface BacklogErrorMessage { message: string; diff --git a/base-64/base-64-tests.ts b/base-64/base-64-tests.ts index a0f85f09aa..3435ae8265 100644 --- a/base-64/base-64-tests.ts +++ b/base-64/base-64-tests.ts @@ -1,13 +1,13 @@ import * as base64 from 'base-64'; import * as utf8 from 'utf8'; - + let text = 'foo © bar 𝌆 baz'; let bytes = utf8.encode(text); let encoded = base64.encode(bytes); -// → 'Zm9vIMKpIGJhciDwnYyGIGJheg==' +// → 'Zm9vIMKpIGJhciDwnYyGIGJheg==' encoded = 'Zm9vIMKpIGJhciDwnYyGIGJheg=='; bytes = base64.decode(encoded); text = utf8.decode(bytes); -let version = base64.version; +const version = base64.version; diff --git a/base-64/index.d.ts b/base-64/index.d.ts index 3d6fd885d2..ddd10db17b 100644 --- a/base-64/index.d.ts +++ b/base-64/index.d.ts @@ -6,19 +6,19 @@ export const version: string; /** - * This function takes a byte string (the input parameter) and encodes it according to base64. - * The input data must be in the form of a string containing only characters - * in the range from U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF. - * The base64.encode() function is designed to be fully compatible + * This function takes a byte string (the input parameter) and encodes it according to base64. + * The input data must be in the form of a string containing only characters + * in the range from U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF. + * The base64.encode() function is designed to be fully compatible * with btoa() as described in the HTML Standard. * see: https://html.spec.whatwg.org/multipage/webappapis.html#dom-windowbase64-btoa */ export function encode(input: string): string; /** - * This function takes a base64-encoded string (the input parameter) and decodes it. - * The return value is in the form of a string containing only characters in - * the range from U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF. - * The base64.decode() function is designed to be fully compatible + * This function takes a base64-encoded string (the input parameter) and decodes it. + * The return value is in the form of a string containing only characters in + * the range from U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF. + * The base64.decode() function is designed to be fully compatible * with atob() as described in the HTML Standard. * see: https://html.spec.whatwg.org/multipage/webappapis.html#dom-windowbase64-atob */ diff --git a/base-64/tslint.json b/base-64/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/base-64/tslint.json +++ b/base-64/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/base64-js/tslint.json b/base64-js/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/base64-js/tslint.json +++ b/base64-js/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/basic-auth/index.d.ts b/basic-auth/index.d.ts index 3dc19b3046..51ada3b0c7 100644 --- a/basic-auth/index.d.ts +++ b/basic-auth/index.d.ts @@ -3,9 +3,11 @@ // Definitions by: Clément Bourgeois // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import * as Express from 'express'; +/// -declare function auth(req: Express.Request): auth.BasicAuthResult; +import * as http from 'http'; + +declare function auth(req: http.IncomingMessage): auth.BasicAuthResult; declare namespace auth { interface BasicAuthResult { diff --git a/bezier-js/bezier-js-tests.ts b/bezier-js/bezier-js-tests.ts index 5776ffd307..f5fba4d947 100644 --- a/bezier-js/bezier-js-tests.ts +++ b/bezier-js/bezier-js-tests.ts @@ -10,7 +10,7 @@ function test() { var utils = bezier.getUtils(); var line: BezierJs.Line = { p1: { x: 0, y: 0 }, p2: { x: 1, y: 1 } }; var abc: BezierJs.ABC = { A: null, B: null, C: null }; - var arc: BezierJs.Arc = { e: 0, s: 0, x: 0, y: 0, r: 1 }; + var arc: BezierJs.Arc = { e: 0, s: 0, x: 0, y: 0, r: 1, interval:{ start: 0, end: 1 } }; var bbox: BezierJs.BBox = bezier.bbox(); var closest: BezierJs.Closest = { mdist: 1, mpos: 0 }; var inflection: BezierJs.Inflection = { values: null, x: [0], y: [0], z: [0] }; @@ -95,4 +95,4 @@ function test() { utils.round(.999, .001); utils.shapeintersections(shape, bbox, shape, bbox); -} \ No newline at end of file +} diff --git a/bezier-js/index.d.ts b/bezier-js/index.d.ts index ff07e67f16..7706a46472 100644 --- a/bezier-js/index.d.ts +++ b/bezier-js/index.d.ts @@ -51,6 +51,7 @@ declare namespace BezierJs { e: number; r: number; s: number; + interval: { start: number; end: number; }; } interface Shape { startcap: BezierCap; diff --git a/bigi/bigi-tests.ts b/bigi/bigi-tests.ts index 82ba89fb18..70569bb919 100644 --- a/bigi/bigi-tests.ts +++ b/bigi/bigi-tests.ts @@ -1,9 +1,9 @@ -import BigInteger = require('bigi') +import BigInteger = require('bigi'); -var b1 = BigInteger.fromHex("188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012") -var b2 = BigInteger.fromHex("07192B95FFC8DA78631011ED6B24CDD573F977A11E794811") +var b1 = BigInteger.fromHex("188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"); +var b2 = BigInteger.fromHex("07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); -var b3 = b1.multiply(b2) +var b3 = b1.multiply(b2); -console.log(b3.toHex()) +console.log(b3.toHex()); // => ae499bfe762edfb416d0ce71447af67ff33d1760cbebd70874be1d7a5564b0439a59808cb1856a91974f7023f72132 \ No newline at end of file diff --git a/bitcoinjs-lib/bitcoinjs-lib-tests.ts b/bitcoinjs-lib/bitcoinjs-lib-tests.ts index 9341d60c66..bdaee3ee83 100644 --- a/bitcoinjs-lib/bitcoinjs-lib-tests.ts +++ b/bitcoinjs-lib/bitcoinjs-lib-tests.ts @@ -1,63 +1,64 @@ /// -import bigi = require('bigi') +import bigi = require('bigi'); import bitcoin = require('bitcoinjs-lib'); declare var it: any; declare var describe: any; declare var assert: any; -describe('bitcoinjs-lib (basic)', function () { - it('can generate a random bitcoin address', function () { +describe('bitcoinjs-lib (basic)', () => { + it('can generate a random bitcoin address', () => { // for testing only - function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz') } + function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); } // generate random keyPair - var keyPair = bitcoin.ECPair.makeRandom({ rng: rng }) - var address = keyPair.getAddress() + var keyPair = bitcoin.ECPair.makeRandom({ rng }); + var address = keyPair.getAddress(); - assert.strictEqual(address, '1F5VhMHukdnUES9kfXqzPzMeF1GPHKiF64') - }) + assert.strictEqual(address, '1F5VhMHukdnUES9kfXqzPzMeF1GPHKiF64'); + }); - it('can generate an address from a SHA256 hash', function () { - var hash = bitcoin.crypto.sha256('correct horse battery staple') - var d = bigi.fromBuffer(hash) + it('can generate an address from a SHA256 hash', () => { + var hash = bitcoin.crypto.sha256('correct horse battery staple'); + var d = bigi.fromBuffer(hash); - var keyPair = new bitcoin.ECPair(d) - var address = keyPair.getAddress() + var keyPair = new bitcoin.ECPair(d); + var address = keyPair.getAddress(); - assert.strictEqual(address, '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8') - }) + assert.strictEqual(address, '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8'); + }); - it('can generate a random keypair for alternative networks', function () { + it('can generate a random keypair for alternative networks', () => { // for testing only - function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz') } + function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); } - var litecoin = bitcoin.networks.litecoin + var litecoin = bitcoin.networks.litecoin; - var keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng: rng }) - var wif = keyPair.toWIF() - var address = keyPair.getAddress() + var keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng }); + var wif = keyPair.toWIF(); + var address = keyPair.getAddress(); - assert.strictEqual(address, 'LZJSxZbjqJ2XVEquqfqHg1RQTDdfST5PTn') - assert.strictEqual(wif, 'T7A4PUSgTDHecBxW1ZiYFrDNRih2o7M8Gf9xpoCgudPF9gDiNvuS') - }) + assert.strictEqual(address, 'LZJSxZbjqJ2XVEquqfqHg1RQTDdfST5PTn'); + assert.strictEqual(wif, 'T7A4PUSgTDHecBxW1ZiYFrDNRih2o7M8Gf9xpoCgudPF9gDiNvuS'); + }); - it('can import an address via WIF', function () { - var keyPair = bitcoin.ECPair.fromWIF('Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct') - var address = keyPair.getAddress() + it('can import an address via WIF', () => { + var keyPair = bitcoin.ECPair.fromWIF('Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct'); + var address = keyPair.getAddress(); - assert.strictEqual(address, '19AAjaTUbRjQCMuVczepkoPswiZRhjtg31') - }) + assert.strictEqual(address, '19AAjaTUbRjQCMuVczepkoPswiZRhjtg31'); + }); - it('can create a Transaction', function () { - var keyPair = bitcoin.ECPair.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy') - var tx = new bitcoin.TransactionBuilder() + it('can create a Transaction', () => { + var keyPair = bitcoin.ECPair.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy'); + var tx = new bitcoin.TransactionBuilder(); - tx.addInput('aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31', 0) - tx.addOutput('1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK', 15000) - tx.sign(0, keyPair) + tx.addInput('aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31', 0); + tx.addOutput('1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK', 15000); + tx.sign(0, keyPair); - assert.strictEqual(tx.build().toHex(), '0100000001313eb630b128102b60241ca895f1d0ffca2170d5a0990e094f2182c102ab94aa000000006b483045022100aefbcf847900b01dd3e3debe054d3b6d03d715d50aea8525f5ea3396f168a1fb022013d181d05b15b90111808b22ef4f9ebe701caf2ab48db269691fdf4e9048f4f60121029f50f51d63b345039a290c94bffd3180c99ed659ff6ea6b1242bca47eb93b59fffffffff01983a0000000000001976a914ad618cf4333b3b248f9744e8e81db2964d0ae39788ac00000000') - }) -}) \ No newline at end of file + // tslint:disable-next-line:max-line-length + assert.strictEqual(tx.build().toHex(), '0100000001313eb630b128102b60241ca895f1d0ffca2170d5a0990e094f2182c102ab94aa000000006b483045022100aefbcf847900b01dd3e3debe054d3b6d03d715d50aea8525f5ea3396f168a1fb022013d181d05b15b90111808b22ef4f9ebe701caf2ab48db269691fdf4e9048f4f60121029f50f51d63b345039a290c94bffd3180c99ed659ff6ea6b1242bca47eb93b59fffffffff01983a0000000000001976a914ad618cf4333b3b248f9744e8e81db2964d0ae39788ac00000000'); + }); +}); diff --git a/bittorrent-protocol/bittorrent-protocol-tests.ts b/bittorrent-protocol/bittorrent-protocol-tests.ts index 1d73154565..1d0d17793a 100644 --- a/bittorrent-protocol/bittorrent-protocol-tests.ts +++ b/bittorrent-protocol/bittorrent-protocol-tests.ts @@ -1,20 +1,20 @@ import * as Protocol from 'bittorrent-protocol'; import * as net from 'net'; -net.createServer(function(socket) { +net.createServer(socket => { var wire = new Protocol(); // pipe to and from the protocol socket.pipe(wire).pipe(socket); - wire.on('handshake', function(infoHash, peerId) { + wire.on('handshake', (infoHash, peerId) => { // receive a handshake (infoHash and peerId are hex strings) // lets emit a handshake of our own as well wire.handshake('my info hash (hex)', 'my peer id (hex)'); }); - wire.on('unchoke', function() { + wire.on('unchoke', () => { console.log('peer is no longer choking us: ' + wire.peerChoking); }); }).listen(6881); diff --git a/bittorrent-protocol/tsconfig.json b/bittorrent-protocol/tsconfig.json index 65222bf056..9258205ba7 100644 --- a/bittorrent-protocol/tsconfig.json +++ b/bittorrent-protocol/tsconfig.json @@ -1,20 +1,22 @@ { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "bittorrent-protocol-tests.ts" - ] -} + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bittorrent-protocol-tests.ts" + ] +} \ No newline at end of file diff --git a/bittorrent-protocol/tslint.json b/bittorrent-protocol/tslint.json index ec365f164b..3c4a3237e8 100644 --- a/bittorrent-protocol/tslint.json +++ b/bittorrent-protocol/tslint.json @@ -1,3 +1,6 @@ { - "extends": "../tslint.json" + "extends": "../tslint.json", + "rules": { + "no-misused-new": false + } } diff --git a/blacklist/blacklist-tests.ts b/blacklist/blacklist-tests.ts index daff924403..0f465dd62a 100644 --- a/blacklist/blacklist-tests.ts +++ b/blacklist/blacklist-tests.ts @@ -1,13 +1,13 @@ -var someInput = { a: 1, b: 2, c: 3 } +var someInput = { a: 1, b: 2, c: 3 }; -import blacklist = require('blacklist') +import blacklist = require('blacklist'); -blacklist(someInput, 'b', 'c') +blacklist(someInput, 'b', 'c'); // => { a: 1 } blacklist(someInput, { a: true, // a will not be in the result b: false, // b will be in the result c: 1 > 2 // false, therefore c will be in the result -}) +}); // => { b: 2, c: 3 } \ No newline at end of file diff --git a/bluebird-global/tslint.json b/bluebird-global/tslint.json index eaffa3152c..b03221674a 100644 --- a/bluebird-global/tslint.json +++ b/bluebird-global/tslint.json @@ -1,9 +1,10 @@ { - "extends": "../tslint.json", - "rules": { - "no-empty-interface": false, - "array-type": false, - "unified-signatures": false, - "forbidden-types": false - } + "extends": "../tslint.json", + "rules": { + "max-line-length": false, + "no-empty-interface": false, + "array-type": false, + "unified-signatures": false, + "forbidden-types": false + } } diff --git a/body-parser/index.d.ts b/body-parser/index.d.ts index a11205f6f3..5fd2096c27 100644 --- a/body-parser/index.d.ts +++ b/body-parser/index.d.ts @@ -10,7 +10,7 @@ import { Request, RequestHandler, Response } from 'express'; // for docs go to https://github.com/expressjs/body-parser/tree/1.16.0#body-parser // @deprecated -declare function bodyParser(options?: bodyParser.OptionsJson | bodyParser.OptionsText | bodyParser.OptionsUrlencoded): RequestHandler; +declare function bodyParser(options?: bodyParser.OptionsJson & bodyParser.OptionsText & bodyParser.OptionsUrlencoded): RequestHandler; declare namespace bodyParser { @@ -42,6 +42,7 @@ declare namespace bodyParser { export function text(options?: OptionsText): RequestHandler; export function urlencoded(options?: OptionsUrlencoded): RequestHandler; + } -export = bodyParser; +export = bodyParser; \ No newline at end of file diff --git a/browser-bunyan/browser-bunyan-tests.ts b/browser-bunyan/browser-bunyan-tests.ts index 656a8eb002..ffb2ebf7a7 100644 --- a/browser-bunyan/browser-bunyan-tests.ts +++ b/browser-bunyan/browser-bunyan-tests.ts @@ -4,5 +4,5 @@ var log = bunyan.createLogger({ name: 'play', serializers: bunyan.stdSerializers }); -log.debug({foo: 'bar'}, 'hi at debug') -log.trace('hi at trace') +log.debug({foo: 'bar'}, 'hi at debug'); +log.trace('hi at trace'); diff --git a/bufferstream/bufferstream-tests.ts b/bufferstream/bufferstream-tests.ts index 5d2bcbd4c7..06cbd43e28 100644 --- a/bufferstream/bufferstream-tests.ts +++ b/bufferstream/bufferstream-tests.ts @@ -1,13 +1,13 @@ -import BufferStream = require('bufferstream') +import BufferStream = require('bufferstream'); -var stream = new BufferStream({encoding:'utf8', size:'flexible'}); +var stream = new BufferStream({encoding: 'utf8', size: 'flexible'}); stream.enable(); stream.disable(); stream.split('//', ':'); stream.on('split', (chunk: any, token: any) => { - console.log("got '%s' by '%s'", chunk.toString(), token.toString()) + console.log("got '%s' by '%s'", chunk.toString(), token.toString()); }); stream.write("buffer:stream//23"); console.log(stream.toString()); diff --git a/bufferstream/tslint.json b/bufferstream/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/bufferstream/tslint.json +++ b/bufferstream/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/camelcase-keys/camelcase-keys-tests.ts b/camelcase-keys/camelcase-keys-tests.ts index 2e8d7ab2d7..ed2865e9ce 100644 --- a/camelcase-keys/camelcase-keys-tests.ts +++ b/camelcase-keys/camelcase-keys-tests.ts @@ -1,10 +1,10 @@ import camelcaseKeys = require('camelcase-keys'); camelcaseKeys({'foo-bar': true}); -//=> {fooBar: true} +// => {fooBar: true} -camelcaseKeys({'foo-bar': true, nested: {unicorn_rainbow: true}}, {deep: true}); -//=> {fooBar: true, nested: {unicornRainbow: true}} +camelcaseKeys({'foo-bar': true, 'nested': {unicorn_rainbow: true}}, {deep: true}); +// => {fooBar: true, nested: {unicornRainbow: true}} -camelcaseKeys({_: [], 'foo-bar': true}); -//=> {_: [], fooBar: true} \ No newline at end of file +camelcaseKeys({'_': [], 'foo-bar': true}); +// => {_: [], fooBar: true} \ No newline at end of file diff --git a/chai-enzyme/chai-enzyme-tests.tsx b/chai-enzyme/chai-enzyme-tests.tsx index a70f7e7f96..1398db807d 100644 --- a/chai-enzyme/chai-enzyme-tests.tsx +++ b/chai-enzyme/chai-enzyme-tests.tsx @@ -40,5 +40,8 @@ expect(wrapper).to.have.data("test", "Test"); expect(wrapper).to.have.style("background", "green"); expect(wrapper).to.have.state("test", "test"); expect(wrapper).to.have.prop("test", 5); +expect(wrapper).to.have.props(["test1", "test2"]); +expect(wrapper).to.have.props({ test: 5 }); expect(wrapper).to.contain(); +expect(wrapper).to.containMatchingElement(); expect(wrapper).to.match(); diff --git a/chai-enzyme/index.d.ts b/chai-enzyme/index.d.ts index 6997abd5fe..0d9eb2994f 100644 --- a/chai-enzyme/index.d.ts +++ b/chai-enzyme/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for chai-enzyme 0.5.0 +// Type definitions for chai-enzyme 0.6.1 // Project: https://github.com/producthunt/chai-enzyme // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -39,6 +39,12 @@ declare namespace Chai { */ className(name: string): Assertion; + /** + * Assert that the wrapper contains a certain element: + * @param selector + */ + containMatchingElement(selector: EnzymeSelector): Assertion; + /** * Assert that the wrapper contains a descendant matching the given selector: * @param selector @@ -140,6 +146,18 @@ declare namespace Chai { * @param val */ prop(key: string, val?: any): Assertion; + + /** + * Assert that the wrapper has given props [with values]: + * @param keys + */ + props(keys: string[]): Assertion; + + /** + * Assert that the wrapper has given props [with values]: + * @param props + */ + props(props: EnzymeSelector): Assertion; } } diff --git a/chai-json-schema/chai-json-schema-tests.ts b/chai-json-schema/chai-json-schema-tests.ts index d0c1234e17..5d4715a76e 100644 --- a/chai-json-schema/chai-json-schema-tests.ts +++ b/chai-json-schema/chai-json-schema-tests.ts @@ -1,5 +1,3 @@ -/// - import { expect } from 'chai'; import { assert } from 'chai'; @@ -44,14 +42,14 @@ const fruitSchema = { } }; -//bdd style +// bdd style expect(goodApple).to.be.jsonSchema(fruitSchema); expect(badApple).to.not.be.jsonSchema(fruitSchema); goodApple.should.be.jsonSchema(fruitSchema); badApple.should.not.be.jsonSchema(fruitSchema); -//tdd style +// tdd style assert.jsonSchema(goodApple, fruitSchema); assert.notJsonSchema(badApple, fruitSchema); diff --git a/chai-oequal/tslint.json b/chai-oequal/tslint.json index cfdf2986e5..0b14fdec0d 100644 --- a/chai-oequal/tslint.json +++ b/chai-oequal/tslint.json @@ -1,6 +1,6 @@ { - "extends": "../tslint.json", - "rules": { - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false + } } diff --git a/chai-subset/chai-subset-tests.ts b/chai-subset/chai-subset-tests.ts index ded911ed19..33cf036cf8 100644 --- a/chai-subset/chai-subset-tests.ts +++ b/chai-subset/chai-subset-tests.ts @@ -8,7 +8,7 @@ var expect = chai.expect; var assert = chai.assert; function test_containSubset() { - var obj: Object = { + var obj = { a: 'b', c: 'd', e: { @@ -34,7 +34,7 @@ function test_containSubset() { } function test_notContainSubset() { - var obj: Object = { + var obj = { a: 'b', c: 'd', e: { @@ -50,16 +50,16 @@ function test_notContainSubset() { } function test_arrayContainSubset() { - var list: Array = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ]; + var list = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ]; - expect(list).to.containSubset([{a:'a', b: 'b'}]); - list.should.containSubset([{a:'a', b: 'b'}]); - assert.containSubset(list, [{a:'a', b: 'b'}]); + expect(list).to.containSubset([{a: 'a', b: 'b'}]); + list.should.containSubset([{a: 'a', b: 'b'}]); + assert.containSubset(list, [{a: 'a', b: 'b'}]); } function test_arrayNotContainSubset() { - var list: Array = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ]; + var list = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ]; - expect(list).not.to.containSubset([{a:'a', b: 'bd'}]); - list.should.not.containSubset([{a:'a', b: 'bd'}]); + expect(list).not.to.containSubset([{a: 'a', b: 'bd'}]); + list.should.not.containSubset([{a: 'a', b: 'bd'}]); } diff --git a/chai-subset/tslint.json b/chai-subset/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/chai-subset/tslint.json +++ b/chai-subset/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/chai-xml/chai-xml-tests.ts b/chai-xml/chai-xml-tests.ts index 492e671bbe..c217662316 100644 --- a/chai-xml/chai-xml-tests.ts +++ b/chai-xml/chai-xml-tests.ts @@ -2,10 +2,10 @@ import * as chai from 'chai'; import chaiXml = require('chai-xml'); chai.use(chaiXml); -let expect = chai.expect; +const expect = chai.expect; function test_chaiXml() { - let testXml = 'test'; + const testXml = 'test'; expect('nope').xml.not.to.be.valid(); expect(testXml).xml.to.be.valid(); expect(testXml).xml.to.equal('\ntest\n'); diff --git a/chai/index.d.ts b/chai/index.d.ts index 44750136c8..532aa3b579 100644 --- a/chai/index.d.ts +++ b/chai/index.d.ts @@ -358,6 +358,7 @@ declare namespace Chai { sameMembers(set1: any[], set2: any[], msg?: string): void; sameDeepMembers(set1: any[], set2: any[], msg?: string): void; includeMembers(superset: any[], subset: any[], msg?: string): void; + includeDeepMembers(superset: any[], subset: any[], msg?: string): void; ifError(val: any, msg?: string): void; diff --git a/charm/charm-tests.ts b/charm/charm-tests.ts index 0cdbdc8055..afc8cbc3b6 100644 --- a/charm/charm-tests.ts +++ b/charm/charm-tests.ts @@ -7,7 +7,7 @@ var colors: getCharm.CharmColor[] = [ 'red', 'cyan', 'yellow', 'green', 'blue' ] var text = 'Always after me lucky charms.'; var offset = 0; -var iv = setInterval(function () { +var iv = setInterval(() => { var y = 0, dy = 1; for (var i = 0; i < 40; i++) { var color = colors[(i + offset) % colors.length]; diff --git a/chart.js/index.d.ts b/chart.js/index.d.ts index 0830e68498..08781f4463 100644 --- a/chart.js/index.d.ts +++ b/chart.js/index.d.ts @@ -103,6 +103,7 @@ declare namespace Chart { animation?: ChartAnimationOptions; elements?: ChartElementsOptions; scales?: ChartScales; + cutoutPercentage?: number; } export interface ChartFontOptions { diff --git a/chrome/index.d.ts b/chrome/index.d.ts index 211375a3fe..b88ae5faf0 100644 --- a/chrome/index.d.ts +++ b/chrome/index.d.ts @@ -1831,7 +1831,7 @@ declare namespace chrome.devtools.panels { * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ - setObject(jsonObject: string, rootTitle?: string, callback?: () => void): void; + setObject(jsonObject: Object, rootTitle?: string, callback?: () => void): void; /** * Sets a JSON-compliant object to be displayed in the sidebar pane. * @param jsonObject An object to be displayed in context of the inspected page. Evaluated in the context of the caller (API client). @@ -1839,7 +1839,7 @@ declare namespace chrome.devtools.panels { * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ - setObject(jsonObject: string, callback?: () => void): void; + setObject(jsonObject: Object, callback?: () => void): void; /** * Sets an HTML page to be displayed in the sidebar pane. * @param path Relative path of an extension page to display within the sidebar. diff --git a/chunked-dc/chunked-dc-tests.ts b/chunked-dc/chunked-dc-tests.ts index 8e1ee9f00f..1bedf11c5a 100644 --- a/chunked-dc/chunked-dc-tests.ts +++ b/chunked-dc/chunked-dc-tests.ts @@ -1,11 +1,11 @@ // Chunker -let chunker = new Chunker(1337, Uint8Array.of(1,2,3), 2); -for (let chunk of chunker) { +let chunker = new Chunker(1337, Uint8Array.of(1, 2, 3), 2); +for (const chunk of chunker) { // Do smoething with chunk } while (chunker.hasNext) { - let chunk = chunker.next().value; + const chunk = chunker.next().value; } // Unchunker @@ -14,6 +14,6 @@ let unchunker = new Unchunker(); unchunker.onMessage = (message: Uint8Array, context: any[]) => { // Do something with the received message }; -let chunk = Uint8Array.of(1,2).buffer; +let chunk = Uint8Array.of(1, 2).buffer; unchunker.add(chunk); unchunker.gc(1024); diff --git a/chunked-dc/index.d.ts b/chunked-dc/index.d.ts index 2b38bef438..ab3acd6901 100644 --- a/chunked-dc/index.d.ts +++ b/chunked-dc/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for chunked-dc v0.1.2 +// Type definitions for chunked-dc 0.1 // Project: https://github.com/saltyrtc/chunked-dc-js // Definitions by: Danilo Bargen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -21,7 +21,7 @@ declare namespace chunkedDc { } interface ChunkerStatic { - new(id: number, message: Uint8Array, chunkSize: number): Chunker + new(id: number, message: Uint8Array, chunkSize: number): Chunker; } /** unchunker.ts **/ @@ -35,14 +35,14 @@ declare namespace chunkedDc { } interface UnchunkerStatic { - new(): Unchunker + new(): Unchunker; } /** main.ts **/ interface Standalone { - Chunker: ChunkerStatic, - Unchunker: UnchunkerStatic, + Chunker: ChunkerStatic; + Unchunker: UnchunkerStatic; } } diff --git a/chunked-dc/tsconfig.json b/chunked-dc/tsconfig.json index 0adf199b05..55832d5160 100644 --- a/chunked-dc/tsconfig.json +++ b/chunked-dc/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6" ], diff --git a/chunked-dc/tslint.json b/chunked-dc/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/chunked-dc/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/clipboard/clipboard-tests.ts b/clipboard/clipboard-tests.ts index 7521c651dd..5af2671671 100644 --- a/clipboard/clipboard-tests.ts +++ b/clipboard/clipboard-tests.ts @@ -17,12 +17,12 @@ var cb5 = new Clipboard('.btn', { cb1.destroy(); -cb2.on('success', function(e) { +cb2.on('success', e => { console.info('Action:', e.action); console.info('Text:', e.text); console.info('Trigger:', e.trigger); e.clearSelection(); }); -cb2.on('error', function(e) { }); +cb2.on('error', e => { }); diff --git a/clndr/clndr-tests.ts b/clndr/clndr-tests.ts index ca904f13b2..018d9a6000 100644 --- a/clndr/clndr-tests.ts +++ b/clndr/clndr-tests.ts @@ -1,6 +1,6 @@ import * as Clndr from 'clndr'; -let options: Clndr.ClndrOptions = { +const options: Clndr.ClndrOptions = { template: '', startWithMonth: "YYYY-MM-DD", weekOffset: 0, @@ -25,21 +25,21 @@ let options: Clndr.ClndrOptions = { adjacentMonth: "adjacent-month", }, clickEvents: { - click: function (target) { }, - today: function (month) { }, - nextMonth: function (month) { }, - previousMonth: function (month) { }, - onMonthChange: function (month) { }, - nextYear: function (month) { }, - previousYear: function (month) { }, - onYearChange: function (month) { }, - nextInterval: function (start, end) { }, - previousInterval: function (start, end) { }, - onIntervalChange: function (start, end) { } + click(target) { }, + today(month) { }, + nextMonth(month) { }, + previousMonth(month) { }, + onMonthChange(month) { }, + nextYear(month) { }, + previousYear(month) { }, + onYearChange(month) { }, + nextInterval(start, end) { }, + previousInterval(start, end) { }, + onIntervalChange(start, end) { } }, useTouchEvents: false, - ready: function () { }, - doneRendering: function () { }, + ready() { }, + doneRendering() { }, events: [], dateParameter: 'date', multiDayEvents: { @@ -59,7 +59,7 @@ let options: Clndr.ClndrOptions = { interval: 1 }, extras: { }, - render: function (data) { + render(data) { return '
'; }, constraints: { @@ -69,7 +69,13 @@ let options: Clndr.ClndrOptions = { moment: null }; -let myCalendar = $('.parent-element').clndr(options); +const myCalendar = $('.parent-element').clndr(options); + +myCalendar.options.constraints = { + startDate: '2017-12-22', + endDate: '2018-01-09' +}; +myCalendar.render(); myCalendar .forward() @@ -82,5 +88,5 @@ myCalendar .today() .setEvents([]) .addEvents([]) - .removeEvents(event => { return event.id === 'idToRemove'; }) + .removeEvents(event => event.id === 'idToRemove') .destroy(); \ No newline at end of file diff --git a/clndr/index.d.ts b/clndr/index.d.ts index 12d84a6088..3e9fbbb09c 100644 --- a/clndr/index.d.ts +++ b/clndr/index.d.ts @@ -13,6 +13,10 @@ export as namespace Clndr; * The clndr instance */ export interface ClndrInstance { + /** + * Get clndr options + */ + options: ClndrOptions; /** * Go to the next month */ @@ -55,6 +59,10 @@ export interface ClndrInstance { * calendar. */ removeEvents(filter: (event: any) => boolean): this; + /** + * Re-render of the calendar. + */ + render(): void; /** * Destroy the clndr instance. This will empty the DOM node containing the * calendar. diff --git a/co-views/co-views-tests.ts b/co-views/co-views-tests.ts index ec5f53ae7c..35f12bbe99 100644 --- a/co-views/co-views-tests.ts +++ b/co-views/co-views-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as views from 'co-views'; const render = views('views', { @@ -15,7 +12,6 @@ const locals = {}; // template locals data async function test() { const html = await render(fileName, locals); - console.log(html); } // or use generator diff --git a/co-views/index.d.ts b/co-views/index.d.ts index f5b8c3d3e0..5df2238c12 100644 --- a/co-views/index.d.ts +++ b/co-views/index.d.ts @@ -1,50 +1,44 @@ -// Type definitions for co-views v2.1 +// Type definitions for co-views 2.1 // Project: https://github.com/tj/co-views/ // Definitions by: devlee , Joshua DeVinney // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace CoViews { - - /** - * Pass views `dir` and `opts` to return a render function. - */ - export interface Views { - (dir?: string, opts?: CoViewsOptions): { (view: string, locals?: Object): any } - } - - export interface CoViewsOptions { + export interface Options { + /** + * default extname + */ + ext?: string; /** * default extname */ - ext?: string, - - /** - * default extname - */ - default?: string, + default?: string; /** * engine map */ - map?: Object, + map?: Object; /** * proxy partials */ - partials?: Object, + partials?: Object; /** * cache compiled templates */ - cache?: boolean, + cache?: boolean; /** * common locals data */ - locals?: Object + locals?: Object; } } -declare var CoViews: CoViews.Views; +/** + * Pass views `dir` and `opts` to return a render function. + */ +declare function CoViews(dir?: string, opts?: CoViews.Options): (view: string, locals?: Object) => any; export = CoViews; diff --git a/co-views/tsconfig.json b/co-views/tsconfig.json index a3aec989e0..5a319edbcf 100644 --- a/co-views/tsconfig.json +++ b/co-views/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6" ], diff --git a/co-views/tslint.json b/co-views/tslint.json new file mode 100644 index 0000000000..f05741c59b --- /dev/null +++ b/co-views/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/code/code-tests.ts b/code/code-tests.ts index f90d2c9eb7..c3455577d9 100644 --- a/code/code-tests.ts +++ b/code/code-tests.ts @@ -16,7 +16,7 @@ expect([1, 2, 3]).to.part.include([1, 4]); expect(10, "Age").to.be.above(5); -const func = function () { return arguments; }; +const func = function() { return arguments; }; expect(func()).to.be.arguments(); expect([1, 2]).to.be.an.array(); @@ -136,8 +136,7 @@ class CustomError extends Error { call: (message: string) => Error; } -const throws = function () { - +const throws = () => { throw new CustomError("Oh no!"); }; diff --git a/code/tslint.json b/code/tslint.json index 192203ab54..377cc837d4 100644 --- a/code/tslint.json +++ b/code/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/codependency/codependency-tests.ts b/codependency/codependency-tests.ts index 46f2db8d6d..e0f8a793a6 100644 --- a/codependency/codependency-tests.ts +++ b/codependency/codependency-tests.ts @@ -1,6 +1,3 @@ -/// -/// - let requirePeer = codependency.register(module), package: any; requirePeer = codependency.register(module, {index: ["dependencies", "devDependencies"]}); requirePeer = codependency.get("some-middleware"); diff --git a/codependency/tslint.json b/codependency/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/codependency/tslint.json +++ b/codependency/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/coinstring/coinstring-tests.ts b/coinstring/coinstring-tests.ts index ad1312d652..ab11a44fb7 100644 --- a/coinstring/coinstring-tests.ts +++ b/coinstring/coinstring-tests.ts @@ -1,69 +1,69 @@ /// -import cs = require('coinstring') +import cs = require('coinstring'); -var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd" -var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex') -var version = 0x80; //Bitcoin private key +var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd"; +var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex'); +var version = 0x80; // Bitcoin private key -console.log(cs.encode(privateKeyHexBuf, version)) +console.log(cs.encode(privateKeyHexBuf, version)); // => 5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD -var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8" //hash representing uncompressed -var hash160Buf = new Buffer(hash160, 'hex') -var version = 0x00; //Bitcoin public address +var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8"; // hash representing uncompressed +var hash160Buf = new Buffer(hash160, 'hex'); +var version = 0x00; // Bitcoin public address console.log(cs.encode(hash160Buf, version)); // => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS -var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd" +var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd"; -//for compressed, append "01" -privateKeyHex += '01' +// for compressed, append "01" +privateKeyHex += '01'; -var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex') -var version = 0x80 //Bitcoin private key +var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex'); +var version = 0x80; // Bitcoin private key -console.log(cs.encode(privateKeyHexBuf, version)) +console.log(cs.encode(privateKeyHexBuf, version)); // => KwomKti1X3tYJUUMb1TGSM2mrZk1wb1aHisUNHCQXTZq5auC2qc3 -var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8" //hash representing uncompressed -var hash160Buf = new Buffer(hash160, 'hex') -var version = 0x1E //Dogecoin public address +var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8"; // hash representing uncompressed +var hash160Buf = new Buffer(hash160, 'hex'); +var version = 0x1E; // Dogecoin public address -console.log(cs.encode(hash160Buf, version)) +console.log(cs.encode(hash160Buf, version)); // => DAcq9oJpZZAjr56RmF7Y5zmWboZWQ4HAsW -var data = "000000000000000000873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d50800e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35" -var buffer = new Buffer(data, 'hex') -var versionBuffer = new Buffer('0488ade4', 'hex') //0488ade4 is a consant listed in the aforementioned bip32 wiki. +var data = "000000000000000000873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d50800e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35"; +var buffer = new Buffer(data, 'hex'); +var versionBuffer = new Buffer('0488ade4', 'hex'); // 0488ade4 is a consant listed in the aforementioned bip32 wiki. -console.log(cs.encode(buffer, versionBuffer)) +console.log(cs.encode(buffer, versionBuffer)); // => xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd"; -var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex') -var version = 0x80 //Bitcoin private key +var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex'); +var version = 0x80; // Bitcoin private key -var toBtcWif = cs.createEncoder(version) +var toBtcWif = cs.createEncoder(version); -//later in your program -console.log(toBtcWif(privateKeyHexBuf)) +// later in your program +console.log(toBtcWif(privateKeyHexBuf)); // => 5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD -var wif = "5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD" -var version = 0x80 //Bitcoin private key +var wif = "5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD"; +var version = 0x80; // Bitcoin private key -var fromBtcWif = cs.createDecoder(version) +var fromBtcWif = cs.createDecoder(version); -var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8" //hash representing uncompressed -var hash160Buf = new Buffer(hash160, 'hex') -var version = 0x6F //Bitcoin Testnet Address +var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8"; // hash representing uncompressed +var hash160Buf = new Buffer(hash160, 'hex'); +var version = 0x6F; // Bitcoin Testnet Address -var testnetAddressValidator = cs.createValidator(version) -console.log(testnetAddressValidator("mkzgubTA5Ahi6BPSkE6MN9pEafRutznkMe")) // => true \ No newline at end of file +var testnetAddressValidator = cs.createValidator(version); +console.log(testnetAddressValidator("mkzgubTA5Ahi6BPSkE6MN9pEafRutznkMe")); // => true \ No newline at end of file diff --git a/colors/tslint.json b/colors/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/colors/tslint.json +++ b/colors/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/combined-stream/combined-stream-tests.ts b/combined-stream/combined-stream-tests.ts new file mode 100644 index 0000000000..776e530e63 --- /dev/null +++ b/combined-stream/combined-stream-tests.ts @@ -0,0 +1,30 @@ +import * as CombinedStream from "combined-stream"; +import { createReadStream, createWriteStream } from "fs"; + +const stream1 = new CombinedStream(); + +stream1.append(createReadStream("tsconfig.json")); +stream1.append(createReadStream("tslint.json")); +stream1.append(createReadStream("index.d.ts")); + +stream1.pipe(createWriteStream("combined.txt")); + +const stream2 = CombinedStream.create({ + maxDataSize: 1 << 32, + pauseStreams: false, +}); + +stream1.destroy(); + +// should log true +console.log(CombinedStream.isStreamLike(stream2)); + +stream2.on("data", (data) => { + console.log(data); +}); + +stream2.pipe(createWriteStream("combined.txt")); + +stream2.write(CombinedStream.name); + +stream2.destroy(); diff --git a/combined-stream/index.d.ts b/combined-stream/index.d.ts new file mode 100644 index 0000000000..cada758701 --- /dev/null +++ b/combined-stream/index.d.ts @@ -0,0 +1,56 @@ +// Type definitions for combined-stream 1.0 +// Project: https://github.com/felixge/node-combined-stream +// Definitions by: Felix Geisendörfer , Tomek Łaziuk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Stream } from "stream"; + +declare class CombinedStream extends Stream implements CombinedStream.Options { + readonly writable: boolean; + readonly readable: boolean; + readonly dataSize: number; + maxDataSize: number; + pauseStreams: boolean; + append(stream: NodeJS.ReadableStream | NodeJS.WritableStream | Buffer | string): this; + write(data: any): void; + pause(): void; + resume(): void; + end(): void; + destroy(): void; + + // private properties + _released: boolean; + // @TODO it should be a type of Array<'delayed-stream' instance | Buffer | string> + _streams: Array; + _currentStream: Stream | Buffer | string | null; + _getNext(): void; + _pipeNext(): void; + _handleErrors(stream: NodeJS.EventEmitter): void; + _reset(): void; + _checkDataSize(): void; + _updateDataSize(): void; + _emitError(error: Error): void; + + // events + on(event: "close" | "end" | "resume" | "pause", cb: () => void): this; + on(event: "error", cb: (err: Error) => void): this; + on(event: "data", cb: (data: any) => void): this; + once(event: "close" | "end" | "resume" | "pause", cb: () => void): this; + once(event: "error", cb: (err: Error) => void): this; + once(event: "data", cb: (data: any) => void): this; +} + +declare namespace CombinedStream { + export interface Options { + maxDataSize?: number; + pauseStreams?: boolean; + } + + export function create(options?: Options): CombinedStream; + + export function isStreamLike(stream: any): stream is Stream; +} + +export = CombinedStream; diff --git a/combined-stream/tsconfig.json b/combined-stream/tsconfig.json new file mode 100644 index 0000000000..5ffd68770c --- /dev/null +++ b/combined-stream/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "combined-stream-tests.ts" + ] +} diff --git a/combined-stream/tslint.json b/combined-stream/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/combined-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/comment-json/tsconfig.json b/comment-json/tsconfig.json index 342694cbb3..314e9c0143 100644 --- a/comment-json/tsconfig.json +++ b/comment-json/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "comment-json-tests.ts" ] -} +} \ No newline at end of file diff --git a/concat-stream/concat-stream-tests.ts b/concat-stream/concat-stream-tests.ts index 6dac3129f0..4f3bf839e0 100644 --- a/concat-stream/concat-stream-tests.ts +++ b/concat-stream/concat-stream-tests.ts @@ -1,4 +1,4 @@ -import concat = require("concat-stream") +import concat = require("concat-stream"); import { Readable } from "stream"; @@ -14,7 +14,7 @@ class MyReadable extends Readable { } } -let myReadable = new MyReadable(); +const myReadable = new MyReadable(); myReadable.pipe(concat((buf) => console.log(buf.toString()))); myReadable.pipe(concat({}, (buf) => console.log(buf.toString()))); diff --git a/conf/tsconfig.json b/conf/tsconfig.json index 8bb74358fa..8ef2367ca4 100644 --- a/conf/tsconfig.json +++ b/conf/tsconfig.json @@ -5,6 +5,7 @@ "es6", "dom" ], + "target": "es6", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, diff --git a/configstore/configstore-tests.ts b/configstore/configstore-tests.ts index 0d8e777fe0..724dbe9a38 100644 --- a/configstore/configstore-tests.ts +++ b/configstore/configstore-tests.ts @@ -6,7 +6,7 @@ var value: any; var key: string; var num: number; var bool: any; -var object:Object; +var object: any; cs.set(key, value); value = cs.get(key); diff --git a/configstore/tslint.json b/configstore/tslint.json index f9e30021f4..377cc837d4 100644 --- a/configstore/tslint.json +++ b/configstore/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/connect-ensure-login/tslint.json b/connect-ensure-login/tslint.json index f9e30021f4..377cc837d4 100644 --- a/connect-ensure-login/tslint.json +++ b/connect-ensure-login/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/convert-source-map/convert-source-map-tests.ts b/convert-source-map/convert-source-map-tests.ts index 1a6df7df10..96a638ca93 100644 --- a/convert-source-map/convert-source-map-tests.ts +++ b/convert-source-map/convert-source-map-tests.ts @@ -1,6 +1,7 @@ - import convert = require("convert-source-map"); +// tslint:disable:max-line-length + var json = convert .fromComment('//@ sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9vLmpzIiwic291cmNlcyI6WyJjb25zb2xlLmxvZyhcImhpXCIpOyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=') .toJSON(); diff --git a/convert-source-map/tslint.json b/convert-source-map/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/convert-source-map/tslint.json +++ b/convert-source-map/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/cookies/cookies-tests.ts b/cookies/cookies-tests.ts index 21e81b49de..30e07d3000 100644 --- a/cookies/cookies-tests.ts +++ b/cookies/cookies-tests.ts @@ -7,29 +7,29 @@ const server = http.createServer((req, res) => { const cookies = new Cookies(req, res); let unsigned: string, signed: string, - tampered: string + tampered: string; - if (req.url == "/set") { + if (req.url === "/set") { cookies // set a regular cookie .set("unsigned", "foo", { httpOnly: false }) - - // set a signed cookie - .set("signed", "bar", { signed: true }) - - // mimic a signed cookie, but with a bogus signature - .set("tampered", "baz") - .set("tampered.sig", "bogus") - res.writeHead(302, { "Location": "/" }) - return res.end("Now let's check.") + // set a signed cookie + .set("signed", "bar", { signed: true }) + + // mimic a signed cookie, but with a bogus signature + .set("tampered", "baz") + .set("tampered.sig", "bogus"); + + res.writeHead(302, { Location: "/" }); + return res.end("Now let's check."); } - unsigned = cookies.get("unsigned") - signed = cookies.get("signed", { signed: true }) - tampered = cookies.get("tampered", { signed: true }) + unsigned = cookies.get("unsigned"); + signed = cookies.get("signed", { signed: true }); + tampered = cookies.get("tampered", { signed: true }); - res.writeHead(200, { "Content-Type": "text/plain" }) + res.writeHead(200, { "Content-Type": "text/plain" }); res.end( "unsigned expected: foo\n\n" + "unsigned actual: " + unsigned + "\n\n" + @@ -37,5 +37,5 @@ const server = http.createServer((req, res) => { "signed actual: " + signed + "\n\n" + "tampered expected: undefined\n\n" + "tampered: " + tampered + "\n\n" - ) -}) \ No newline at end of file + ); +}); \ No newline at end of file diff --git a/cordova-sqlite-storage/cordova-sqlite-storage-tests.ts b/cordova-sqlite-storage/cordova-sqlite-storage-tests.ts index 31c334afca..bb5a768bf8 100644 --- a/cordova-sqlite-storage/cordova-sqlite-storage-tests.ts +++ b/cordova-sqlite-storage/cordova-sqlite-storage-tests.ts @@ -1,5 +1,3 @@ -/// - // examples taken from https://github.com/litehelpers/Cordova-sqlite-storage function echoTestFunction() { function successCallback(value: string) { @@ -33,26 +31,26 @@ function openingDatabase() { } function openingDatabase2() { - window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'}, function(db) { - db.transaction(function(tx) { + window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'}, db => { + db.transaction(tx => { // ... - }, function(err) { + }, err => { console.log('Open database ERROR: ' + JSON.stringify(err)); }); }); } function singleStatementTransactions(db: SQLitePlugin.Database) { - db.executeSql('INSERT INTO MyTable VALUES (?)', ['test-value'], function (resultSet) { + db.executeSql('INSERT INTO MyTable VALUES (?)', ['test-value'], resultSet => { console.log('resultSet.insertId: ' + resultSet.insertId); console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected); - }, function(error) { + }, error => { console.log('SELECT error: ' + error.message); }); - db.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], function (resultSet) { + db.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], resultSet => { console.log('got stringlength: ' + resultSet.rows.item(0).stringlength); - }, function(error) { + }, error => { console.log('SELECT error: ' + error.message); }); } @@ -62,40 +60,40 @@ function sqlBatchTransactions(db: SQLitePlugin.Database) { 'DROP TABLE IF EXISTS MyTable', 'CREATE TABLE MyTable (SampleColumn)', [ 'INSERT INTO MyTable VALUES (?)', ['test-value'] ], - ], function() { - db.executeSql('SELECT * FROM MyTable', [], function (resultSet) { + ], () => { + db.executeSql('SELECT * FROM MyTable', [], resultSet => { console.log('Sample column value: ' + resultSet.rows.item(0).SampleColumn); }); - }, function(error) { + }, error => { console.log('Populate table error: ' + error.message); }); } function asynchronousTransaction(db: SQLitePlugin.Database) { - db.transaction(function(tx) { + db.transaction(tx => { tx.executeSql('DROP TABLE IF EXISTS MyTable'); tx.executeSql('CREATE TABLE MyTable (SampleColumn)'); - tx.executeSql('INSERT INTO MyTable VALUES (?)', ['test-value'], function(tx, resultSet) { + tx.executeSql('INSERT INTO MyTable VALUES (?)', ['test-value'], (tx, resultSet) => { console.log('resultSet.insertId: ' + resultSet.insertId); console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected); - }, function(tx, error) { + }, (tx, error) => { console.log('INSERT error: ' + error.message); }); - }, function(error) { + }, error => { console.log('transaction error: ' + error.message); - }, function() { + }, () => { console.log('transaction ok'); }); - db.readTransaction(function(tx) { - tx.executeSql("SELECT UPPER('Some US-ASCII text') AS uppertext", [], function(tx, resultSet) { + db.readTransaction(tx => { + tx.executeSql("SELECT UPPER('Some US-ASCII text') AS uppertext", [], (tx, resultSet) => { console.log("resultSet.rows.item(0).uppertext: " + resultSet.rows.item(0).uppertext); - }, function(tx, error) { + }, (tx, error) => { console.log('SELECT error: ' + error.message); }); - }, function(error) { + }, error => { console.log('transaction error: ' + error.message); - }, function() { + }, () => { console.log('transaction ok'); }); } @@ -108,28 +106,28 @@ function sampleWithPRAGMA() { function onDeviceReady() { var db = window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'}); - db.transaction(function(tx) { + db.transaction(tx => { tx.executeSql('DROP TABLE IF EXISTS test_table'); tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)'); // demonstrate PRAGMA: - db.executeSql("pragma table_info (test_table);", [], function(res) { + db.executeSql("pragma table_info (test_table);", [], res => { console.log("PRAGMA res: " + JSON.stringify(res)); }); - tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) { + tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], (tx, res) => { console.log("insertId: " + res.insertId + " -- probably 1"); console.log("rowsAffected: " + res.rowsAffected + " -- should be 1"); - db.transaction(function(tx) { - tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) { + db.transaction(tx => { + tx.executeSql("select count(id) as cnt from test_table;", [], (tx, res) => { console.log("res.rows.length: " + res.rows.length + " -- should be 1"); console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1"); }); }); // }, function(e) { // probably example in https://github.com/litehelpers/Cordova-sqlite-storage is broken - }, function(_tx, e) { + }, (_tx, e) => { console.log("ERROR: " + e.message); }); }); @@ -145,20 +143,20 @@ function sampleWithTransactionLevelNesting() { function onDeviceReady() { var db = window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'}); - db.transaction(function(tx) { + db.transaction(tx => { tx.executeSql('DROP TABLE IF EXISTS test_table'); tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)'); - tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) { + tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], (tx, res) => { console.log("insertId: " + res.insertId + " -- probably 1"); console.log("rowsAffected: " + res.rowsAffected + " -- should be 1"); - tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) { + tx.executeSql("select count(id) as cnt from test_table;", [], (tx, res) => { console.log("res.rows.length: " + res.rows.length + " -- should be 1"); console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1"); }); - }, function(tx, e) { + }, (tx, e) => { console.log("ERROR: " + e.message); }); }); @@ -177,18 +175,18 @@ function dbClose(db: SQLitePlugin.Database) { db.close(successcb, errorcb); - db.transaction(function (tx) { - tx.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], function (tx, res) { + db.transaction(tx => { + tx.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], (tx, res) => { console.log('got stringlength: ' + res.rows.item(0).stringlength); }); - }, function (error) { + }, error => { // OK to close here: console.log('transaction error: ' + error.message); db.close(); - }, function () { + }, () => { // OK to close here: console.log('transaction ok'); - db.close(function () { + db.close(() => { console.log('database is closed ok'); }); }); @@ -207,11 +205,11 @@ function deleteDatabase() { function quickInstallationTest() { - window.sqlitePlugin.openDatabase({ name: 'hello-world.db', location: 'default' }, function (db) { - db.executeSql("select length('tenletters') as stringlength", [], function (res) { + window.sqlitePlugin.openDatabase({ name: 'hello-world.db', location: 'default' }, db => { + db.executeSql("select length('tenletters') as stringlength", [], res => { var stringlength = res.rows.item(0).stringlength; console.log('got stringlength: ' + stringlength); - //document.getElementById('deviceready').querySelector('.received').innerHTML = 'stringlength: ' + stringlength; + // document.getElementById('deviceready').querySelector('.received').innerHTML = 'stringlength: ' + stringlength; }); }); } diff --git a/cordova-sqlite-storage/tslint.json b/cordova-sqlite-storage/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/cordova-sqlite-storage/tslint.json +++ b/cordova-sqlite-storage/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/core-decorators/core-decorators-tests.ts b/core-decorators/core-decorators-tests.ts index 86df21fc6d..04a22c19cf 100644 --- a/core-decorators/core-decorators-tests.ts +++ b/core-decorators/core-decorators-tests.ts @@ -17,8 +17,8 @@ class Person { } } -let person = new Person(); -let { getPerson, getPersonAgain } = person; +const person = new Person(); +const { getPerson, getPersonAgain } = person; getPerson() === person; @@ -81,7 +81,7 @@ class Person2 { facepalmHarder() {} } -let person2 = new Person2(); +const person2 = new Person2(); person2.facepalm(); // DEPRECATION Person#facepalm: This function will be removed in future versions. @@ -144,7 +144,7 @@ class Person3 { } } -let person3 = new Person3(); +const person3 = new Person3(); person3.facepalmWithoutWarning(); // no warning is logged @@ -242,7 +242,7 @@ editor.hugeBuffer; // already initialized and equals our buffer, so // createHugeBuffer() is not called again -//TODO: For @mixin, I don't know how we can make it work for TypeScript... +// TODO: For @mixin, I don't know how we can make it work for TypeScript... // // @mixin (alias: @mixins) // @@ -265,7 +265,7 @@ const FlyMixin = { @mixin(SingerMixin, FlyMixin) class Bird { singMatingCall() { - //TODO: For @mixin, I don't know how we can make it work for TypeScript... + // TODO: For @mixin, I don't know how we can make it work for TypeScript... // this.sing('tweet tweet'); } } @@ -280,10 +280,10 @@ bird.singMatingCall(); import { time } from 'core-decorators'; -let myConsole = { - time: function(label: string) { /* custom time() method */ }, - timeEnd: function(label: string) { /* custom timeEnd method */ }, - log: function(str: any) { /* custom log method */ } +const myConsole = { + time(label: string) { /* custom time() method */ }, + timeEnd(label: string) { /* custom timeEnd method */ }, + log(str: any) { /* custom log method */ } }; class Bird2 { diff --git a/core-decorators/index.d.ts b/core-decorators/index.d.ts index 18fcc95a27..d0a51009eb 100644 --- a/core-decorators/index.d.ts +++ b/core-decorators/index.d.ts @@ -1,8 +1,8 @@ -// Type definitions for core-decorators.js v0.10 +// Type definitions for core-decorators.js 0.10 // Project: https://github.com/jayphelps/core-decorators.js // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.1 export interface ClassDecorator { (target: TFunction): TFunction | void; diff --git a/core-decorators/tsconfig.json b/core-decorators/tsconfig.json index dee0784eed..1c0b389c96 100644 --- a/core-decorators/tsconfig.json +++ b/core-decorators/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/core-decorators/tslint.json b/core-decorators/tslint.json new file mode 100644 index 0000000000..0332a8383e --- /dev/null +++ b/core-decorators/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "callable-types": false, + "forbidden-types": false + } +} diff --git a/crc/crc-tests.ts b/crc/crc-tests.ts index b279bc6fad..36f5c023b6 100644 --- a/crc/crc-tests.ts +++ b/crc/crc-tests.ts @@ -1,5 +1,5 @@ -import * as crc from "crc" -import * as fs from "fs" +import * as crc from "crc"; +import * as fs from "fs"; // tests move from the readme of the module diff --git a/cryptojs/test/sha1-tests.ts b/cryptojs/test/sha1-tests.ts index 50dfe1992b..fa05f3289d 100644 --- a/cryptojs/test/sha1-tests.ts +++ b/cryptojs/test/sha1-tests.ts @@ -31,7 +31,7 @@ YUI.add('algo-sha1-test', function (Y) { Y.Assert.areEqual('761c457bf73b14d27e9e9265c46f4b4dda11f940', C.SHA1('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789').toString()); }, - testVector7: function () { + testVector7() { Y.Assert.areEqual('50abf5706a150990a08b2c5ea40fa0e585554732', C.SHA1('12345678901234567890123456789012345678901234567890123456789012345678901234567890').toString()); }, diff --git a/csv-stringify/csv-stringify-tests.ts b/csv-stringify/csv-stringify-tests.ts index 7ffd1f6e3e..bd6873affb 100644 --- a/csv-stringify/csv-stringify-tests.ts +++ b/csv-stringify/csv-stringify-tests.ts @@ -19,6 +19,6 @@ stream = stringify({ delimiter: "," }); stream.write(["1", "2", "3"]); -let transform: NodeJS.ReadWriteStream = stream; +const transform: NodeJS.ReadWriteStream = stream; stream = stringify(); diff --git a/csv-stringify/index.d.ts b/csv-stringify/index.d.ts index fcf3321319..e65695c059 100644 --- a/csv-stringify/index.d.ts +++ b/csv-stringify/index.d.ts @@ -8,7 +8,9 @@ declare namespace stringify { interface StringifyOpts { /** - * List of fields, applied when transform returns an object, order matters, read the transformer documentation for additionnal information, columns are auto discovered when the user write object, see the "header" option on how to print columns names on the first line. + * List of fields, applied when transform returns an object. + * Order matters, read the transformer documentation for additionnal information, + * columns are auto discovered when the user write object, see the "header" option on how to print columns names on the first line. */ columns?: string[]; /** @@ -28,7 +30,8 @@ declare namespace stringify { */ header?: boolean; /** - * String used to delimit record rows or a special value; special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). + * String used to delimit record rows or a special value; + * special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). */ lineBreaks?: string; /** @@ -48,7 +51,8 @@ declare namespace stringify { */ quotedString?: boolean; /** - * String used to delimit record rows or a special value; special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). + * String used to delimit record rows or a special value; + * special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). */ rowDelimiter?: string; diff --git a/cucumber/cucumber-tests.ts b/cucumber/cucumber-tests.ts index dd92ee7c19..87089671ae 100644 --- a/cucumber/cucumber-tests.ts +++ b/cucumber/cucumber-tests.ts @@ -9,6 +9,12 @@ function StepSample() { var step = this; var hook = this; + hook.setWorldConstructor(function() { + this.visit = function(url: string, callback: Callback) { + callback(null, 'pending'); + } + }) + hook.Before(function(scenario: HookScenario, callback: Callback){ scenario.isFailed() && callback.pending(); }); diff --git a/cucumber/index.d.ts b/cucumber/index.d.ts index 154e6707cc..a8b85539ce 100644 --- a/cucumber/index.d.ts +++ b/cucumber/index.d.ts @@ -69,6 +69,7 @@ declare namespace cucumber { After(code: HookCode): void; Around(code: AroundCode):void; setDefaultTimeout(time:number): void; + setWorldConstructor(world: () => void): void; registerHandler(handlerOption:string, code:(event:any, callback:CallbackStepDefinition) =>void): void; registerListener(listener: EventListener): void; } @@ -207,7 +208,7 @@ declare namespace cucumber { } export interface SupportCodeConsumer { - (stepDefinitions:StepDefinitions | Hooks):void; + (stepDefinitions:StepDefinitions & Hooks):void; } export function defineSupportCode(consumer:SupportCodeConsumer): void; diff --git a/d3-array/d3-array-tests.ts b/d3-array/d3-array-tests.ts index 26ef2d3ef5..74b749bea3 100644 --- a/d3-array/d3-array-tests.ts +++ b/d3-array/d3-array-tests.ts @@ -15,23 +15,22 @@ import { timeYear } from 'd3-time'; // ----------------------------------------------------------------------------- class NumCoercible { - public a: number; + a: number; constructor(a: number) { this.a = a; } - public valueOf() { + valueOf() { return this.a; } } - class MixedObject { - public num: number; - public str: string; - public numeric: NumCoercible; - public date: Date; + num: number; + str: string; + numeric: NumCoercible; + date: Date; constructor(a: number, date: Date) { this.num = a; @@ -40,29 +39,58 @@ class MixedObject { this.date = date; } } + let num: number; -let str: string; -let numeric: NumCoercible; let date: Date; -let extentNum: [number, number]; -let extentStr: [string, string]; -let extentNumeric: [NumCoercible, NumCoercible]; -let extentDateMixed: [d3Array.Primitive, d3Array.Primitive]; -let extentMixed: [d3Array.Primitive | NumCoercible, d3Array.Primitive | NumCoercible]; -let extentDate: [Date, Date]; + +let numOrUndefined: number | undefined; +let strOrUndefined: string | undefined; +let numericOrUndefined: NumCoercible | undefined; +let dateOrUndefined: Date | undefined; +let numOrUndefinedExtent: [number, number] | [undefined, undefined]; +let strOrUndefinedExtent: [string, string] | [undefined, undefined]; +let numericOrUndefinedExtent: [NumCoercible, NumCoercible] | [undefined, undefined]; +let dateMixedOrUndefined: [Date , Date] | [undefined, undefined]; +let mixedOrUndefinedExtent: [d3Array.Primitive | NumCoercible, d3Array.Primitive | NumCoercible] | [undefined, undefined]; +let dateOrUndefinedExtent: [Date, Date] | [undefined, undefined]; let numbersArray = [10, 20, 30, 40, 50]; -let stringyNumbersArray = ['10', '20', '30', '40', '50']; -let numericArray = [new NumCoercible(10), new NumCoercible(20), new NumCoercible(30), new NumCoercible(40), new NumCoercible(50)]; -let dateArray = [new Date(2016, 6, 1), new Date(2016, 7, 30), new Date(2015, 3, 15)]; -let mixedObjectArray = [ +const numbersOrUndefinedArray = [10, 20, undefined, null, 40, 50]; +const stringyNumbersArray = ['10', '20', '30', '40', '50']; +const numericArray = [new NumCoercible(10), new NumCoercible(20), new NumCoercible(30), new NumCoercible(40), new NumCoercible(50)]; +const dateArray = [new Date(2016, 6, 1), new Date(2016, 7, 30), new Date(2015, 3, 15)]; +const mixedObjectArray = [ new MixedObject(10, new Date(2016, 6, 1)), new MixedObject(20, new Date(2016, 7, 30)), new MixedObject(30, new Date(2015, 3, 15)), new MixedObject(40, new Date(2014, 3, 15)), new MixedObject(50, new Date(2017, 4, 15)) ]; +const mixedObjectOrUndefinedArray = [...mixedObjectArray, undefined]; +function accessorMixedObjectToNum(datum: MixedObject, index: number, array: MixedObject[]): number { + return datum.num; +} + +function accessorMixedObjectToStr(datum: MixedObject, index: number, array: MixedObject[]): string { + return datum.str; +} + +function accessorMixedObjectToNumeric(datum: MixedObject, index: number, array: MixedObject[]): NumCoercible { + return datum.numeric; +} + +function accessorMixedObjectToDate(datum: MixedObject, index: number, array: MixedObject[]): Date { + return datum.date; +} + +function accessorMixedObjectToNumOrUndefined(datum: MixedObject | undefined, index: number, array: Array): number | undefined | null { + return datum ? datum.num : undefined; +} + +function accessorMixedObjectToStrOrUndefined(datum: MixedObject | undefined, index: number, array: MixedObject[]): string | undefined | null { + return datum ? datum.str : undefined; +} // ----------------------------------------------------------------------------- // Test Statistics @@ -72,186 +100,109 @@ let mixedObjectArray = [ // without accessors -num = d3Array.max(numbersArray); -str = d3Array.max(stringyNumbersArray); -numeric = d3Array.max(numericArray); -date = d3Array.max(dateArray); +numOrUndefined = d3Array.max(numbersArray); +strOrUndefined = d3Array.max(stringyNumbersArray); +numericOrUndefined = d3Array.max(numericArray); +dateOrUndefined = d3Array.max(dateArray); // with accessors -num = d3Array.max(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); - -str = d3Array.max(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.str; -}); - -numeric = d3Array.max(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.numeric; -}); - -date = d3Array.max(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.date; -}); +numOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNum); +strOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToStr); +numericOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNumeric); +dateOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToDate); +numOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNumOrUndefined); +strOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToStrOrUndefined); // min() ----------------------------------------------------------------------- // without accessors -num = d3Array.min(numbersArray); -str = d3Array.min(stringyNumbersArray); -numeric = d3Array.min(numericArray); -date = d3Array.min(dateArray); +numOrUndefined = d3Array.min(numbersArray); +strOrUndefined = d3Array.min(stringyNumbersArray); +numericOrUndefined = d3Array.min(numericArray); +dateOrUndefined = d3Array.min(dateArray); // with accessors -num = d3Array.min(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); - -str = d3Array.min(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.str; -}); - -numeric = d3Array.min(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.numeric; -}); - -date = d3Array.min(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.date; -}); +numOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNum); +strOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToStr); +numericOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNumeric); +dateOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToDate); +numOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNumOrUndefined); +strOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToStrOrUndefined); // extent() -------------------------------------------------------------------- // without accessors -extentNum = d3Array.extent(numbersArray); -extentStr = d3Array.extent(stringyNumbersArray); -extentNumeric = d3Array.extent(numericArray); -extentDate = d3Array.extent(dateArray); -extentMixed = d3Array.extent([new NumCoercible(10), 13, '12', true]); +numOrUndefinedExtent = d3Array.extent(numbersArray); +strOrUndefinedExtent = d3Array.extent(stringyNumbersArray); +numericOrUndefinedExtent = d3Array.extent(numericArray); +dateOrUndefinedExtent = d3Array.extent(dateArray); // with accessors -extentNum = d3Array.extent(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); - -extentStr = d3Array.extent(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.str; -}); - -extentMixed = d3Array.extent(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.numeric; -}); - -extentDateMixed = d3Array.extent(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.date; -}); +numOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToNum); +strOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToStr); +mixedOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToNumeric); +dateMixedOrUndefined = d3Array.extent(mixedObjectArray, accessorMixedObjectToDate); +numOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToNumOrUndefined); +strOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToStrOrUndefined); // mean() ---------------------------------------------------------------------- -num = d3Array.mean(numbersArray); +numOrUndefined = d3Array.mean(numbersArray); +numOrUndefined = d3Array.mean(numericArray); +numOrUndefined = d3Array.mean(numbersOrUndefinedArray); -num = d3Array.mean(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); +numOrUndefined = d3Array.mean(mixedObjectArray, accessorMixedObjectToNum); +numOrUndefined = d3Array.mean(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // median() -------------------------------------------------------------------- -num = d3Array.median(numbersArray); +numOrUndefined = d3Array.median(numbersArray); +numOrUndefined = d3Array.median(numericArray); +numOrUndefined = d3Array.median(numbersOrUndefinedArray); -num = d3Array.median(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); +numOrUndefined = d3Array.median(mixedObjectArray, accessorMixedObjectToNum); +numOrUndefined = d3Array.median(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // quantile() ------------------------------------------------------------------ -num = d3Array.quantile(numbersArray, 0.5); +numOrUndefined = d3Array.quantile(numbersArray, 0.5); +numOrUndefined = d3Array.quantile(numericArray, 0.5); +numOrUndefined = d3Array.quantile(numbersOrUndefinedArray, 0.5); -num = d3Array.quantile(mixedObjectArray, 0.5, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); +numOrUndefined = d3Array.quantile(mixedObjectArray, 0.5, accessorMixedObjectToNum); +numOrUndefined = d3Array.quantile(mixedObjectOrUndefinedArray, 0.5, accessorMixedObjectToNumOrUndefined); // sum() ----------------------------------------------------------------------- +numOrUndefined = d3Array.sum(numbersArray); +numOrUndefined = d3Array.sum(numericArray); +numOrUndefined = d3Array.sum(numbersOrUndefinedArray); -num = d3Array.sum(numbersArray); - -num = d3Array.sum(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); +numOrUndefined = d3Array.sum(mixedObjectArray, accessorMixedObjectToNum); +numOrUndefined = d3Array.sum(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // deviation() ----------------------------------------------------------------- -num = d3Array.deviation(numbersArray); +numOrUndefined = d3Array.deviation(numbersArray); +numOrUndefined = d3Array.deviation(numericArray); +numOrUndefined = d3Array.deviation(numbersOrUndefinedArray); -num = d3Array.deviation(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); +numOrUndefined = d3Array.deviation(mixedObjectArray, accessorMixedObjectToNum); +numOrUndefined = d3Array.deviation(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // variance() ------------------------------------------------------------------ -num = d3Array.variance(numbersArray); +numOrUndefined = d3Array.variance(numbersArray); +numOrUndefined = d3Array.variance(numericArray); +numOrUndefined = d3Array.variance(numbersOrUndefinedArray); -num = d3Array.variance(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); +numOrUndefined = d3Array.variance(mixedObjectArray, accessorMixedObjectToNum); +numOrUndefined = d3Array.variance(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // ----------------------------------------------------------------------------- // Test Searching Arrays @@ -259,8 +210,18 @@ num = d3Array.variance(mixedObjectArray, function (datum, index, array) { // scan() ---------------------------------------------------------------------- -num = d3Array.scan(mixedObjectArray, function (a, b) { - return a.num - b.num; // a and b are of type MixedObject +numOrUndefined = d3Array.scan(numbersArray); + +numOrUndefined = d3Array.scan(mixedObjectArray, (a, b) => { + const aElem: MixedObject = a; + const bElem: MixedObject = b; + return a.num - b.num; +}); + +numOrUndefined = d3Array.scan(mixedObjectOrUndefinedArray, (a, b) => { + const aElem: MixedObject | undefined = a; + const bElem: MixedObject | undefined = b; + return a && b ? a.num - b.num : NaN; }); // bisectLeft() ---------------------------------------------------------------- @@ -307,19 +268,16 @@ num = d3Array.bisect([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, // bisector() ------------------------------------------------------------------ -mixedObjectArray.sort(function (a, b) { return a.date.valueOf() - b.date.valueOf(); }); +mixedObjectArray.sort((a, b) => a.date.valueOf() - b.date.valueOf()); let mixedObjectDateBisectorObject: d3Array.Bisector; // define using accessor -mixedObjectDateBisectorObject = d3Array.bisector(function (el) { - return el.date; -}); +mixedObjectDateBisectorObject = d3Array.bisector(el => el.date); // define using comparator -mixedObjectDateBisectorObject = d3Array.bisector(function (el, x) { - return el.date.valueOf() - x.valueOf(); -}); +mixedObjectDateBisectorObject = d3Array.bisector((el, x) => + el.date.valueOf() - x.valueOf()); // bisect left num = mixedObjectDateBisectorObject.left(mixedObjectArray, new Date(2015, 3, 14)); @@ -334,12 +292,14 @@ num = mixedObjectDateBisectorObject.right(mixedObjectArray, new Date(2015, 3, 14 // ascending() ----------------------------------------------------------------- +num = d3Array.ascending(undefined, 20); num = d3Array.ascending(10, 20); num = d3Array.ascending('10', '20'); num = d3Array.ascending(new Date(2016, 6, 13), new Date(2016, 6, 14)); // descending() ---------------------------------------------------------------- +num = d3Array.descending(undefined, 20); num = d3Array.descending(10, 20); num = d3Array.descending('10', '20'); num = d3Array.descending(new Date(2016, 6, 13), new Date(2016, 6, 14)); @@ -364,12 +324,11 @@ let testArrays: MixedObject[][] = [ ] ]; - let mergedArray: MixedObject[]; mergedArray = d3Array.merge(testArrays); // inferred type mergedArray = d3Array.merge(testArrays); // explicit type -// mergedArray = d3.merge([[10, 40, 30], [15, 30]]); // fails, type mismatch +// mergedArray = d3Array.merge([[10, 40, 30], [15, 30]]); // fails, type mismatch // pairs() --------------------------------------------------------------------- @@ -384,14 +343,14 @@ mergedArray = d3Array.permute(mergedArray, [1, 0, 2, 5, 3, 4, 6]); // Getting an ordered array with object properties -let testObject = { +const testObject = { val: 10, name: 'Test', when: new Date(), more: [10, 30, 40] }; -let x: Array = d3Array.permute(testObject, ['name', 'val', 'when', 'more']); +const x: Array = d3Array.permute(testObject, ['name', 'val', 'when', 'more']); // range() --------------------------------------------------------------------- @@ -450,7 +409,7 @@ testArrays = d3Array.zip( // Test Histogram // ----------------------------------------------------------------------------- -let tScale = scaleTime(); +const tScale = scaleTime(); // Create histogram generator ================================================== @@ -464,10 +423,10 @@ testHistogram = d3Array.histogram(); // value(...) ------------------------------------------------------------------ -testHistogram = testHistogram.value(function (d, i, data) { - let datum: MixedObject = d; // d is of type MixedObject - let index: number = i; // i is number - let array: MixedObject[] = data; // data is of type MixedObject[] +testHistogram = testHistogram.value((d, i, data) => { + const datum: MixedObject = d; // d is of type MixedObject + const index: number = i; // i is number + const array: MixedObject[] = data; // data is of type MixedObject[] return datum.date; }); @@ -480,16 +439,14 @@ valueAccessorFn = testHistogram.value(); testHistogram = testHistogram.domain([new Date(2014, 3, 15), new Date(2017, 4, 15)]); // usage with scale domain: -let domain = tScale.domain(); +const domain = tScale.domain(); testHistogram = testHistogram.domain([domain[0], domain[domain.length]]); // testHistogram = testHistogram.domain(tScale.domain()); // fails, as scale domain is an array with possibly more than the two elements expected by histogram // use with accessor function -testHistogram = testHistogram.domain(function (values) { - return [values[0], values[values.length]]; -}); +testHistogram = testHistogram.domain(values => [values[0], values[values.length]]); // get current domain accessor function let domainAccessorFn: (values: Date[]) => [Date, Date]; @@ -508,7 +465,7 @@ defaultHistogram = defaultHistogram.thresholds(d3Array.thresholdScott); testHistogram = testHistogram.thresholds([new Date(2015, 11, 15), new Date(2016, 6, 1), new Date(2016, 8, 30)]); // with thresholds value array accessors -testHistogram = testHistogram.thresholds(function (values: Date[], min: Date, max: Date) { +testHistogram = testHistogram.thresholds((values: Date[], min: Date, max: Date) => { let thresholds: Date[]; thresholds = [values[0], values[2], values[4]]; return thresholds; @@ -536,7 +493,7 @@ let testBin: d3Array.Bin; testBin = testBins[0]; num = testBin.length; // defaultBin is array -let mixedObject: MixedObject = testBin[0]; // with element type MixedObject +const mixedObject: MixedObject = testBin[0]; // with element type MixedObject date = testBin.x0; // bin lower bound is Date date = testBin.x1; // bin upper bound is Date diff --git a/d3-array/index.d.ts b/d3-array/index.d.ts index e3bd2d549d..336eb2bc83 100644 --- a/d3-array/index.d.ts +++ b/d3-array/index.d.ts @@ -1,8 +1,10 @@ -// Type definitions for D3JS d3-array module v1.0.1 +// Type definitions for D3JS d3-array module 1.0 // Project: https://github.com/d3/d3-array // Definitions by: Alex Ford , Boris Yankov , Tom Wanzek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Last module patch version validated against: 1.0.2 + // -------------------------------------------------------------------------- // Shared Types and Interfaces // -------------------------------------------------------------------------- @@ -20,17 +22,11 @@ interface Numeric { valueOf(): number; } - // -------------------------------------------------------------------------------------- // Descriptive Statistics // -------------------------------------------------------------------------------------- -/** - * Return the maximum value in the array of numbers using natural order. - */ -export function max(array: number[]): number | undefined; - /** * Return the maximum value in the array of strings using natural order. */ @@ -41,25 +37,15 @@ export function max(array: string[]): string | undefined; */ export function max(array: T[]): T | undefined; -/** - * Return the maximum value in the array using natural order and a projection function to map values to numbers. - */ -export function max(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number | undefined; - /** * Return the maximum value in the array using natural order and a projection function to map values to strings. */ -export function max(array: T[], accessor: (datum: T, index: number, array: T[]) => string): string | undefined; +export function max(array: T[], accessor: (datum: T, index: number, array: T[]) => string | undefined | null): string | undefined; /** * Return the maximum value in the array using natural order and a projection function to map values to easily-sorted values. */ -export function max(array: T[], accessor: (datum: T, index: number, array: T[]) => U): U | undefined; - -/** - * Return the minimum value in the array using natural order. - */ -export function min(array: number[]): number | undefined; +export function max(array: T[], accessor: (datum: T, index: number, array: T[]) => U | undefined | null): U | undefined; /** * Return the minimum value in the array using natural order. @@ -74,25 +60,15 @@ export function min(array: T[]): T | undefined; /** * Return the minimum value in the array using natural order. */ -export function min(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number | undefined; +export function min(array: T[], accessor: (datum: T, index: number, array: T[]) => string | undefined | null): string | undefined; /** * Return the minimum value in the array using natural order. */ -export function min(array: T[], accessor: (datum: T, index: number, array: T[]) => string): string | undefined; - -/** - * Return the minimum value in the array using natural order. - */ -export function min(array: T[], accessor: (datum: T, index: number, array: T[]) => U): U | undefined; +export function min(array: T[], accessor: (datum: T, index: number, array: T[]) => U | undefined | null): U | undefined; -/** - * Return the min and max simultaneously. - */ -export function extent(array: number[]): [number, number] | [undefined, undefined]; - /** * Return the min and max simultaneously. */ @@ -106,79 +82,70 @@ export function extent(array: T[]): [T, T] | [undefined, unde /** * Return the min and max simultaneously. */ -export function extent(array: Array): [T | Primitive, T | Primitive] | [undefined, undefined]; +export function extent(array: T[], accessor: (datum: T, index: number, array: T[]) => string | undefined | null): [string, string] | [undefined, undefined]; /** * Return the min and max simultaneously. */ -export function extent(array: T[], accessor: (datum: T, index: number, array: T[]) => number): [number, number] | [undefined, undefined]; - -/** - * Return the min and max simultaneously. - */ -export function extent(array: T[], accessor: (datum: T, index: number, array: T[]) => string): [string, string] | [undefined, undefined]; - -/** - * Return the min and max simultaneously. - */ -export function extent(array: T[], accessor: (datum: T, index: number, array: T[]) => U): [U, U ] | [undefined, undefined]; +export function extent(array: T[], accessor: (datum: T, index: number, array: T[]) => U | undefined | null): [U, U] | [undefined, undefined]; /** * Return the mean of an array of numbers */ -export function mean(array: number[]): number | undefined; -export function mean(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number | undefined; +export function mean(array: Array): number | undefined; +export function mean(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number | undefined; /** * Return the median of an array of numbers */ -export function median(array: number[]): number | undefined; -export function median(array: T[], accessor: (element: T, i: number, array: T[]) => number): number | undefined; +export function median(array: Array): number | undefined; +export function median(array: T[], accessor: (element: T, i: number, array: T[]) => number | undefined | null): number | undefined; /** * Returns the p-quantile of an array of numbers */ -export function quantile(array: number[], p: number): number | undefined; -export function quantile(array: T[], p: number, accessor: (element: T, i: number, array: T[]) => number): number | undefined; +export function quantile(array: Array, p: number): number | undefined; +export function quantile(array: T[], p: number, accessor: (element: T, i: number, array: T[]) => number | undefined | null): number | undefined; /** * Compute the sum of an array of numbers. */ -export function sum(array: number[]): number; +export function sum(array: Array): number; /** * Compute the sum of an array, using the given accessor to convert values to numbers. */ -export function sum(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number; +export function sum(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number; /** * Compute the standard deviation, defined as the square root of the bias-corrected variance, of the given array of numbers. */ -export function deviation(array: number[]): number | undefined; +export function deviation(array: Array): number | undefined; /** * Compute the standard deviation, defined as the square root of the bias-corrected variance, of the given array, * using the given accessor to convert values to numbers. */ -export function deviation(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number | undefined; +export function deviation(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number | undefined; /** * Compute an unbiased estimator of the population variance of the given array of numbers. */ -export function variance(array: number[]): number | undefined; +export function variance(array: Array): number | undefined; /** * Compute an unbiased estimator of the population variance of the given array, * using the given accessor to convert values to numbers. */ -export function variance(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number | undefined; +export function variance(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number | undefined; // -------------------------------------------------------------------------------------- // Searching Arrays // -------------------------------------------------------------------------------------- -export function scan(array: T[], comparator: (a: T, b: T) => number): number; +export function scan(array: number[], comparator?: (a: number, b: number) => number): number | undefined; +export function scan(array: T[], comparator: (a: T, b: T) => number): number | undefined; export function bisectLeft(array: number[], x: number, lo?: number, hi?: number): number; export function bisectLeft(array: string[], x: string, lo?: number, hi?: number): number; @@ -202,16 +169,16 @@ export function bisector(accessor: (x: T) => U): Bisector; /** * Compares two primitive values for sorting (in ascending order). */ -export function ascending(a: Primitive, b: Primitive): number; +export function ascending(a: Primitive | undefined, b: Primitive | undefined): number; // NB. this is limited to primitive values due to D3's use of the <, >, and >= operators. Results get weird for object instances. /** * Compares two primitive values for sorting (in ascending order). */ -export function descending(a: Primitive, b: Primitive): number; +export function descending(a: Primitive | undefined, b: Primitive | undefined): number; // -------------------------------------------------------------------------------------- -// Transforming Arrays +// Transforming Arrays // -------------------------------------------------------------------------------------- @@ -236,7 +203,6 @@ export function permute(array: { [key: number]: T }, keys: number[]): T[]; */ export function permute(object: { [key: string]: T }, keys: string[]): T[]; - /** * Generates a 0-based numeric sequence. The output range does not include 'stop'. */ diff --git a/d3-array/tsconfig.json b/d3-array/tsconfig.json index db900a4087..b70f6aed80 100644 --- a/d3-array/tsconfig.json +++ b/d3-array/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/d3-array/tslint.json b/d3-array/tslint.json new file mode 100644 index 0000000000..68d10d72a6 --- /dev/null +++ b/d3-array/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "unified-signatures": false + } +} diff --git a/d3-axis/d3-axis-tests.ts b/d3-axis/d3-axis-tests.ts index 1aa50ba641..1a4077d690 100644 --- a/d3-axis/d3-axis-tests.ts +++ b/d3-axis/d3-axis-tests.ts @@ -54,9 +54,9 @@ axisScaleString = scalePoint(); // -------------------------------------------------------------------------- let containerElement: d3Axis.AxisContainerElement; -const svg: SVGSVGElement = select('svg').node() !; //mock -const g: SVGGElement = select('g').node() !; //mock -const canvas: HTMLCanvasElement = select('canvas').node() !; //mock +const svg: SVGSVGElement = select('svg').node() !; // mock +const g: SVGGElement = select('g').node() !; // mock +const canvas: HTMLCanvasElement = select('canvas').node() !; // mock containerElement = svg; containerElement = g; @@ -78,7 +78,7 @@ let leftAxis: d3Axis.Axis = d3Axis.axisLeft(scal // scale(...) ---------------------------------------------------------------- leftAxis = leftAxis.scale(scalePow()); -let powerScale: ScalePower = leftAxis.scale>(); +const powerScale: ScalePower = leftAxis.scale>(); // powerScale = leftAxis.scale(); // fails, without casting as AxisScale is purposely generic @@ -86,8 +86,8 @@ let powerScale: ScalePower = leftAxis.scale()); // bottomAxis = bottomAxis.scale(scalePow()) // fails, domain of scale incompatible with domain of axis -let axisScale: d3Axis.AxisScale = bottomAxis.scale(); -let ordinalScale: ScaleOrdinal = bottomAxis.scale>(); +const axisScale: d3Axis.AxisScale = bottomAxis.scale(); +const ordinalScale: ScaleOrdinal = bottomAxis.scale>(); // ordinalScale = bottomAxis.scale(); // fails, without casting as AxisScale is purposely generic // ticks(...) ---------------------------------------------------------------- @@ -102,7 +102,7 @@ topAxis = topAxis.tickArguments([20, 's']); rightAxis = rightAxis.tickArguments([timeMinute.every(5)]); -let tickArguments: any[] = leftAxis.tickArguments(); +const tickArguments: any[] = leftAxis.tickArguments(); // tickValues(...) ---------------------------------------------------------------- @@ -112,17 +112,17 @@ bottomAxis = bottomAxis.tickValues(['strongly negative', 'strongly positive']); leftAxis = leftAxis.tickValues(null); -let tickValues: Date[] | null = rightAxis.tickValues(); +const tickValues: Date[] | null = rightAxis.tickValues(); // tickFormat(...) ---------------------------------------------------------------- topAxis = topAxis.tickFormat(format(',.0f')); topAxis = topAxis.tickFormat(null); -let formatFn: ((domainValue: string, index: number) => string) | null = bottomAxis.tickFormat(); +const formatFn: ((domainValue: string, index: number) => string) | null = bottomAxis.tickFormat(); -bottomAxis.tickFormat(function (d, i) { return '#' + i; }); -bottomAxis.tickFormat(function (d) { return d + '!'; }); +bottomAxis.tickFormat((d, i) => '#' + i); +bottomAxis.tickFormat(d => d + '!'); // tickSize(...) ---------------------------------------------------------------- rightAxis = rightAxis.tickSize(5); @@ -147,20 +147,20 @@ num = rightAxis.tickPadding(); // Test Apply Axis // -------------------------------------------------------------------------- -let gSelection: Selection = select('g'); -let gTransition = gSelection.transition(); +const gSelection: Selection = select('g'); +const gTransition = gSelection.transition(); gSelection.call(topAxis); gTransition.call(topAxis); -let svgSelection: Selection = select('g'); -let svgTransition = svgSelection.transition(); +const svgSelection: Selection = select('g'); +const svgTransition = svgSelection.transition(); svgSelection.call(leftAxis); svgTransition.call(leftAxis); -let canvasSelection: Selection = select('canvas'); -let canvasTransition = canvasSelection.transition(); +const canvasSelection: Selection = select('canvas'); +const canvasTransition = canvasSelection.transition(); // canvasSelection.call(rightAxis); // fails, incompatible context container element // canvasTransition.call(rightAxis); // fails, incompatible context container element diff --git a/d3-brush/d3-brush-tests.ts b/d3-brush/d3-brush-tests.ts index eca4a8ef91..367cc05d1b 100644 --- a/d3-brush/d3-brush-tests.ts +++ b/d3-brush/d3-brush-tests.ts @@ -26,9 +26,9 @@ interface BrushDatum { let brush: d3Brush.BrushBehavior = d3Brush.brush(); -let brushX: d3Brush.BrushBehavior = d3Brush.brushX(); +const brushX: d3Brush.BrushBehavior = d3Brush.brushX(); -let brushY: d3Brush.BrushBehavior = d3Brush.brushY(); +const brushY: d3Brush.BrushBehavior = d3Brush.brushY(); // extent() ---------------------------------------------------------------------- @@ -39,7 +39,7 @@ extent = brush.extent(); brush = brush.extent([[0, 0], [300, 200]]); // chainable with function -brush = brush.extent(function (d, i, group) { +brush = brush.extent(function(d, i, group) { console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement return d.extent; // datum of type BrushDatum }); @@ -47,10 +47,10 @@ brush = brush.extent(function (d, i, group) { // filter() ---------------------------------------------------------------- // chainable -brush = brush.filter(function (d, i, group) { +brush = brush.filter(function(d, i, group) { // Cast d3 event to D3ZoomEvent to be used in filter logic - let e = > event; + const e = > event; console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement return e.sourceEvent.type !== 'zoom' || !d.filterZoomEvent; // datum type is BrushDatum (as propagated to SVGGElement with brush event attached) @@ -63,17 +63,17 @@ filterFn = brush.filter(); // chainable brush = brush.handleSize(7); -let handleSize: number = brush.handleSize(); +const handleSize: number = brush.handleSize(); // on() ------------------------------------------------------------------------ let brushed: ((this: SVGGElement, datum: BrushDatum, index: number, group: SVGGElement[] | ArrayLike) => void) | undefined; -brushed = function (d, i, group) { +brushed = (d, i, group) => { // do anything }; -let wrongHandler1: (this: SVGSVGElement, datum: BrushDatum, index: number, group: SVGSVGElement[] | ArrayLike) => void; -let wrongHandler2: (this: SVGGElement, datum: { test: string }, index: number, group: SVGGElement[] | ArrayLike) => void; +// let wrongHandler1: (this: SVGSVGElement, datum: BrushDatum, index: number, group: SVGSVGElement[] | ArrayLike) => void; +// let wrongHandler2: (this: SVGGElement, datum: { test: string }, index: number, group: SVGGElement[] | ArrayLike) => void; // chainable brush = brush.on('end', brushed); @@ -87,11 +87,11 @@ brushed = brush.on('end'); brush = brush.on('end', null); // re-apply -brush.on('end', function (d, i, g) { - let that: SVGGElement = this; - let datum: BrushDatum = d; - let index: number = i; - let group: SVGGElement[] | ArrayLike = g; +brush.on('end', function(d, i, g) { + const that: SVGGElement = this; + const datum: BrushDatum = d; + const index: number = i; + const group: SVGGElement[] | ArrayLike = g; console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement console.log('Extent as per data: ', d.extent); // datum of type BrushDatum // do anything @@ -103,7 +103,7 @@ brush.on('end', function (d, i, g) { // Test Attach Brush Behavior // ----------------------------------------------------------------------------- -let g = select('svg') +const g = select('svg') .append('g') .classed('brush', true) .datum({ @@ -113,7 +113,7 @@ let g = select('svg') g.call(brush); -let gX = select('svg') +const gX = select('svg') .append('g') .classed('brush', true) .datum({ @@ -129,13 +129,13 @@ gX.call(brushX); // Test Use Brush Behavior // ----------------------------------------------------------------------------- -let gTransition = g.transition(); +const gTransition = g.transition(); // 2d brush move with Selection brush.move(g, [[10, 10], [50, 50]]); // two-dimensional brush -brush.move(g, function (d, i, group) { +brush.move(g, function(d, i, group) { console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement - let selection: [[number, number], [number, number]] = [[0, 0], [0, 0]]; + const selection: [[number, number], [number, number]] = [[0, 0], [0, 0]]; selection[0][0] = d.extent[0][0] + 10; // datum type is brushDatum selection[0][1] = d.extent[0][1] + 10; selection[1][0] = d.extent[0][0] + 40; @@ -145,9 +145,9 @@ brush.move(g, function (d, i, group) { // 2d brush move with Transition brush.move(gTransition, [[10, 10], [50, 50]]); // two-dimensional brush -brush.move(gTransition, function (d, i, group) { +brush.move(gTransition, function(d, i, group) { console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement - let selection: [[number, number], [number, number]] = [[0, 0], [0, 0]]; + const selection: [[number, number], [number, number]] = [[0, 0], [0, 0]]; selection[0][0] = d.extent[0][0] + 10; // datum type is brushDatum selection[0][1] = d.extent[0][1] + 10; selection[1][0] = d.extent[0][0] + 40; @@ -156,13 +156,13 @@ brush.move(gTransition, function (d, i, group) { }); -let gXTransition = gX.transition(); +const gXTransition = gX.transition(); // 1d brush move with Selection brush.move(gX, [10, 40]); // two-dimensional brush -brush.move(gX, function (d, i, group) { +brush.move(gX, function(d, i, group) { console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement - let selection: [number, number] = [0, 0]; + const selection: [number, number] = [0, 0]; selection[0] = d.extent[0][0] + 10; // datum type is brushDatum selection[1] = d.extent[0][0] + 40; return selection; @@ -170,9 +170,9 @@ brush.move(gX, function (d, i, group) { // 1d brush move with Transition brush.move(gXTransition, [10, 40]); // two-dimensional brush -brush.move(gXTransition, function (d, i, group) { +brush.move(gXTransition, function(d, i, group) { console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement - let selection: [number, number] = [0, 0]; + const selection: [number, number] = [0, 0]; selection[0] = d.extent[0][0] + 10; // datum type is brushDatum selection[1] = d.extent[0][0] + 40; return selection; @@ -184,10 +184,10 @@ brush.move(gXTransition, function (d, i, group) { // ----------------------------------------------------------------------------- -let e: d3Brush.D3BrushEvent = event; +const e: d3Brush.D3BrushEvent = event; -let target: d3Brush.BrushBehavior = e.target; -let type: 'start' | 'brush' | 'end' | string = e.type; -let brushSelection: d3Brush.BrushSelection = e.selection; -let sourceEvent: any = e.sourceEvent; +const target: d3Brush.BrushBehavior = e.target; +const type: 'start' | 'brush' | 'end' | string = e.type; +const brushSelection: d3Brush.BrushSelection = e.selection; +const sourceEvent: any = e.sourceEvent; diff --git a/d3-chord/d3-chord-tests.ts b/d3-chord/d3-chord-tests.ts index b2dd960b79..c826c81fac 100644 --- a/d3-chord/d3-chord-tests.ts +++ b/d3-chord/d3-chord-tests.ts @@ -15,7 +15,7 @@ import { ascending } from 'd3-array'; // Preparatory Steps // --------------------------------------------------------------------- -let context: CanvasRenderingContext2D | null= document.querySelector('canvas')!.getContext('2d'); +let context: CanvasRenderingContext2D | null = document.querySelector('canvas')!.getContext('2d'); let chords: d3Chord.Chords; let chordGroups: d3Chord.ChordGroup[]; @@ -23,7 +23,7 @@ let chord: d3Chord.Chord; let chordSubgroup: d3Chord.ChordSubgroup; let num: number; -let matrix: number[][] = [ +const matrix: number[][] = [ [11975, 5871, 8916, 2868], [1951, 10048, 2060, 6171], [8010, 16145, 8090, 8045], @@ -79,7 +79,7 @@ chords = chordLayout(matrix); // Test supporting interfaces ========================================== -let length: number = chords.length; +const length: number = chords.length; chordGroups = chords.groups; @@ -126,7 +126,7 @@ svgRibbon = svgRibbon.context(null); // source() ----------------------------------------------------------- -svgRibbon = svgRibbon.source(function (d) { +svgRibbon = svgRibbon.source(d => { return d.source; // datum is of type Chord }); @@ -134,7 +134,7 @@ subgroupAccessor = svgRibbon.source(); // target() ----------------------------------------------------------- -svgRibbon = svgRibbon.target(function (d) { +svgRibbon = svgRibbon.target(d => { return d.target; // datum is of type Chord }); @@ -145,7 +145,7 @@ subgroupAccessor = svgRibbon.target(); canvasRibbon = canvasRibbon.radius(30); -svgRibbon = svgRibbon.radius(function (d) { +svgRibbon = svgRibbon.radius(function(d) { console.log('SVGPathElement createSVGPathSegCurvetoCubicAbs method:', this.createSVGPathSegCurvetoCubicAbs); // this type SVGPathElement console.log('Subgroup startAngle', d.startAngle); // datum is of type Chord return 30; @@ -157,7 +157,7 @@ numAccessor = svgRibbon.radius(); canvasRibbon = canvasRibbon.startAngle(0); -svgRibbon = svgRibbon.startAngle(function (d) { +svgRibbon = svgRibbon.startAngle(function(d) { console.log('SVGPathElement createSVGPathSegCurvetoCubicAbs method:', this.createSVGPathSegCurvetoCubicAbs); // this type SVGPathElement return d.startAngle; // datum is of type ChordSubgroup }); @@ -168,7 +168,7 @@ numAccessor = svgRibbon.startAngle(); canvasRibbon = canvasRibbon.endAngle(Math.PI); -svgRibbon = svgRibbon.endAngle(function (d) { +svgRibbon = svgRibbon.endAngle(function(d) { console.log('SVGPathElement createSVGPathSegCurvetoCubicAbs method:', this.createSVGPathSegCurvetoCubicAbs); // this type SVGPathElement return d.endAngle; // datum is of type ChordSubgroup }); @@ -178,7 +178,7 @@ numAccessor = svgRibbon.endAngle(); // Use RibbonGenerator ================================================= // use canvas -let ribbon: d3Chord.Ribbon = { +const ribbon: d3Chord.Ribbon = { source: {startAngle: 0.7524114, endAngle: 1.1212972, radius: 240}, target: {startAngle: 1.8617078, endAngle: 1.9842927, radius: 240} }; @@ -199,6 +199,6 @@ let ribbonPaths: Selection('g') .datum(chords) .selectAll() - .data(function (chords) { return chords; }) + .data(chords => chords) .enter().append('path') .attr('d', svgRibbon); diff --git a/d3-chord/index.d.ts b/d3-chord/index.d.ts index 4696693d83..b4865c962c 100644 --- a/d3-chord/index.d.ts +++ b/d3-chord/index.d.ts @@ -306,8 +306,9 @@ export interface RibbonGenerator { * Sets the radius accessor to the specified function and returns this ribbon generator. * * @param radius An accessor function which is invoked for the source and target of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and - * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. It is also passed any additional arguments that were passed - * into the generator, with the exception of the first element representing the chord datum itself. The function returns the radius value. + * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. + * It is also passed any additional arguments that were passed into the generator, with the exception of the first element representing the chord datum itself. + * The function returns the radius value. */ radius(radius: (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number): this; @@ -326,8 +327,9 @@ export interface RibbonGenerator { * Sets the start angle accessor to the specified function and returns this ribbon generator. * * @param angle An accessor function which is invoked for the source and target of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and - * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. It is also passed any additional arguments that were passed - * into the generator, with the exception of the first element representing the chord datum itself. The function returns the start angle in radians. + * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. + * It is also passed any additional arguments that were passed into the generator, with the exception of the first element representing the chord datum itself. + * The function returns the start angle in radians. */ startAngle(angle: (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number): this; @@ -346,8 +348,9 @@ export interface RibbonGenerator { * Sets the end angle accessor to the specified function and returns this ribbon generator. * * @param angle An accessor function which is invoked for the source and target of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and - * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. It is also passed any additional arguments that were passed - * into the generator, with the exception of the first element representing the chord datum itself. The function returns the end angle in radians. + * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. + * It is also passed any additional arguments that were passed into the generator, with the exception of the first element representing the chord datum itself. + * The function returns the end angle in radians. */ endAngle(angle: (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number): this; diff --git a/d3-drag/d3-drag-tests.ts b/d3-drag/d3-drag-tests.ts index 379647117b..deb5a6dc55 100644 --- a/d3-drag/d3-drag-tests.ts +++ b/d3-drag/d3-drag-tests.ts @@ -38,9 +38,9 @@ interface CustomSubject { r: number; } -let svg: SVGSVGElement = select('svg').node()!; // mock +const svg: SVGSVGElement = select('svg').node()!; // mock -let circles: Selection = select('svg').selectAll('circle'); // mock +const circles: Selection = select('svg').selectAll('circle'); // mock // ----------------------------------------------------------------------------- // Test Define DragBehavior @@ -65,7 +65,7 @@ circleCustomDrag = d3Drag.drag) => d3Drag.DragContainerElement; -containerAccessor = function (d, i, group) { +containerAccessor = function(d, i, group) { console.log('Node Id of circle: ', d.nodeId); // console.log(this.a); // fails, a is not a property of SVGCircleElement return this.ownerSVGElement; // this-type is SVGCircleElement @@ -73,7 +73,7 @@ containerAccessor = function (d, i, group) { // Test chainability circleDrag = circleDrag - .container(function (d, i, group) { // container accessor function setter + .container(function(d, i, group) { // container accessor function setter console.log('Node Id of circle: ', d.nodeId); // CircleDatum type // console.log(this.a); // fails, a is not a property of SVGCircleElement return this.ownerSVGElement; // this-type is SVGCircleElement @@ -93,12 +93,12 @@ containerAccessor = circleDrag.container(); let filterFn: (this: SVGCircleElement, datum: CircleDatum, index: number, group: SVGCircleElement[] | NodeListOf) => boolean; -filterFn = function (d) { +filterFn = function(d) { return (d.color !== 'green' && this.r.baseVal.value < 10) ? !event.button : true; // 'this' is SVGCircleElement and d is CircleDatum }; // chainable -circleDrag = circleDrag.filter(function (d, i, group) { +circleDrag = circleDrag.filter(function(d, i, group) { return (d.color !== 'green' && this.r.baseVal.value < 10) ? !event.button : true; // 'this' is SVGCircleElement and d is CircleDatum }); @@ -108,13 +108,13 @@ filterFn = circleDrag.filter(); // set and get subject --------------------------------------------------------- -circleCustomDrag.subject(function (d, i, g) { +circleCustomDrag.subject(function(d, i, g) { // Cast event type for completeness, otherwise event is of type any. - let e = > event; - let that: SVGCircleElement = this; - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; + const e = > event; + const that: SVGCircleElement = this; + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; if (d == null) { return { x: e.x, y: e.y }; @@ -139,14 +139,14 @@ subjectAccessor = circleCustomDrag.subject(); function dragstarted(this: SVGCircleElement, d: CircleDatum) { // cast d3 event to drag event. Otherwise, d3 event is currently defined as type 'any' - let e = > event; + const e = > event; e.sourceEvent.stopPropagation(); select(this).classed('dragging', true); } function dragged(this: SVGCircleElement, d: CircleDatum) { // cast d3 event to drag event. Otherwise, d3 event is currently defined as type 'any' - let e = > event; + const e = > event; select(this).attr('cx', d.x = e.x).attr('cy', d.y = e.y); } @@ -174,16 +174,17 @@ circleDrag = circleDrag circleDrag.on('start.tmp', null); let handler: ((this: SVGCircleElement, d: CircleDatum, i: number, group: SVGCircleElement[] | NodeListOf) => void) | undefined = circleDrag.on('start'); -// let wrongHandler1: ((this:SVGRectElement, d:CircleDatum, i: number, group: SVGRectElement[] | NodeListOf)=> void) | undefined = circleDrag.on('start'); // fails, wrong dragged DOM event -// let wrongHandler2: ((this:SVGCircleElement, d:{test: number}, i: number, group: SVGCircleElement[] | NodeListOf)=> void) | undefined = circleDrag.on('start'); // fails, handler with wrong datum type - +// fails, wrong dragged DOM event +// let wrongHandler1: ((this:SVGRectElement, d:CircleDatum, i: number, group: SVGRectElement[] | NodeListOf)=> void) | undefined = circleDrag.on('start'); +// fails, handler with wrong datum type +// let wrongHandler2: ((this:SVGCircleElement, d:{test: number}, i: number, group: SVGCircleElement[] | NodeListOf)=> void) | undefined = circleDrag.on('start'); // ----------------------------------------------------------------------------- // Test Attach Drag Behavior // ----------------------------------------------------------------------------- circles.call(circleDrag); -let wrongSelection: Selection = select('div'); +const wrongSelection: Selection = select('div'); // wrongSelection.call(circleDrag); // fails, as dragged elements are not of type specified for drag behavior @@ -197,15 +198,15 @@ let e: d3Drag.D3DragEvent)=> void) | undefined = e.on('dragged'); // fails, wrong dragged DOM event -// let wrongHandler4: ((this:SVGCircleElement, d:{test: number}, i: number, group: SVGCircleElement[] | NodeListOf)=> void) | undefined = e.on('dragged'); // fails, handler with wrong datum type +// fails, wrong dragged DOM event +// let wrongHandler3: ((this:SVGRectElement, d:CircleDatum, i: number, group: SVGRectElement[] | NodeListOf)=> void) | undefined = e.on('dragged'); +// fails, handler with wrong datum type +// let wrongHandler4: ((this:SVGCircleElement, d:{test: number}, i: number, group: SVGCircleElement[] | NodeListOf)=> void) | undefined = e.on('dragged'); // ----------------------------------------------------------------------------- // Test dragDisable() and dragEnable() // ----------------------------------------------------------------------------- -let w: Window = window; +const w: Window = window; d3Drag.dragDisable(w); diff --git a/d3-dsv/d3-dsv-tests.ts b/d3-dsv/d3-dsv-tests.ts index 40516166b1..a4d958f01b 100644 --- a/d3-dsv/d3-dsv-tests.ts +++ b/d3-dsv/d3-dsv-tests.ts @@ -13,13 +13,13 @@ import * as d3Dsv from 'd3-dsv'; // ------------------------------------------------------------------------------------------ -let csvTestString: string = '1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38'; -let tsvTestString: string = '1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38'; -let pipedTestString: string = '1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38'; +const csvTestString: string = '1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38'; +const tsvTestString: string = '1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38'; +const pipedTestString: string = '1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38'; -let csvTestStringWithHeader: string = 'Year,Make,Model,Length\n1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38'; -let tsvTestStringWithHeader: string = 'Year\tMake\tModel\tLength\n1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38'; -let pipedTestStringWithHeader: string = 'Year|Make|Model|Length\n1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38'; +const csvTestStringWithHeader: string = 'Year,Make,Model,Length\n1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38'; +const tsvTestStringWithHeader: string = 'Year\tMake\tModel\tLength\n1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38'; +const pipedTestStringWithHeader: string = 'Year|Make|Model|Length\n1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38'; interface ParsedTestObject { year: Date; @@ -31,11 +31,11 @@ interface ParsedTestObject { let parseArray: d3Dsv.DSVParsedArray; let parseMappedArray: d3Dsv.DSVParsedArray; -let parseRowsArray: Array>; -let parseRowsMappedArray: Array; +let parseRowsArray: string[][]; +let parseRowsMappedArray: ParsedTestObject[]; -let columns: Array; +let columns: string[]; let num: number; let date: Date; let str: string; @@ -57,21 +57,17 @@ str = parseArray[0]['Year']; // with row mapper --------------------------------------------------------------------------- -parseMappedArray = d3Dsv.csvParse(csvTestStringWithHeader, function (rawRow, index, columns) { - let rr: d3Dsv.DSVRowString = rawRow; - let i: number = index; - let c: Array = columns; - let pr: ParsedTestObject; - - pr = { +parseMappedArray = d3Dsv.csvParse(csvTestStringWithHeader, (rawRow, index, columns) => { + const rr: d3Dsv.DSVRowString = rawRow; + const i: number = index; + const c: string[] = columns; + const pr: ParsedTestObject = { year: new Date(+rr['Year'], 0, 1), make: rr['Make'], model: rr['Model'], length: +rr['Length'] }; - return pr; - }); columns = parseMappedArray.columns; @@ -94,20 +90,16 @@ str = parseRowsArray[0][0]; // 'Year' of first row // with row mapper --------------------------------------------------------------------------- -parseRowsMappedArray = d3Dsv.csvParseRows(csvTestString, function (rawRow, index) { - let rr: Array = rawRow; - let i: number = index; - let pr: ParsedTestObject; - - pr = { +parseRowsMappedArray = d3Dsv.csvParseRows(csvTestString, (rawRow, index) => { + const rr: string[] = rawRow; + const i: number = index; + const pr: ParsedTestObject = { year: new Date(+rr[0], 0, 1), make: rr[1], model: rr[2], length: +rr[3] }; - return pr; - }); date = parseRowsMappedArray[0].year; @@ -122,14 +114,12 @@ str = d3Dsv.csvFormat(parseRowsMappedArray, columns); // csvFormatRows(...) ======================================================================== -str = d3Dsv.csvFormatRows(parseRowsMappedArray.map(function(d, i) { - return [ +str = d3Dsv.csvFormatRows(parseRowsMappedArray.map((d, i) => [ d.year.getFullYear().toString(), d.make, d.model, d.length.toString() - ]; -})); +])); // ------------------------------------------------------------------------------------------ // Test TSV @@ -148,21 +138,17 @@ str = parseArray[0]['Year']; // with row mapper --------------------------------------------------------------------------- -parseMappedArray = d3Dsv.tsvParse(tsvTestStringWithHeader, function (rawRow, index, columns) { - let rr: d3Dsv.DSVRowString = rawRow; - let i: number = index; - let c: Array = columns; - let pr: ParsedTestObject; - - pr = { +parseMappedArray = d3Dsv.tsvParse(tsvTestStringWithHeader, (rawRow, index, columns) => { + const rr: d3Dsv.DSVRowString = rawRow; + const i: number = index; + const c: string[] = columns; + const pr: ParsedTestObject = { year: new Date(+rr['Year'], 0, 1), make: rr['Make'], model: rr['Model'], length: +rr['Length'] }; - return pr; - }); columns = parseMappedArray.columns; @@ -185,20 +171,16 @@ str = parseRowsArray[0][0]; // 'Year' of first row // with row mapper --------------------------------------------------------------------------- -parseRowsMappedArray = d3Dsv.tsvParseRows(tsvTestString, function (rawRow, index) { - let rr: Array = rawRow; - let i: number = index; - let pr: ParsedTestObject; - - pr = { +parseRowsMappedArray = d3Dsv.tsvParseRows(tsvTestString, (rawRow, index) => { + const rr: string[] = rawRow; + const i: number = index; + const pr: ParsedTestObject = { year: new Date(+rr[0], 0, 1), make: rr[1], model: rr[2], length: +rr[3] }; - return pr; - }); date = parseRowsMappedArray[0].year; @@ -213,14 +195,12 @@ str = d3Dsv.tsvFormat(parseRowsMappedArray, columns); // tsvFormatRows(...) ======================================================================== -str = d3Dsv.tsvFormatRows(parseRowsMappedArray.map(function(d, i) { - return [ +str = d3Dsv.tsvFormatRows(parseRowsMappedArray.map((d, i) => [ d.year.getFullYear().toString(), d.make, d.model, d.length.toString() - ]; -})); +])); // ------------------------------------------------------------------------------------------ // Test DSV Generalized Parsers and Formatters @@ -244,21 +224,17 @@ str = parseArray[0]['Year']; // with row mapper --------------------------------------------------------------------------- -parseMappedArray = dsv.parse(pipedTestStringWithHeader, function (rawRow, index, columns) { - let rr: d3Dsv.DSVRowString = rawRow; - let i: number = index; - let c: Array = columns; - let pr: ParsedTestObject; - - pr = { +parseMappedArray = dsv.parse(pipedTestStringWithHeader, (rawRow, index, columns) => { + const rr: d3Dsv.DSVRowString = rawRow; + const i: number = index; + const c: string[] = columns; + const pr: ParsedTestObject = { year: new Date(+rr['Year'], 0, 1), make: rr['Make'], model: rr['Model'], length: +rr['Length'] }; - return pr; - }); columns = parseMappedArray.columns; @@ -281,20 +257,16 @@ str = parseRowsArray[0][0]; // 'Year' of first row // with row mapper --------------------------------------------------------------------------- -parseRowsMappedArray = dsv.parseRows(pipedTestString, function (rawRow, index) { - let rr: Array = rawRow; - let i: number = index; - let pr: ParsedTestObject; - - pr = { +parseRowsMappedArray = dsv.parseRows(pipedTestString, (rawRow, index) => { + const rr: string[] = rawRow; + const i: number = index; + const pr: ParsedTestObject = { year: new Date(+rr[0], 0, 1), make: rr[1], model: rr[2], length: +rr[3] }; - return pr; - }); date = parseRowsMappedArray[0].year; @@ -309,11 +281,9 @@ str = dsv.format(parseRowsMappedArray, columns); // formatRows(...) ======================================================================== -str = dsv.formatRows(parseRowsMappedArray.map(function(d, i) { - return [ +str = dsv.formatRows(parseRowsMappedArray.map((d, i) => [ d.year.getFullYear().toString(), d.make, d.model, d.length.toString() - ]; -})); +])); diff --git a/d3-dsv/index.d.ts b/d3-dsv/index.d.ts index 7682644987..eaf9797b02 100644 --- a/d3-dsv/index.d.ts +++ b/d3-dsv/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3-dsv module v1.0.1 +// Type definitions for D3JS d3-dsv module 1.0 // Project: https://github.com/d3/d3-dsv/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -16,7 +16,7 @@ export interface DSVRowAny { } export interface DSVParsedArray extends Array { - columns: Array; + columns: string[]; } // ------------------------------------------------------------------------------------------ @@ -26,21 +26,20 @@ export interface DSVParsedArray extends Array { // csvParse(...) ============================================================================ export function csvParse(csvString: string): DSVParsedArray; -export function csvParse(csvString: string, row: (rawRow: DSVRowString, index: number, columns: Array) => ParsedRow): DSVParsedArray; +export function csvParse(csvString: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow): DSVParsedArray; // csvParseRows(...) ======================================================================== -export function csvParseRows(csvString: string): Array>; -export function csvParseRows(csvString: string, row: (rawRow: Array, index: number) => ParsedRow): Array; +export function csvParseRows(csvString: string): string[][]; +export function csvParseRows(csvString: string, row: (rawRow: string[], index: number) => ParsedRow): ParsedRow[]; // csvFormat(...) ============================================================================ -export function csvFormat(rows: Array): string; -export function csvFormat(rows: Array, columns: Array): string; +export function csvFormat(rows: DSVRowAny[], columns?: string[]): string; // csvFormatRows(...) ======================================================================== -export function csvFormatRows(rows: Array>): string; +export function csvFormatRows(rows: string[][]): string; // ------------------------------------------------------------------------------------------ // TSV Parsers and Formatters @@ -49,21 +48,20 @@ export function csvFormatRows(rows: Array>): string; // tsvParse(...) ============================================================================ export function tsvParse(tsvString: string): DSVParsedArray; -export function tsvParse(tsvString: string, row: (rawRow: DSVRowString, index: number, columns: Array) => MappedRow): DSVParsedArray; +export function tsvParse(tsvString: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => MappedRow): DSVParsedArray; // tsvParseRows(...) ======================================================================== -export function tsvParseRows(tsvString: string): Array>; -export function tsvParseRows(tsvString: string, row: (rawRow: Array, index: number) => MappedRow): Array; +export function tsvParseRows(tsvString: string): string[][]; +export function tsvParseRows(tsvString: string, row: (rawRow: string[], index: number) => MappedRow): MappedRow[]; // tsvFormat(...) ============================================================================ -export function tsvFormat(rows: Array): string; -export function tsvFormat(rows: Array, columns: Array): string; +export function tsvFormat(rows: DSVRowAny[], columns?: string[]): string; // tsvFormatRows(...) ======================================================================== -export function tsvFormatRows(rows: Array>): string; +export function tsvFormatRows(rows: string[][]): string; // ------------------------------------------------------------------------------------------ // DSV Generalized Parsers and Formatters @@ -71,12 +69,11 @@ export function tsvFormatRows(rows: Array>): string; export interface DSV { parse(dsvString: string): DSVParsedArray; - parse(dsvString: string, row: (rawRow: DSVRowString, index: number, columns: Array) => ParsedRow): DSVParsedArray; - parseRows(dsvString: string): Array>; - parseRows(dsvString: string, row: (rawRow: Array, index: number) => ParsedRow): Array; - format(rows: Array): string; - format(rows: Array, columns: Array): string; - formatRows(rows: Array>): string; + parse(dsvString: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow): DSVParsedArray; + parseRows(dsvString: string): string[][]; + parseRows(dsvString: string, row: (rawRow: string[], index: number) => ParsedRow): ParsedRow[]; + format(rows: DSVRowAny[], columns?: string[]): string; + formatRows(rows: string[][]): string; } export function dsvFormat(delimiter: string): DSV; diff --git a/d3-dsv/v0/index.d.ts b/d3-dsv/v0/index.d.ts index 5547fccf6c..82ccd0f87f 100644 --- a/d3-dsv/v0/index.d.ts +++ b/d3-dsv/v0/index.d.ts @@ -38,7 +38,12 @@ interface D3Dsv { ): TRow[]; /** - Parses the specified string, which is the contents of a CSV file, returning an array of arrays representing the parsed rows. The string is assumed to be RFC4180-compliant. Unlike the parse method, this method treats the header line as a standard row, and should be used whenever the CSV file does not contain a header. Each row is represented as an array rather than an object. Rows may have variable length. For example, consider the following CSV file: + Parses the specified string, which is the contents of a CSV file, returning an array of arrays representing the parsed rows. + The string is assumed to be RFC4180-compliant. + Unlike the parse method, this method treats the header line as a standard row, and should be used whenever the CSV file does not contain a header. + Each row is represented as an array rather than an object. + Rows may have variable length. + For example, consider the following CSV file: 1997,Ford,E350,2.34 2000,Mercury,Cougar,2.38 @@ -55,14 +60,20 @@ interface D3Dsv { ): TRow[]; /** - Converts the specified array of rows into comma-separated values format, returning a string. This operation is the reverse of parse. Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. + Converts the specified array of rows into comma-separated values format, returning a string. + This operation is the reverse of parse. + Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). + Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. - Each row should be an object, and all object properties will be converted into fields. For greater control over which properties are converted, convert the rows into arrays containing only the properties that should be converted and use formatRows. + Each row should be an object, and all object properties will be converted into fields. + For greater control over which properties are converted, convert the rows into arrays containing only the properties that should be converted and use formatRows. */ format(rows: any[]): string; /** - Converts the specified array of rows into comma-separated values format, returning a string. This operation is the reverse of parseRows. Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. + Converts the specified array of rows into comma-separated values format, returning a string. + This operation is the reverse of parseRows. Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). + Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. */ formatRows(rows: any[]): string; } diff --git a/d3-dsv/v0/tslint.json b/d3-dsv/v0/tslint.json index 06eb30c7b9..af53769b6b 100644 --- a/d3-dsv/v0/tslint.json +++ b/d3-dsv/v0/tslint.json @@ -1 +1 @@ -{ "extends": "../../tslint.json" } \ No newline at end of file +{ "extends": "../../tslint.json" } diff --git a/d3-ease/d3-ease-tests.ts b/d3-ease/d3-ease-tests.ts index 84e34aa064..b50ceba9a4 100644 --- a/d3-ease/d3-ease-tests.ts +++ b/d3-ease/d3-ease-tests.ts @@ -8,7 +8,7 @@ import * as d3Ease from 'd3-ease'; -let t_in: number = 0.5; +const t_in: number = 0.5; let t_out: number; t_out = d3Ease.easeLinear(t_in); diff --git a/d3-ease/tslint.json b/d3-ease/tslint.json index f9e30021f4..377cc837d4 100644 --- a/d3-ease/tslint.json +++ b/d3-ease/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/d3-force/d3-force-tests.ts b/d3-force/d3-force-tests.ts index b760864079..0ecd7555d3 100644 --- a/d3-force/d3-force-tests.ts +++ b/d3-force/d3-force-tests.ts @@ -31,7 +31,7 @@ interface Graph { } -let graph: Graph = { +const graph: Graph = { nodes: [ { id: 'Myriel', group: 1, r: 5 }, { id: 'Napoleon', group: 1, r: 10 }, @@ -55,10 +55,10 @@ let simLinks: SimLink[]; let num: number; -let canvas = document.querySelector('canvas')!; -let context = canvas.getContext('2d'); -let width = canvas.width; -let height = canvas.height; +const canvas = document.querySelector('canvas')!; +const context = canvas.getContext('2d'); +const width = canvas.width; +const height = canvas.height; // ------------------------------------------------------------------------------------- // Test Pre-Defined Forces @@ -105,10 +105,10 @@ forceCollide = d3Force.forceCollide(); forceCollide = d3Force.forceCollide(15); // with radius accessor function -forceCollide = d3Force.forceCollide(function (node, index, nodes) { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; +forceCollide = d3Force.forceCollide((node, index, nodes) => { + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return n.r; }); @@ -120,10 +120,10 @@ let radiusAccessor: (node: SimNode, i: number, nodes: SimNode[]) => number; // radius forceCollide = forceCollide.radius(20); -forceCollide = forceCollide.radius(function (node, index, nodes) { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; +forceCollide = forceCollide.radius((node, index, nodes) => { + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return 2 * n.r; }); @@ -161,7 +161,7 @@ forceLink = d3Force.forceLink(graph.links); // Configure Link force ----------------------------------------------------------- let linkNumberAccessor: (link: SimLink, i: number, links: SimLink[]) => number; -let nodeIdAccessor: (node: SimNode, i: number, nodes: SimNode[]) => number | string; +// let nodeIdAccessor: (node: SimNode, i: number, nodes: SimNode[]) => number | string; // links @@ -174,7 +174,7 @@ simLink = simLinks[0]; simNode = (typeof simLink.source !== 'number' && typeof simLink.source !== 'string') ? simLink.source : undefined; simNode = (typeof simLink.target !== 'number' && typeof simLink.target !== 'string') ? simLink.target : undefined; -let maybeNum: number | undefined = simLink.index; // Ex-ante type before initialization of links +const maybeNum: number | undefined = simLink.index; // Ex-ante type before initialization of links num = simLink.index!; // Ex-post after link initialization, use ! non-null assertion operator to narrow to number num = simLink.value; @@ -184,20 +184,20 @@ num = simLink.s; // id (node id accessor) -forceLink = forceLink.id(function (node, index, nodes) { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; +forceLink = forceLink.id((node, index, nodes) => { + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return n.id; }); // distance forceLink = forceLink.distance(50); -forceLink = forceLink.distance(function (link, index, links) { - let l: SimLink = link; - let i: number = index; - let ls: SimLink[] = links; +forceLink = forceLink.distance((link, index, links) => { + const l: SimLink = link; + const i: number = index; + const ls: SimLink[] = links; return l.d; }); @@ -206,10 +206,10 @@ linkNumberAccessor = forceLink.distance(); // strength forceLink = forceLink.strength(0.95); -forceLink = forceLink.strength(function (link, index, links) { - let l: SimLink = link; - let i: number = index; - let ls: SimLink[] = links; +forceLink = forceLink.strength((link, index, links) => { + const l: SimLink = link; + const i: number = index; + const ls: SimLink[] = links; return l.s; }); @@ -242,10 +242,10 @@ let simNodeNumberAccessor: (node: SimNode, i: number, nodes: SimNode[]) => numbe // strength forceCharge = forceCharge.strength(-3000); -forceCharge = forceCharge.strength(function (node, index, nodes) { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; +forceCharge = forceCharge.strength((node, index, nodes) => { + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return -1000 * n.group; }); simNodeNumberAccessor = forceCharge.strength(); @@ -286,10 +286,10 @@ forcePosX = d3Force.forceX(); // strength forcePosX = forcePosX.strength(0.2); -forcePosX = forcePosX.strength(function (node, index, nodes) { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; +forcePosX = forcePosX.strength((node, index, nodes) => { + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return 0.1 * n.group; }); simNodeNumberAccessor = forcePosX.strength(); @@ -297,10 +297,10 @@ simNodeNumberAccessor = forcePosX.strength(); // x forcePosX = forcePosX.x(100); -forcePosX = forcePosX.x(function (node, index, nodes) { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; +forcePosX = forcePosX.x((node, index, nodes) => { + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; let target: number; switch (n.group) { case 1: @@ -341,10 +341,10 @@ forcePosY = d3Force.forceY(); // strength forcePosY = forcePosY.strength(0.2); -forcePosY = forcePosY.strength(function (node, index, nodes) { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; +forcePosY = forcePosY.strength((node, index, nodes) => { + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return 0.1 * n.group; }); simNodeNumberAccessor = forcePosY.strength(); @@ -352,10 +352,10 @@ simNodeNumberAccessor = forcePosY.strength(); // y forcePosY = forcePosY.y(100); -forcePosY = forcePosY.y(function (node, index, nodes) { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; +forcePosY = forcePosY.y((node, index, nodes) => { + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; let target: number; switch (n.group) { case 1: @@ -503,7 +503,7 @@ function drawNode(d: SimNode) { nodeLinkSimulation = nodeLinkSimulation.on('tick', function ticked() { - let that: d3Force.Simulation = this; + const that: d3Force.Simulation = this; if (context) { context.clearRect(0, 0, width, height); @@ -525,7 +525,7 @@ nodeLinkSimulation = nodeLinkSimulation.on('tick', function ticked() { nodeSimulation = nodeSimulation.on('tick', null); // get listener -let listener: ((this: d3Force.Simulation) => void) | undefined = nodeSimulation.on('tick'); +const listener: ((this: d3Force.Simulation) => void) | undefined = nodeSimulation.on('tick'); // Configure and Use Force Simulation =================================================== diff --git a/d3-scale/d3-scale-tests.ts b/d3-scale/d3-scale-tests.ts index 269218967e..c1feb4766a 100644 --- a/d3-scale/d3-scale-tests.ts +++ b/d3-scale/d3-scale-tests.ts @@ -37,7 +37,6 @@ class StringCoercible { } let num: number; -let str: string; let date: Date; let clampFlag: boolean; @@ -46,7 +45,7 @@ let outputNumber: number; let outputString: string; let domainNumbers: number[] = [1, 100]; -let domainNumeric: NumCoercible[] = [new NumCoercible(0), new NumCoercible(100)]; +const domainNumeric: NumCoercible[] = [new NumCoercible(0), new NumCoercible(100)]; let domainStrings: string[]; let domainDates: Date[] = [new Date(2016, 0, 15), new Date(2016, 5, 15)]; @@ -126,19 +125,15 @@ clampFlag = linearScaleNumber.clamp(); linearScaleString = linearScaleString.interpolate(interpolateCubehelix.gamma(3)); -linearScaleNumString = linearScaleNumString.interpolate(function (a, b) { +linearScaleNumString = linearScaleNumString.interpolate((a, b) => { // take two numbers - return function (t: number) { - return (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type - }; + return (t: number) => (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type }); // Changes scale output type (inferred generic) -linearScaleNumString = linearScaleNumber.interpolate(function (a, b) { +linearScaleNumString = linearScaleNumber.interpolate((a, b) => { // take two numbers - return function (t: number) { - return (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type - }; + return (t: number) => (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type }); // nice(...) ----------------------------------------------------------------------- @@ -169,7 +164,7 @@ outputString = linearScaleNumString(10); // copy(...) ----------------------------------------------------------------- -let copiedLinearScale: d3Scale.ScaleLinear = linearScaleNumString.copy(); +const copiedLinearScale: d3Scale.ScaleLinear = linearScaleNumString.copy(); // ------------------------------------------------------------------------------- // Power Scale Factories @@ -198,7 +193,7 @@ squarerootScaleNumString = d3Scale.scaleSqrt(); // exponent -------------------------------------------------------------------- -let exponent: number = squarerootScaleNumber.exponent(); +const exponent: number = squarerootScaleNumber.exponent(); powerScaleNumber = powerScaleNumber.exponent(5); @@ -249,11 +244,9 @@ clampFlag = powerScaleNumber.clamp(); powerScaleString = powerScaleString.interpolate(interpolateCubehelix.gamma(3)); -powerScaleNumString = powerScaleNumString.interpolate(function (a, b) { +powerScaleNumString = powerScaleNumString.interpolate((a, b) => { // take two numbers - return function (t: number) { - return (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type - }; + return (t: number) => (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type }); // nice(...) ----------------------------------------------------------------------- @@ -283,7 +276,7 @@ outputString = powerScaleNumString(10); // copy(...) ----------------------------------------------------------------- -let copiedPowerScale: d3Scale.ScalePower = powerScaleNumString.copy(); +const copiedPowerScale: d3Scale.ScalePower = powerScaleNumString.copy(); // ------------------------------------------------------------------------------- // Logarithmic Scale Factory @@ -305,7 +298,7 @@ logScaleNumString = d3Scale.scaleLog(); // base -------------------------------------------------------------------- -let base: number = logScaleNumber.base(); +const base: number = logScaleNumber.base(); logScaleNumber = logScaleNumber.base(42); @@ -356,11 +349,9 @@ clampFlag = logScaleNumber.clamp(); logScaleString = logScaleString.interpolate(interpolateCubehelix.gamma(3)); -logScaleNumString = logScaleNumString.interpolate(function (a, b) { +logScaleNumString = logScaleNumString.interpolate((a, b) => { // take two numbers - return function (t: number) { - return (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type - }; + return (t: number) => (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type }); // nice(...) ----------------------------------------------------------------------- @@ -390,7 +381,7 @@ outputString = logScaleNumString(10); // copy(...) ----------------------------------------------------------------- -let copiedLogScale: d3Scale.ScaleLogarithmic = logScaleNumString.copy(); +const copiedLogScale: d3Scale.ScaleLogarithmic = logScaleNumString.copy(); // ------------------------------------------------------------------------------- // Identity Scale Factory @@ -446,7 +437,7 @@ outputNumber = identityScale(10); // copy(...) ----------------------------------------------------------------- -let copiedIdentityScale: d3Scale.ScaleIdentity = identityScale.copy(); +const copiedIdentityScale: d3Scale.ScaleIdentity = identityScale.copy(); // ------------------------------------------------------------------------------- @@ -517,11 +508,9 @@ clampFlag = localTimeScaleNumber.clamp(); localTimeScaleString = localTimeScaleString.interpolate(interpolateCubehelix.gamma(3)); -localTimeScaleNumString = localTimeScaleNumString.interpolate(function (a, b) { +localTimeScaleNumString = localTimeScaleNumString.interpolate((a, b) => { // take two numbers - return function (t: number) { - return (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type - }; + return (t: number) => (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type }); // nice(...) ----------------------------------------------------------------------- @@ -565,7 +554,7 @@ outputString = localTimeScaleNumString(new Date(2016, 6, 4)); // copy(...) ----------------------------------------------------------------- -let copiedTimeScale: d3Scale.ScaleTime = localTimeScaleNumString.copy(); +const copiedTimeScale: d3Scale.ScaleTime = localTimeScaleNumString.copy(); // ------------------------------------------------------------------------------- // Sequential Scale Factory @@ -584,7 +573,7 @@ sequentialScaleColorString = d3Scale.scaleSequential(d3Scale.interpolateCool); / sequentialScaleColorString = sequentialScaleColorString.domain([0, 1]); sequentialScaleColorString = sequentialScaleColorString.domain([new NumCoercible(0), new NumCoercible(100)]); -let domainSequential: [number, number] = sequentialScaleColorString.domain(); +const domainSequential: [number, number] = sequentialScaleColorString.domain(); // clamp(...) ----------------------------------------------------------------- @@ -604,7 +593,7 @@ outputString = sequentialScaleColorString(10); // copy(...) ----------------------------------------------------------------- -let copiedSequentialScale: d3Scale.ScaleSequential = sequentialScaleColorString.copy(); +const copiedSequentialScale: d3Scale.ScaleSequential = sequentialScaleColorString.copy(); @@ -650,7 +639,7 @@ quantizeScaleString = d3Scale.scaleQuantize(); quantizeScaleNumber = quantizeScaleNumber.domain([0, 1]); quantizeScaleNumber = quantizeScaleNumber.domain([new NumCoercible(0), new NumCoercible(100)]); -let domainQuantize: [number, number] = quantizeScaleNumber.domain(); +const domainQuantize: [number, number] = quantizeScaleNumber.domain(); // range(...) ----------------------------------------------------------------- @@ -690,7 +679,7 @@ outputNumber = quantizeScaleNumber(0.51); // copy(...) ----------------------------------------------------------------- -let copiedQuantizeScale: d3Scale.ScaleQuantize = quantizeScaleNumber.copy(); +const copiedQuantizeScale: d3Scale.ScaleQuantize = quantizeScaleNumber.copy(); // ------------------------------------------------------------------------------- @@ -734,7 +723,7 @@ numExtent = quantileScaleString.invertExtent('q50'); // quantile() ----------------------------------------------------------------------- -let quantiles: number[] = quantileScaleNumber.quantiles(); +const quantiles: number[] = quantileScaleNumber.quantiles(); // (...) value mapping from domain to output ----------------------------------- @@ -742,7 +731,7 @@ outputNumber = quantileScaleNumber(0.51); // copy(...) ----------------------------------------------------------------- -let copiedQuantileScale: d3Scale.ScaleQuantile = quantileScaleNumber.copy(); +const copiedQuantileScale: d3Scale.ScaleQuantile = quantileScaleNumber.copy(); // ------------------------------------------------------------------------------- @@ -790,7 +779,7 @@ outputString = thresholdScaleNumberString(0.9); // copy(...) ----------------------------------------------------------------- -let copiedThresholdScale: d3Scale.ScaleThreshold = thresholdScaleNumberString.copy(); +const copiedThresholdScale: d3Scale.ScaleThreshold = thresholdScaleNumberString.copy(); // ------------------------------------------------------------------------------- @@ -826,13 +815,13 @@ rangeNumbers = ordinalScaleStringNumber.range(); // unknown(...) and d3Scale.scaleImplicit -------------------------------------- -let implicit: { name: 'implicit' } = d3Scale.scaleImplicit; +const implicit: { name: 'implicit' } = d3Scale.scaleImplicit; ordinalScaleStringString = ordinalScaleStringString.unknown(d3Scale.scaleImplicit); ordinalScaleStringNumber = ordinalScaleStringNumber.unknown(0); -let unknownValue: string | { name: 'implicit' } = ordinalScaleStringString.unknown(); +const unknownValue: string | { name: 'implicit' } = ordinalScaleStringString.unknown(); if (typeof unknownValue === 'string') { console.log(unknownValue); @@ -848,7 +837,7 @@ outputNumber = ordinalScaleStringNumber('negative'); // copy(...) ----------------------------------------------------------------- -let copiedOrdinalScale: d3Scale.ScaleOrdinal = ordinalScaleStringNumber.copy(); +const copiedOrdinalScale: d3Scale.ScaleOrdinal = ordinalScaleStringNumber.copy(); // ------------------------------------------------------------------------------- @@ -930,7 +919,7 @@ outputNumberMaybe = bandScaleCoercible(new StringCoercible('negative')); // copy(...) ----------------------------------------------------------------- -let copiedBandScale: d3Scale.ScaleBand = bandScaleCoercible.copy(); +const copiedBandScale: d3Scale.ScaleBand = bandScaleCoercible.copy(); // ------------------------------------------------------------------------------- @@ -1001,7 +990,7 @@ outputNumberMaybe = pointScaleCoercible(new StringCoercible('negative')); // copy(...) ----------------------------------------------------------------- -let copiedPointScale: d3Scale.ScalePoint = pointScaleCoercible.copy(); +const copiedPointScale: d3Scale.ScalePoint = pointScaleCoercible.copy(); // ------------------------------------------------------------------------------- // Categorical Color Schemas for Ordinal Scales diff --git a/d3-scale/index.d.ts b/d3-scale/index.d.ts index 2fe664346a..2ba9eeec8a 100644 --- a/d3-scale/index.d.ts +++ b/d3-scale/index.d.ts @@ -501,8 +501,10 @@ export interface ScaleLogarithmic extends ScaleContinuousNumeric< /** * Returns a number format function suitable for displaying a tick value, automatically computing the appropriate precision based on the fixed interval between tick values. * - * The specified count typically has the same value as the count that is used to generate the tick values. If there are too many ticks, the formatter may return the empty string for some of the tick labels; - * however, note that the ticks are still shown. To disable filtering, specify a count of Infinity. When specifying a count, you may also provide a format specifier or format function. + * The specified count typically has the same value as the count that is used to generate the tick values. + * If there are too many ticks, the formatter may return the empty string for some of the tick labels; + * however, note that the ticks are still shown. + * To disable filtering, specify a count of Infinity. When specifying a count, you may also provide a format specifier or format function. * For example, to get a tick formatter that will display 20 ticks of a currency, say log.tickFormat(20, "$,f"). * If the specifier does not have a defined precision, the precision will be set automatically by the scale, returning the appropriate format. * This provides a convenient way of specifying a format whose precision will be automatically set by the scale. @@ -1271,8 +1273,10 @@ export function scaleQuantize(): ScaleQuantize; // ------------------------------------------------------------------------------- /** - * Quantile scales map a sampled input domain to a discrete range. The domain is considered continuous and thus the scale will accept any reasonable input value; - * however, the domain is specified as a discrete set of sample values. The number of values in (the cardinality of) the output range determines the number of quantiles that will be computed from the domain. + * Quantile scales map a sampled input domain to a discrete range. + * The domain is considered continuous and thus the scale will accept any reasonable input value; + * however, the domain is specified as a discrete set of sample values. + * The number of values in (the cardinality of) the output range determines the number of quantiles that will be computed from the domain. * To compute the quantiles, the domain is sorted, and treated as a population of discrete values; see d3-array’s quantile. * * The generic correponds to the data type of range elements. @@ -1358,7 +1362,8 @@ export function scaleQuantile(): ScaleQuantile; * Threshold scales are similar to quantize scales, except they allow you to map arbitrary subsets of the domain to discrete values in the range. * The input domain is still continuous, and divided into slices based on a set of threshold values. * - * If the number of values in the scale’s range is N+1, the number of values in the scale’s domain must be N. If there are fewer than N elements in the domain, the additional values in the range are ignored. + * If the number of values in the scale’s range is N+1, the number of values in the scale’s domain must be N. + * If there are fewer than N elements in the domain, the additional values in the range are ignored. * If there are more than N elements in the domain, the scale may return undefined for some inputs. * * The first generic corresponds to the data type of domain values. diff --git a/d3-selection-multi/d3-selection-multi-tests.ts b/d3-selection-multi/d3-selection-multi-tests.ts index 5f8259052d..515dd8e92e 100644 --- a/d3-selection-multi/d3-selection-multi-tests.ts +++ b/d3-selection-multi/d3-selection-multi-tests.ts @@ -34,10 +34,10 @@ selection = selection.attrs({ }); // Function that returns a map -selection = selection.attrs(function (d, i, g) { - let that: HTMLAnchorElement = this; - let index: number = i; - let group: HTMLAnchorElement[] | ArrayLike = g; +selection = selection.attrs(function(d, i, g) { + const that: HTMLAnchorElement = this; + const index: number = i; + const group: HTMLAnchorElement[] | ArrayLike = g; return this.id ? {} : { id: d }; }); @@ -67,11 +67,11 @@ selection = selection.styles({ }, 'important'); // Functions that return a map -selection.styles(function (d) { +selection.styles(function(d) { return this.id ? { color: 'red' } : { color: d }; }); -selection = selection.styles(function (d) { +selection = selection.styles(function(d) { return this.id ? { color: 'red' } : { color: d }; }, 'important'); @@ -89,10 +89,10 @@ selection = selection.properties({ }); // Function that returns an object -selection = selection.properties(function (d, i, g) { - let that: HTMLAnchorElement = this; - let index: number = i; - let group: HTMLAnchorElement[] | ArrayLike = g; +selection = selection.properties(function(d, i, g) { + const that: HTMLAnchorElement = this; + const index: number = i; + const group: HTMLAnchorElement[] | ArrayLike = g; return that.href ? {} : { href: d }; }); @@ -112,16 +112,16 @@ transition = transition.attrs({ foo: () => 1, bar: (d) => d, baz: (d, i) => i !== 0, - bat: function () { + bat() { return this.href; }, }); // Function that returns a map -transition = transition.attrs(function (d, i, g) { - let that: HTMLAnchorElement = this; - let index: number = i; - let group: HTMLAnchorElement[] | ArrayLike = g; +transition = transition.attrs(function(d, i, g) { + const that: HTMLAnchorElement = this; + const index: number = i; + const group: HTMLAnchorElement[] | ArrayLike = g; return this.id ? {} : { id: d }; }); @@ -151,11 +151,11 @@ transition = transition.styles({ }, 'important'); // Function that returns a map -transition = transition.styles(function (d) { +transition = transition.styles(function(d) { return this.id ? { color: 'red' } : { color: d }; }); -transition = transition.styles(function (d) { +transition = transition.styles(function(d) { return this.id ? { color: 'red' } : { color: d }; }, 'important'); @@ -174,22 +174,22 @@ valueMap = { foo2: 2, foo3: true, foo4: null, - bar1: function (d) { - let that: SVGCircleElement = this; - let datum: SampleDatum = d; + bar1(d) { + const that: SVGCircleElement = this; + const datum: SampleDatum = d; return d.name; }, - bar2: function (d, i) { - let that: SVGCircleElement = this; - let datum: SampleDatum = d; - let index: number = i; + bar2(d, i) { + const that: SVGCircleElement = this; + const datum: SampleDatum = d; + const index: number = i; return d.r; }, - bar3: function (d, i, g) { - let that: SVGCircleElement = this; - let datum: SampleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; + bar3(d, i, g) { + const that: SVGCircleElement = this; + const datum: SampleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; return d.filled; } }; @@ -200,7 +200,7 @@ valueMap = { // valueMap = { // fails, as a ValueFunction returning an array is not a permissible value type // foo1: function (d) { -// let that: SVGCircleElement = this; +// const that: SVGCircleElement = this; // let datum: SampleDatum = d; // return [1, 2]; // } diff --git a/d3-selection/d3-selection-tests.ts b/d3-selection/d3-selection-tests.ts index 042fba622a..43d8708938 100644 --- a/d3-selection/d3-selection-tests.ts +++ b/d3-selection/d3-selection-tests.ts @@ -15,7 +15,7 @@ import * as d3Selection from 'd3-selection'; // --------------------------------------------------------------------------------------- // Generic DOM related variables -let xDoc: Document = document; +const xDoc: Document = document; let xWindow: Window = window; interface BodyDatum { @@ -59,14 +59,14 @@ interface CircleDatumAlternative { // test top-level .selection() ----------------------------------------------------------- -let topSelection: d3Selection.Selection = d3Selection.selection(); +const topSelection: d3Selection.Selection = d3Selection.selection(); // test top-level select() --------------------------------------------------------------- // Using select() with string argument and no type parameters creates selection // with Group element of type BaseType and datum of type 'any'. The parent element is of type HTMLElement with datum of type 'any' -let baseTypeEl: d3Selection.Selection = d3Selection.select('body'); +const baseTypeEl: d3Selection.Selection = d3Selection.select('body'); // Using select() with string argument and type parameters creates selection // with Group element of type HTMLBodyElement and datum of BodyDatum type. The parent element is of type HTMLElement with datum of type 'any' @@ -76,18 +76,18 @@ let body: d3Selection.Selection = // Using select() with node argument and no type parameters creates selection // with Group element of type BaseType and datum of type 'any' The parent element is of type 'null' with datum of type 'undefined' -let baseTypeEl2: d3Selection.Selection = d3Selection.select(baseTypeEl.node()); +const baseTypeEl2: d3Selection.Selection = d3Selection.select(baseTypeEl.node()); // let body2: d3Selection.Selection = d3Selection.select(baseTypeEl.node()); // fails as baseTypeEl.node() is of type cannot be assigned to HTMLElement -let body3: d3Selection.Selection = d3Selection.select(body.node()!); // element types match, but datum is of type 'any' as it cannot be inferred from .node() +const body3: d3Selection.Selection = d3Selection.select(body.node()!); // element types match, but datum is of type 'any' as it cannot be inferred from .node() // Using select() with node argument and type parameters creates selection // with Group element of type HTMLBodyElement and datum of BodyDatum type. The parent element is of type 'null' with datum of type 'undefined' -let body4: d3Selection.Selection = d3Selection.select(body.node()!); +const body4: d3Selection.Selection = d3Selection.select(body.node()!); // Explicitly cast body.node() to HTMLBodyElement to narrow selection definition. -let body5: d3Selection.Selection = d3Selection.select(body.node()!); +const body5: d3Selection.Selection = d3Selection.select(body.node()!); // d3Selection.select(baseTypeEl.node()!); // fails as baseTypeEl.node() is not of type HTMLBodyElement @@ -98,7 +98,8 @@ maybeSVG1 = d3Selection.select('svg'); let maybeSVG2: d3Selection.Selection; maybeSVG2 = d3Selection.select(maybeSVG1.node()); -// let body7: d3Selection.Selection = d3Selection.select(maybeSVG1.node()); // fails, as node type mismatches selection type +// fails, as node type mismatches selection type +// let body7: d3Selection.Selection = d3Selection.select(maybeSVG1.node()); // test "special case DOM objects" @@ -119,26 +120,28 @@ emptyRootSelection = d3Selection.selectAll(undefined); // Using selectAll(...) with string argument and no type parameters creates selection // with Group elements of type BaseType and datum of type 'any'. The parent element is of type HTMLElement with datum of type 'any' -let baseTypeElements: d3Selection.Selection = d3Selection.selectAll('div'); +const baseTypeElements: d3Selection.Selection = d3Selection.selectAll('div'); // Using selectAll() with string argument and type parameters creates selection // with Group element of type HTMLDivElement and datum of DivDatum type. The parent element is of type HTMLElement with datum of type 'any' -let divElements: d3Selection.Selection = d3Selection.selectAll('div'); +const divElements: d3Selection.Selection = d3Selection.selectAll('div'); // Using selectAll(...) with node array argument and no type parameters creates selection // with Group element of type BaseType and datum of type 'any' The parent element is of type 'null' with datum of type 'undefined' -let baseTypeElements2: d3Selection.Selection = d3Selection.selectAll(baseTypeElements.nodes()); -// let divElements2: d3Selection.Selection = d3Selection.selectAll(baseTypeElements.nodes()); // fails, group elements types not of compatible for baseTypeElements +const baseTypeElements2: d3Selection.Selection = d3Selection.selectAll(baseTypeElements.nodes()); +// fails, group elements types not of compatible for baseTypeElements +// let divElements2: d3Selection.Selection = d3Selection.selectAll(baseTypeElements.nodes()); -let divElements3: d3Selection.Selection = d3Selection.selectAll(divElements.nodes()); // element types match, but datum is of type 'any' as it cannot be inferred from .nodes() +// element types match, but datum is of type 'any' as it cannot be inferred from .nodes() +const divElements3: d3Selection.Selection = d3Selection.selectAll(divElements.nodes()); // Using selectAll(...) with node array argument and type parameters creates selection // with Group element of type HTMLDivElement and datum of DivDatum type. The parent element is of type 'null' with datum of type 'undefined' -let divElements4: d3Selection.Selection = d3Selection.selectAll(divElements.nodes()); +const divElements4: d3Selection.Selection = d3Selection.selectAll(divElements.nodes()); // d3Selection.selectAll(baseTypeElements.nodes()); // fails as baseTypeEl.node() is not of type HTMLBodyElement @@ -146,12 +149,12 @@ let divElements4: d3Selection.Selection argument -let xSVGCircleElementList: NodeListOf = document.querySelectorAll('circle'); -let circleSelection: d3Selection.Selection = d3Selection.selectAll(xSVGCircleElementList); +const xSVGCircleElementList: NodeListOf = document.querySelectorAll('circle'); +const circleSelection: d3Selection.Selection = d3Selection.selectAll(xSVGCircleElementList); // selectAll(...) accepts HTMLCollection, HTMLCollectionOf<...> argument -let documentLinks: d3Selection.Selection = d3Selection.selectAll(document.links); +const documentLinks: d3Selection.Selection = d3Selection.selectAll(document.links); @@ -168,7 +171,7 @@ let documentLinks: d3Selection.Selection = d3Selection.select('svg'); +const svgEl: d3Selection.Selection = d3Selection.select('svg'); let firstG: d3Selection.Selection = svgEl.select('g'); // let firstG_2: d3Selection.Selection = svgEl.select('g'); // fails, parent element of selection does not change with .select(...) @@ -187,19 +190,19 @@ function svgGroupSelector(this: SVGSVGElement, d: SVGDatum, i: number, groups: S firstG = svgEl.select(svgGroupSelector); -firstG = svgEl.select(function () { - let that: SVGSVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch +firstG = svgEl.select(function() { + const that: SVGSVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement return this.querySelector('g')!; // this of type SVGSVGElement by type inference }); -firstG = svgEl.select(function (d, i, g) { - let that: SVGSVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: SVGDatum = d; - let index: number = i; - let group: SVGSVGElement[] | d3Selection.ArrayLike = g; +firstG = svgEl.select(function(d, i, g) { + const that: SVGSVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: SVGDatum = d; + const index: number = i; + const group: SVGSVGElement[] | d3Selection.ArrayLike = g; console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement console.log('Width in datum:', d.width); // d is type of originating selection element Datum: SVGDatum if (g.length > 1) { @@ -246,19 +249,19 @@ function wrongSvgGroupSelectorAll(this: HTMLElement, d: SVGDatum, i: number, gro } // gElementsOldData = svgEl.selectAll(wrongSvgGroupSelectorAll); // fails, wrong this context -gElementsOldData = svgEl.selectAll(function () { - let that: SVGSVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch +gElementsOldData = svgEl.selectAll(function() { + const that: SVGSVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement return this.querySelectorAll('g'); // this of type SVGSVGElement by type inference }); -gElementsOldData = svgEl.selectAll(function (d, i, g) { - let that: SVGSVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: SVGDatum = d; - let index: number = i; - let group: SVGSVGElement[] | d3Selection.ArrayLike = g; +gElementsOldData = svgEl.selectAll(function(d, i, g) { + const that: SVGSVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: SVGDatum = d; + const index: number = i; + const group: SVGSVGElement[] | d3Selection.ArrayLike = g; console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement console.log('Width in datum:', d.width); // type of d is SVGDatum if (g.length > 1) { @@ -277,9 +280,9 @@ gElementsOldData = svgEl.selectAll(function (d, i, g) elementsUnknownData = svgEl.selectAll(svgGroupSelectorAll); -elementsUnknownData = svgEl.selectAll(function () { - let that: SVGSVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch +elementsUnknownData = svgEl.selectAll(function() { + const that: SVGSVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement return this.querySelectorAll('g'); // this of type SVGSVGElement by type inference }); @@ -288,13 +291,13 @@ elementsUnknownData = svgEl.selectAll(function () { // return this.querySelectorAll('a'); // }); -maybeG.selectAll(function (d, i, g) { - let that: SVGGElement | null = this; - // let that2: SVGGElement = this; // fails with strictNullChecks - // let that3: HTMLElement | null = this; // fails, type mismatch - let datum: SVGDatum = d; - let index: number = i; - let group: Array | d3Selection.ArrayLike = g; +maybeG.selectAll(function(d, i, g) { + const that: SVGGElement | null = this; + // const that2: SVGGElement = this; // fails with strictNullChecks + // const that3: HTMLElement | null = this; // fails, type mismatch + const datum: SVGDatum = d; + const index: number = i; + const group: Array | d3Selection.ArrayLike = g; return that ? that.querySelectorAll('circle') : []; }); @@ -319,12 +322,12 @@ let filterdGElements: d3Selection.Selection = g; +filterdGElements = gElementsOldData.filter(function(d, i, g) { + const that: SVGGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGGElement[] | d3Selection.ArrayLike = g; console.log('Element Id of DOM element: ', this.id); // this context SVGGElement if (g.length > 0) { console.log('Element Id of first DOM element in group: ', g[0].id); // group: Array @@ -341,11 +344,11 @@ filterdGElements2 = d3Selection.selectAll('.any-svg-type').filt // filterdGElements2 = d3Selection.selectAll('.any-type').filter('g'); // fails without using narrowing generic on filter method filterdGElements2 = d3Selection.selectAll('.any-svg-type').filter(function(){ - let that: SVGElement = this; + const that: SVGElement = this; return that.tagName === 'g' || that.tagName === 'G'; }); // filterdGElements2 = d3Selection.selectAll('.any-svg-type').filter(function(){ -// let that: SVGElement = this; +// const that: SVGElement = this; // return that.tagName === 'g'|| that.tagName === 'G'; // }); // fails without using narrowing generic on filter method @@ -385,27 +388,23 @@ circles = d3Selection.selectAll('circl .attr('stroke', 'blue'); // string circles = circles // re-assignment test chaining return-type - .attr('cx', function (d, i, g) { - let that: SVGGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGGElement[] | d3Selection.ArrayLike = g; + .attr('cx', function(d, i, g) { + const that: SVGGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGGElement[] | d3Selection.ArrayLike = g; console.log('Pre-change center x-coordinate: ', this.cx.baseVal.value); // this context SVGCircleElement if (g.length > 0) { console.log('Owner SVG Element of first group element:', g[0].ownerSVGElement); // group : Array } return d.cx; // numeric return value }) - .attr('stroke', function (d) { - return d.color; // string return value - }); + .attr('stroke', d => d.color); // string return value divs = d3Selection.selectAll('div') .attr('contenteditable', false) // boolean - .attr('contenteditable', function () { - return false; // boolean return value - }); + .attr('contenteditable', () => false); // boolean return value // classed(...) Tests @@ -413,12 +412,12 @@ divs = divs .classed('success', true); divs = divs - .classed('zero-px-padding', function (d, i, g) { - let that: HTMLDivElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: DivDatum = d; - let index: number = i; - let group: HTMLDivElement[] | d3Selection.ArrayLike = g; + .classed('zero-px-padding', function(d, i, g) { + const that: HTMLDivElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: DivDatum = d; + const index: number = i; + const group: HTMLDivElement[] | d3Selection.ArrayLike = g; console.log('Client Rectangle Top: ', this.getBoundingClientRect().top); // this context HTMLDivElement if (g.length > 0) { console.log('Alignment of first group element:', g[0].align); // group : Array @@ -436,23 +435,21 @@ divs = divs .style('color', 'green', 'important'); divs = divs - .style('padding', function (d, i, g) { - let that: HTMLDivElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: DivDatum = d; - let index: number = i; - let group: HTMLDivElement[] | d3Selection.ArrayLike = g; + .style('padding', function(d, i, g) { + const that: HTMLDivElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: DivDatum = d; + const index: number = i; + const group: HTMLDivElement[] | d3Selection.ArrayLike = g; console.log('Client Rectangle Top: ', this.getBoundingClientRect().top); // this context HTMLDivElement if (g.length > 0) { console.log('Alignment of first group element:', g[0].align); // group : Array } return d.padding; // string return value }) - .style('hidden', function () { - return true; - }, null) // boolean return + test: priority = null - // .style('color', function () { return 'green'; }, 'test') // fails, test: invalid priority value - .style('color', function () { return 'green'; }, 'important'); // boolean return + test: priority = 'important'; + .style('hidden', () => true, null) // boolean return + test: priority = null + // .style('color', function() { return 'green'; }, 'test') // fails, test: invalid priority value + .style('color', () => 'green', 'important'); // boolean return + test: priority = 'important'; // property(...) Tests @@ -464,12 +461,12 @@ circles = circles }); // any circles = circles - .property('__hitchhikersguide__', function (d, i, g) { - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatumAlternative = d; - let index: number = i; - let group: SVGCircleElement[] | d3Selection.ArrayLike = g; + .property('__hitchhikersguide__', function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatumAlternative = d; + const index: number = i; + const group: SVGCircleElement[] | d3Selection.ArrayLike = g; console.log('Pre-change center x-coordinate: ', this.cx.baseVal.value); // this context SVGCircleElement if (g.length > 0) { console.log('Owner SVG Element of first group element:', g[0].ownerSVGElement); // group : Array @@ -488,32 +485,28 @@ body = body .text(true); // boolean will be converted to string by D3 body = body - .text(function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | d3Selection.ArrayLike = g; + .text(function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; console.log('Body background color: ', this.bgColor); // this context HTMLBodyElement return d.foo; // BodyDatum }) - .text(function (d) { - return 42; // number will be converted to string by D3 - }) - .text(function (d) { - return true; // boolean will be converted to string by D3 - }); + .text(d => 42) // number will be converted to string by D3 + .text(d => true); // boolean will be converted to string by D3 body = body .html('
42
'); body = body - .html(function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | d3Selection.ArrayLike = g; + .html(function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; return '
Body Background Color: ' + this.bgColor + ', Foo Datum: ' + d.foo + '
'; // this context HTMLBodyElement, datum BodyDatum }); @@ -522,13 +515,13 @@ body = body // --------------------------------------------------------------------------------------- -let data: CircleDatum[] = [ +const data: CircleDatum[] = [ { nodeId: 'c1', cx: 10, cy: 10, r: 5, name: 'foo', label: 'Foo' }, { nodeId: 'c2', cx: 20, cy: 20, r: 5, name: 'bar', label: 'Bar' }, { nodeId: 'c3', cx: 30, cy: 30, r: 5, name: 'fooBar', label: 'Foo Bar' } ]; -let data2: CircleDatumAlternative[] = [ +const data2: CircleDatumAlternative[] = [ { nodeId: 'c1', cx: 10, cy: 10, r: 5, name: 'foo', label: 'Foo', color: 'seagreen' }, { nodeId: 'c2', cx: 20, cy: 20, r: 5, name: 'bar', label: 'Bar', color: 'midnightblue' }, { nodeId: 'c4', cx: 10, cy: 15, r: 10, name: 'newbie', label: 'Newbie', color: 'red' } @@ -538,7 +531,7 @@ let data2: CircleDatumAlternative[] = [ // Tests of Datum ----------------------------------------------------------------------- // TEST GETTER -let bodyDatum: BodyDatum = body.datum(); +const bodyDatum: BodyDatum = body.datum(); // TEST REMOVE DATUM body.datum(null); // removes datum, i.e. return type has group datum type 'undefined' @@ -555,18 +548,18 @@ newBodyDatum = body.datum({ newFoo: 'new foo' }).datum(); // inferred type // function-based -newBodyDatum = body.datum(function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | d3Selection.ArrayLike = g; +newBodyDatum = body.datum(function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; console.log('HTML5 Custom Data Attributes of body: ', this.dataset); // this typings HTMLBodyElement console.log('Old foo:', d.foo); // current data of type BodyDatum return { newFoo: 'new foo' }; }).datum(); // inferred type -// newBodyDatum = body.datum(function (d) { // fails, data type incompatible with return value type +// newBodyDatum = body.datum(function(d) { // fails, data type incompatible with return value type // console.log('HTML5 Custom Data Attributes of body: ', this.dataset); // this typings HTMLBodyElement // return { newFoo: 'new foo' }; // }).datum(); // inferred type @@ -579,7 +572,7 @@ newBodyDatum = body.datum(function (d, i, g) { d3Selection.select('#svg-1') .select('g.circles-group') // first matching element only .datum(data2) - .classed('has-transform-property', function (d) { + .classed('has-transform-property', function(d) { console.log('Color of first data element array', d.length > 0 ? d[0].color : 'Data array empty'); return this.transform !== undefined; }); @@ -589,12 +582,12 @@ d3Selection.select('#svg-1') d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in last step of chain .select('g.circles-group') .datum(data2) // new data type inferred - .classed('has-transform-property', function (d, i, g) { - let that: SVGGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatumAlternative[] = d; - let index: number = i; - let group: SVGGElement[] | d3Selection.ArrayLike = g; + .classed('has-transform-property', function(d, i, g) { + const that: SVGGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatumAlternative[] = d; + const index: number = i; + const group: SVGGElement[] | d3Selection.ArrayLike = g; console.log('Color of first data element array', d.length > 0 ? d[0].color : 'Data array empty'); // CircleDatumAlternative type return this.transform !== undefined; }); @@ -604,7 +597,7 @@ d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in la // d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in last step of chain // .select('g.circles-group') // missing typing of selected DOM element for use in .classed(...) // .datum(data2) // new data type inferred -// .classed('has-transform-property', function (d) { +// .classed('has-transform-property', function(d) { // console.log('Color of first data element array', d.length > 0? d[0].color: 'Data array empty'); // CircleDatumAlternative type // return this.transform !== undefined; // }); @@ -614,12 +607,12 @@ d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in la d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in last step of chain .select('g.circles-group') // irrelevant typing to get contextual typing in last step of chain .datum(data2) // new data type inferred - .classed('has-green-first-data-element', function (d, i, g) { - let that: d3Selection.BaseType = this; - // let that2: Element = this; // fails, type mismatch - let datum: CircleDatumAlternative[] = d; - let index: number = i; - let group: d3Selection.BaseType[] | d3Selection.ArrayLike = g; + .classed('has-green-first-data-element', function(d, i, g) { + const that: d3Selection.BaseType = this; + // const that2: Element = this; // fails, type mismatch + const datum: CircleDatumAlternative[] = d; + const index: number = i; + const group: d3Selection.BaseType[] | d3Selection.ArrayLike = g; return d.length > 0 && d[0].color === 'green'; }); @@ -627,12 +620,12 @@ d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in la // Tests of Data Join -------------------------------------------------------------------- -let dimensions: SVGDatum = { +const dimensions: SVGDatum = { width: 500, height: 300 }; -let startCircleData: CircleDatumAlternative[] = [ +const startCircleData: CircleDatumAlternative[] = [ { nodeId: 'n1', name: 'node_1', @@ -652,7 +645,7 @@ let startCircleData: CircleDatumAlternative[] = [ color: 'slateblue' } ]; -let endCircleData: CircleDatumAlternative[] = [ +const endCircleData: CircleDatumAlternative[] = [ { nodeId: 'n1', name: 'node_1', @@ -683,8 +676,8 @@ let circles2: d3Selection.Selection('#svg2') .datum(dimensions) - .attr('width', function (d) { return d.width; }) - .attr('height', function (d) { return d.height; }) + .attr('width', d => d.width) + .attr('height', d => d.height) .selectAll() // create empty Selection .data(startCircleData) // assign data for circles to be added (no previous circles) .enter() // obtain enter selection @@ -694,9 +687,9 @@ circles2 = d3Selection.select('#svg2') // Assign new data and use key(...) function for mapping circles2 = circles2 // returned update selection has the same type parameters as original selection, if data type is unchanged - .data(endCircleData, function (d) { return d.nodeId; }); + .data(endCircleData, d => d.nodeId); -// circles2.data(endCircleData, function (d) { return d.nodeId; }); // fails, forced data type parameter and data argument mismatch +// circles2.data(endCircleData, function(d) { return d.nodeId; }); // fails, forced data type parameter and data argument mismatch // ENTER-selection ----------------------------------------------------------------- @@ -706,27 +699,27 @@ let enterElements: d3Selection.Selection('circle') // enter selection with materialized DOM elements (svg circles) - .attr('cx', function (d) { return d.cx; }) - .attr('cy', function (d) { return d.cy; }) - .attr('r', function (d) { return d.r; }) - .style('stroke', function (d) { return d.color; }) - .style('fill', function (d) { return d.color; }); + .attr('cx', d => d.cx) + .attr('cy', d => d.cy) + .attr('r', d => d.r) + .style('stroke', d => d.color) + .style('fill', d => d.color); // EXIT-selection ---------------------------------------------------------------------- // tests exit(...) and remove() -let exitCircles = circles2.exit(); // Note: need to re-type datum type, as the exit selection elements have the 'old data' +const exitCircles = circles2.exit(); // Note: need to re-type datum type, as the exit selection elements have the 'old data' exitCircles - .style('opacity', function (d, i, g) { - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatumAlternative = d; - let index: number = i; - let group: SVGCircleElement[] | d3Selection.ArrayLike = g; + .style('opacity', function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatumAlternative = d; + const index: number = i; + const group: SVGCircleElement[] | d3Selection.ArrayLike = g; console.log('Circle Radius exit node: ', this.r.baseVal.value); // this type is SVGCircleElement return d.color === 'green' ? 1 : 0; // data type as per .exit<...>() parameterization }) @@ -737,7 +730,7 @@ exitCircles // let exitCircles2 = circles2.exit(); // Note: Without explicit re-typing to the old data type, the data type default to '{}' // exitCircles2 -// .style('opacity', function (d) { +// .style('opacity', function(d) { // console.log('Circle Radius exit node: ', this.r.baseVal.value); // return d.color === 'green' ? 1 : 0; // fails, as data type is defaulted to {}. If datum access is required, this should trigger the thought to type .exit<...> // }); @@ -775,14 +768,14 @@ nMatrix = tr.data(); // i.e. matrix let td: d3Selection.Selection; td = tr.selectAll() - .data(function (d) { return d; }) // d : Array inferred (Array[4] of number per parent ) + .data(d => d) // d : Array inferred (Array[4] of number per parent ) .enter().append('td') - .text(function (d, i, g) { - let that: HTMLTableDataCellElement = this; - // let that2: Element = this; // fails, type mismatch - let datum: number = d; - let index: number = i; - let group: HTMLTableDataCellElement[] | d3Selection.ArrayLike = g; + .text(function(d, i, g) { + const that: HTMLTableDataCellElement = this; + // const that2: Element = this; // fails, type mismatch + const datum: number = d; + const index: number = i; + const group: HTMLTableDataCellElement[] | d3Selection.ArrayLike = g; console.log('Abbreviated text for object', this.abbr); // this-type HTMLTableDataCellElement (demonstration only) return d; }); // d:number inferred @@ -791,7 +784,7 @@ nRow = td.data(); // flattened matrix (Array[16] of number) // SCENARIO 2 - Completely inferred types, when there is no need for `this` typings -let tr2 = d3Selection.select('body') +const tr2 = d3Selection.select('body') .append('table') .selectAll('tr') .data(matrix) @@ -799,10 +792,10 @@ let tr2 = d3Selection.select('body') nMatrix = tr2.data(); // i.e. matrix -let td2 = tr2.selectAll('td') - .data(function (d) { return d; }) // d : Array inferred (Array[4] of number per parent ) +const td2 = tr2.selectAll('td') + .data(d => d) // d : Array inferred (Array[4] of number per parent ) .enter().append('td') - .text(function (d) { return d; }); // d:number inferred + .text(d => d); // d:number inferred nRow = td2.data(); // flattened matrix (Array[16] of number) @@ -823,12 +816,12 @@ newDiv2 = body.append('div'); newDiv2 = body.append(d3Selection.creator('div')); // newDiv2 = body.append(d3Selection.creator('div')); // fails, as creator returns BaseType element, but HTMLDivElement is expected. -newDiv2 = body.append(function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | d3Selection.ArrayLike = g; +newDiv2 = body.append(function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; console.log('Body element foo property: ', d.foo); // data of type BodyDatum return this.ownerDocument.createElement('div'); // this-type HTMLBodyElement }); @@ -850,23 +843,23 @@ newParagraph = body.insert('p'); // Two arguments; the first can be string, selection , or a -const typeValueFunction = function ( +const typeValueFunction = function( this: HTMLBodyElement, d: BodyDatum, i: number, g: HTMLBodyElement[] | d3Selection.ArrayLike ) { return this.ownerDocument.createElement('p'); // this-type HTMLParagraphElement -} +}; -const beforeValueFunction = function ( +const beforeValueFunction = function( this: HTMLBodyElement, d: BodyDatum, i: number, g: HTMLBodyElement[] | d3Selection.ArrayLike ) { - return this.children[0]; -} + return this.children[0]; +}; let newParagraph2: d3Selection.Selection; @@ -887,9 +880,7 @@ newParagraph2 = body.insert(typeValueFunction); // sort(...) ----------------------------------------------------------------------------- // NB: Return new selection of same type -circles2 = circles2.sort(function (a, b) { - return (b.r - a.r); -}); +circles2 = circles2.sort((a, b) => b.r - a.r); // order(...) ---------------------------------------------------------------------------- @@ -911,27 +902,27 @@ circles2 = circles2.lower(); // --------------------------------------------------------------------------------------- // empty() ------------------------------------------------------------------------------- -let emptyFlag = gElementsOldData.empty(); +const emptyFlag = gElementsOldData.empty(); // node() and nodes() -------------------------------------------------------------------- -let bodyNode: HTMLBodyElement | null= body.node(); +const bodyNode: HTMLBodyElement | null = body.node(); -let gElementsNodes: SVGGElement[] = gElementsOldData.nodes(); +const gElementsNodes: SVGGElement[] = gElementsOldData.nodes(); // size() -------------------------------------------------------------------------------- -let size: number = gElementsOldData.size(); +const size: number = gElementsOldData.size(); // each() ------------------------------------------------------------------------------- // returns 'this' selection -circles = circles.each(function (d, i, g) { // check chaining return type by re-assigning - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | d3Selection.ArrayLike = g; +circles = circles.each(function(d, i, g) { // check chaining return type by re-assigning + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | d3Selection.ArrayLike = g; if (this.r.baseVal.value < d.r) { // this of type SVGCircleElement, datum of type CircleDatumAlternative d3Selection.select(this).attr('r', d.r); } @@ -942,8 +933,8 @@ circles = circles.each(function (d, i, g) { // check chaining return type by re function enforceMinRadius(selection: d3Selection.Selection, minRadius: number): void { - selection.attr('r', function (d) { - let r: number = +d3Selection.select(this).attr('r'); + selection.attr('r', function(d) { + const r: number = +d3Selection.select(this).attr('r'); return Math.max(r, minRadius); }); @@ -952,11 +943,11 @@ function enforceMinRadius(selection: d3Selection.Selection):void { +// circles.call(function(selection: d3Selection.Selection):void { // // fails, group element types of selection not compatible: SVGCircleElement v HTMLDivElement // }); -// circles.call(function (selection: d3Selection.Selection):void { +// circles.call(function(selection: d3Selection.Selection):void { // // fails, group datum types of selection not compatible: CircleDatumAlternative v DivDatum // }); @@ -969,12 +960,12 @@ circles = circles.call(enforceMinRadius, 40); // check chaining return type by r let listener: undefined | ((this: HTMLBodyElement, datum: BodyDatum, index: number, group: HTMLBodyElement[] | ArrayLike) => void); -body = body.on('click', function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | ArrayLike = g; +body = body.on('click', function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | ArrayLike = g; console.log('onclick print body background color: ', this.bgColor); // HTMLBodyElement console.log('onclick print "foo" datum property: ', d.foo); // BodyDatum type }); @@ -993,7 +984,7 @@ body = body.on('click', null); // check chaining return type by re-assigning // dispatch(...) ------------------------------------------------------------------------- -let fooEventParam: d3Selection.CustomEventParameters = { +const fooEventParam: d3Selection.CustomEventParameters = { cancelable: true, bubbles: true, detail: [1, 2, 3, 4] @@ -1002,12 +993,12 @@ let fooEventParam: d3Selection.CustomEventParameters = { // returns 'this' selection body = body.dispatch('fooEvent', fooEventParam); // re-assign for chaining test; -body = body.dispatch('fooEvent', function (d, i, g) { // re-assign for chaining test; - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | d3Selection.ArrayLike = g; +body = body.dispatch('fooEvent', function(d, i, g) { // re-assign for chaining test; + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; let eParam: d3Selection.CustomEventParameters; console.log('fooEvent dispatch body background color', this.bgColor); eParam = { @@ -1030,17 +1021,17 @@ interface SuccessEvent { team: string; sourceEvent?: any; } -let successEvent = { type: 'wonEuro2016', team: 'Island' }; +const successEvent = { type: 'wonEuro2016', team: 'Island' }; let customListener: (this: HTMLBodyElement, finalOpponent: string) => string; -customListener = function (finalOpponent) { - let e = d3Selection.event; +customListener = finalOpponent => { + const e = d3Selection.event; return e.team + ' defeated ' + finalOpponent + ' in the EURO 2016 Cup. Who would have thought!!!'; }; -let resultText: string = d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales'); +const resultText: string = d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales'); // let result = d3Selection.customEvent(successEvent, customListener, circles.nodes()[0], 'Wales'); // fails, incompatible 'this' context in call // let resultValue: number = d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales'); // fails, incompatible return types @@ -1051,10 +1042,10 @@ let resultText: string = d3Selection.customEvent(successEvent, customListener, b // mouse() --------------------------------------------------------------------------------- let position: [number, number] | null; -let svg: SVGSVGElement = d3Selection.select('svg').node()!; -let g: SVGGElement = d3Selection.select('g').node()!; -let h: HTMLElement = d3Selection.select('div').node()!; -let changedTouches: TouchList = new TouchList(); // dummy +const svg: SVGSVGElement = d3Selection.select('svg').node()!; +const g: SVGGElement = d3Selection.select('g').node()!; +const h: HTMLElement = d3Selection.select('div').node()!; +const changedTouches: TouchList = new TouchList(); // dummy position = d3Selection.mouse(svg); position = d3Selection.mouse(g); @@ -1084,9 +1075,9 @@ positions = d3Selection.touches(h, changedTouches); // Tests of Local // --------------------------------------------------------------------------------------- -let xElement: Element = d3Selection.select('foo').node()!; -let foo: d3Selection.Local = d3Selection.local(); -let propName: string = foo.toString(); +let xElement: Element = d3Selection.select('foo').node()!; +const foo: d3Selection.Local = d3Selection.local(); +const propName: string = foo.toString(); // direct set & get on Local object xElement = foo.set(xElement, [1, 2, 3]); @@ -1104,7 +1095,7 @@ foo.remove(xElement); // Tests of Namespace // --------------------------------------------------------------------------------------- -let predefinedNamespaces: d3Selection.NamespaceMap = d3Selection.namespaces; +const predefinedNamespaces: d3Selection.NamespaceMap = d3Selection.namespaces; const svgNamespace: string = predefinedNamespaces['svg']; diff --git a/d3-selection/index.d.ts b/d3-selection/index.d.ts index 1d0ab9472c..49cd141dfa 100644 --- a/d3-selection/index.d.ts +++ b/d3-selection/index.d.ts @@ -820,7 +820,8 @@ interface Selection): this; diff --git a/d3-shape/d3-shape-tests.ts b/d3-shape/d3-shape-tests.ts index beec6c84c8..204f1e7eb1 100644 --- a/d3-shape/d3-shape-tests.ts +++ b/d3-shape/d3-shape-tests.ts @@ -16,7 +16,6 @@ import { path } from 'd3-path'; let context: CanvasRenderingContext2D | null = document.querySelector('canvas')!.getContext('2d'); let num: number; -let pathString: string; let pathStringMaybe: string | null; // ----------------------------------------------------------------------------------- @@ -31,7 +30,7 @@ interface ArcDatum { pAngle: number; } -let arcDefaultDatum: d3Shape.DefaultArcObject = { +const arcDefaultDatum: d3Shape.DefaultArcObject = { innerRadius: 40, outerRadius: 60, startAngle: 0, @@ -39,7 +38,7 @@ let arcDefaultDatum: d3Shape.DefaultArcObject = { padAngle: 0.03 }; -let arcDatum: ArcDatum = { +const arcDatum: ArcDatum = { iRadius: 40, oRadius: 60, sAngle: 0, @@ -52,7 +51,7 @@ let accessorArcDatumNumberOrNull: ((this: any, d: ArcDatum, ...args: any[]) => n // DefaultArcObject interface ======================================================== -let defaultArcObject: d3Shape.DefaultArcObject = { +const defaultArcObject: d3Shape.DefaultArcObject = { innerRadius: 0, outerRadius: 100, startAngle: 0, @@ -86,7 +85,7 @@ svgArc = svgArc.context(null); // use as path string generator for SVG canvasArc = canvasArc.innerRadius(40); -svgArc = svgArc.innerRadius(function (d) { +svgArc = svgArc.innerRadius(d => { return d.iRadius; // datum type is ArcDatum }); accessorArcDatumNumber = svgArc.innerRadius(); @@ -95,7 +94,7 @@ accessorArcDatumNumber = svgArc.innerRadius(); canvasArc = canvasArc.outerRadius(60); -svgArc = svgArc.outerRadius(function (d) { +svgArc = svgArc.outerRadius(d => { return d.oRadius; // datum type is ArcDatum }); accessorArcDatumNumber = svgArc.outerRadius(); @@ -104,7 +103,7 @@ accessorArcDatumNumber = svgArc.outerRadius(); canvasArc = canvasArc.cornerRadius(4); -svgArc = svgArc.cornerRadius(function (d) { +svgArc = svgArc.cornerRadius(d => { return d.oRadius / 10; // datum type is ArcDatum }); accessorArcDatumNumber = svgArc.cornerRadius(); @@ -113,7 +112,7 @@ accessorArcDatumNumber = svgArc.cornerRadius(); canvasArc = canvasArc.startAngle(0); -svgArc = svgArc.startAngle(function (d) { +svgArc = svgArc.startAngle(d => { return d.sAngle; // datum type is ArcDatum }); accessorArcDatumNumber = svgArc.startAngle(); @@ -122,7 +121,7 @@ accessorArcDatumNumber = svgArc.startAngle(); canvasArc = canvasArc.endAngle(Math.PI / 2); -svgArc = svgArc.endAngle(function (d) { +svgArc = svgArc.endAngle(d => { return d.eAngle; // datum type is ArcDatum }); accessorArcDatumNumber = svgArc.endAngle(); @@ -131,7 +130,7 @@ accessorArcDatumNumber = svgArc.endAngle(); canvasArc = canvasArc.padAngle(0); -svgArc = svgArc.padAngle(function (d) { +svgArc = svgArc.padAngle(d => { return d.pAngle; // datum type is ArcDatum }); accessorArcDatumNumber = svgArc.padAngle(); @@ -140,7 +139,7 @@ accessorArcDatumNumber = svgArc.padAngle(); canvasArc = canvasArc.padRadius(0); -svgArc = svgArc.padRadius(function (d) { +svgArc = svgArc.padRadius(d => { return Math.sqrt(d.iRadius * d.iRadius + d.oRadius * d.oRadius); }); @@ -153,7 +152,7 @@ accessorArcDatumNumberOrNull = svgArc.padRadius(); // centroid(...) --------------------------------------------------------------------- -let centroid: [number, number] = svgArc.centroid(arcDatum); +const centroid: [number, number] = svgArc.centroid(arcDatum); // centroid = svgArc.centroid(arcDefaultDatum); // fails, wrong datum type // generate arc ---------------------------------------------------------------------- @@ -164,9 +163,9 @@ canvasArc(arcDefaultDatum); // use with svg -let pArc: Selection = select('.arc-paths'); // mock -let wrongArc1: Selection = select('.arc-paths'); // mock -let wrongArc2: Selection = select('.arc-paths'); // mock +const pArc: Selection = select('.arc-paths'); // mock +const wrongArc1: Selection = select('.arc-paths'); // mock +const wrongArc2: Selection = select('.arc-paths'); // mock pArc.attr('d', svgArc); // wrongArc1.attr('d', svgArc); // fails, incompatible this contexts @@ -192,10 +191,10 @@ class Arcer { this.cornerRadius = 3; this.arc = d3Shape.arc() - .innerRadius(function (d) { + .innerRadius(d => { return Math.min(d.innerRadius, this.innerRadius); }) - .outerRadius(function (d) { + .outerRadius(d => { return Math.min(d.outerRadius, this.outerRadius); }) .cornerRadius(this.cornerRadius) @@ -217,7 +216,7 @@ class Arcer { } } -let arcer = new Arcer(100, 120); +const arcer = new Arcer(100, 120); pathStringMaybe = arcer.getPathString(); pathStringMaybe = arcer.getPathString({ innerRadius: 10, outerRadius: 20 }); @@ -237,7 +236,7 @@ let accessorPieDatumNumber: (this: any, data: PieDatum[], ...args: any[]) => num // PieArcDatum interface ============================================================= -let pieArcObject: d3Shape.PieArcDatum = { +const pieArcObject: d3Shape.PieArcDatum = { data: { val: 10, name: "Segment 1" @@ -249,7 +248,7 @@ let pieArcObject: d3Shape.PieArcDatum = { padAngle: 0 }; -let pieDatum: PieDatum = pieArcObject.data; +const pieDatum: PieDatum = pieArcObject.data; num = pieArcObject.value; num = pieArcObject.index; num = pieArcObject.startAngle; @@ -274,7 +273,7 @@ defaultPieValueAccessor = defaultPie.value(); let pieValueAccessor: (d: PieDatum, i?: number, data?: PieDatum[]) => number; -pie = pie.value(function (d, i, data) { +pie = pie.value((d, i, data) => { console.log(data.length > 0 ? data[0].val : 'no data'); // data type is Array return d.val; // d type is PieDatum }); @@ -286,7 +285,7 @@ pieValueAccessor = pie.value(); let pieSorter: ((a: PieDatum, b: PieDatum) => number) | null; -pie = pie.sort(function (a, b) { +pie = pie.sort((a, b) => { return b.val - a.val; // type of a and b is PieDatum }); @@ -298,7 +297,7 @@ pie = pie.sort(null); let pieValuesSorter: ((a: number, b: number) => number) | null; -pie = pie.sortValues(function (a, b) { +pie = pie.sortValues((a, b) => { return b - a; // type of a and b is number }); @@ -310,7 +309,7 @@ pie = pie.sortValues(null); defaultPie = defaultPie.startAngle(0); -pie = pie.startAngle(function (d) { +pie = pie.startAngle(d => { console.log(d.length > 0 ? d[0].val : 'no data'); // data type is Array return 0; }); @@ -320,7 +319,7 @@ accessorPieDatumNumber = pie.startAngle(); defaultPie = defaultPie.endAngle(2 * Math.PI); -pie = pie.endAngle(function (d) { +pie = pie.endAngle(d => { console.log(d.length > 0 ? d[0].val : 'no data'); // data type is Array return 2 * Math.PI; }); @@ -330,7 +329,7 @@ accessorPieDatumNumber = pie.endAngle(); defaultPie = defaultPie.padAngle(0.03); -pie = pie.padAngle(function (d) { +pie = pie.padAngle(d => { console.log(d.length > 0 ? d[0].val : 'no data'); // data type is Array return 0.03; @@ -343,7 +342,7 @@ let defaultPieChart: Array>; defaultPieChart = defaultPie([20, 10, 30, 40]); -let pieData: PieDatum[] = [ +const pieData: PieDatum[] = [ { name: 'John', val: 20 }, { name: 'Jill', val: 10 }, { name: 'Rodrigo', val: 30 } @@ -396,7 +395,7 @@ line = line.context(null); // use as path string generator for SVG defaultLine = defaultLine.x(30); -line = line.x(function (d, t, data) { +line = line.x((d, t, data) => { console.log('Number of Points: ', data.length); console.log('X-Coordinate of first point: ', data[0].x); // data type is Array return d.x; // d type is LineDatum @@ -408,7 +407,7 @@ lineXYAccessorFn = line.x(); defaultLine = defaultLine.y(10); -line = line.y(function (d, t, data) { +line = line.y((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Y-Coordinate of first point: ', data[0].y); // data type is Array return d.y; // d type is LineDatum @@ -420,7 +419,7 @@ lineXYAccessorFn = line.y(); defaultLine = defaultLine.defined(true); -line = line.defined(function (d, t, data) { +line = line.defined((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Y-Coordinate of first point: ', data[0].y); // data type is Array return !d.missing; // d type is LineDatum @@ -440,13 +439,13 @@ let currentCurveFactory: d3Shape.CurveFactory | d3Shape.CurveFactoryLineOnly = l defaultLine([[10, 10], [20, 10], [20, 20]]); -let lineData: LineDatum[] = [ +const lineData: LineDatum[] = [ { x: 10, y: 10, missing: false }, { x: 20, y: 10, missing: false }, { x: 20, y: 20, missing: false } ]; -let linePathStringMaybe: string | null = line(lineData); +const linePathStringMaybe: string | null = line(lineData); // radialLine(...) create Line generator ===================================================== @@ -468,7 +467,7 @@ radialLine = radialLine.context(null); // use as path string generator for SVG defaultRadialLine = defaultRadialLine.angle(Math.PI); -radialLine = radialLine.angle(function (d, t, data) { +radialLine = radialLine.angle((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Angle of first point: ', data[0].angle); // data type is Array return d.angle; // d type is RadialLineDatum @@ -480,7 +479,7 @@ radialLineAngRAccessorFn = radialLine.angle(); defaultRadialLine = defaultRadialLine.radius(30); -radialLine = radialLine.radius(function (d, t, data) { +radialLine = radialLine.radius((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Angle of first point: ', data[0].angle); // data type is Array return d.radius; // d type is RadialLineDatum @@ -492,7 +491,7 @@ radialLineAngRAccessorFn = radialLine.radius(); defaultRadialLine = defaultRadialLine.defined(true); -radialLine = radialLine.defined(function (d, t, data) { +radialLine = radialLine.defined((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Angle of first point: ', data[0].angle); // data type is Array return !d.missing; // d type is RadialLineDatum @@ -512,13 +511,13 @@ currentCurveFactory = radialLine.curve(); defaultRadialLine([[10, 10], [20, 10], [20, 20]]); -let radialLineData: RadialLineDatum[] = [ +const radialLineData: RadialLineDatum[] = [ { angle: 0, radius: 10, missing: false }, { angle: Math.PI / 2, radius: 20, missing: false }, { angle: 2 * Math.PI, radius: 10, missing: false } ]; -let radialLinePathStringMaybe: string | null = radialLine(radialLineData); +const radialLinePathStringMaybe: string | null = radialLine(radialLineData); // ----------------------------------------------------------------------------------- @@ -569,7 +568,7 @@ area = area.context(null); // use as path string generator for SVG defaultArea = defaultArea.x(30); -area = area.x(function (d, t, data) { +area = area.x((d, t, data) => { console.log('Number of Points: ', data.length); console.log('X0-Coordinate of first point: ', data[0].x0); // data type is Array return d.x0; // d type is AreaDatum @@ -581,7 +580,7 @@ areaXYAccessorFn = area.x(); defaultArea = defaultArea.x0(30); -area = area.x0(function (d, t, data) { +area = area.x0((d, t, data) => { console.log('Number of Points: ', data.length); console.log('X0-Coordinate of first point: ', data[0].x0); // data type is Array return d.x0; // d type is AreaDatum @@ -593,7 +592,7 @@ areaXYAccessorFn = area.x0(); defaultArea = defaultArea.x1(30); -area = area.x1(function (d, t, data) { +area = area.x1((d, t, data) => { console.log('Number of Points: ', data.length); console.log('X1-Coordinate of first point: ', data[0].x1); // data type is Array return d.x1; // d type is AreaDatum @@ -605,7 +604,7 @@ areaXYAccessorFnMaybe = area.x1(); defaultArea = defaultArea.y(10); -area = area.y(function (d, t, data) { +area = area.y((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Y0-Coordinate of first point: ', data[0].y0); // data type is Array return d.y0; // d type is AreaDatum @@ -617,7 +616,7 @@ areaXYAccessorFn = area.y(); defaultArea = defaultArea.y0(10); -area = area.y0(function (d, t, data) { +area = area.y0((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Y0-Coordinate of first point: ', data[0].y0); // data type is Array return d.y0; // d type is AreaDatum @@ -629,7 +628,7 @@ areaXYAccessorFn = area.y0(); defaultArea = defaultArea.y1(10); -area = area.y1(function (d, t, data) { +area = area.y1((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Y1-Coordinate of first point: ', data[0].y1); // data type is Array return d.y1; // d type is AreaDatum @@ -641,7 +640,7 @@ areaXYAccessorFnMaybe = area.y1(); defaultArea = defaultArea.defined(true); -area = area.defined(function (d, t, data) { +area = area.defined((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Y0-Coordinate of first point: ', data[0].y0); // data type is Array return !d.missing; // d type is AreaDatum @@ -662,13 +661,13 @@ currentCurveFactory = area.curve(); defaultArea([[10, 10], [20, 10], [20, 20]]); -let areaData: AreaDatum[] = [ +const areaData: AreaDatum[] = [ { x0: 10, y0: 10, x1: 10, y1: 30, missing: false }, { x0: 20, y0: 20, x1: 20, y1: 40, missing: false }, { x0: 30, y0: 30, x1: 30, y1: 30, missing: false } ]; -let areaPathStringMaybe: string | null = area(areaData); +const areaPathStringMaybe: string | null = area(areaData); // Get Line Generators from Area generator ======================================================== @@ -699,7 +698,7 @@ radialArea = radialArea.context(null); // use as path string generator for SVG defaultRadialArea = defaultRadialArea.angle(Math.PI); -radialArea = radialArea.angle(function (d, t, data) { +radialArea = radialArea.angle((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Start angle of first point: ', data[0].startAngle); // data type is Array return d.startAngle; // d type is RadialAreaDatum @@ -711,7 +710,7 @@ radialAreaAngRAccessorFn = radialArea.angle(); defaultRadialArea = defaultRadialArea.startAngle(Math.PI); -radialArea = radialArea.startAngle(function (d, t, data) { +radialArea = radialArea.startAngle((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Start angle of first point: ', data[0].startAngle); // data type is Array return d.startAngle; // d type is RadialAreaDatum @@ -723,7 +722,7 @@ radialAreaAngRAccessorFn = radialArea.startAngle(); defaultRadialArea = defaultRadialArea.endAngle(Math.PI); -radialArea = radialArea.endAngle(function (d, t, data) { +radialArea = radialArea.endAngle((d, t, data) => { console.log('Number of Points: ', data.length); console.log('End angle of first point: ', data[0].endAngle); // data type is Array return d.endAngle; // d type is RadialAreaDatum @@ -735,7 +734,7 @@ radialAreaAngRAccessorFnMaybe = radialArea.endAngle(); defaultRadialArea = defaultRadialArea.radius(10); -radialArea = radialArea.radius(function (d, t, data) { +radialArea = radialArea.radius((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Inner radius of first point: ', data[0].innerRadius); // data type is Array return d.innerRadius; // d type is RadialAreaDatum @@ -747,7 +746,7 @@ radialAreaAngRAccessorFn = radialArea.radius(); defaultRadialArea = defaultRadialArea.innerRadius(10); -radialArea = radialArea.innerRadius(function (d, t, data) { +radialArea = radialArea.innerRadius((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Inner radius of first point: ', data[0].innerRadius); // data type is Array return d.innerRadius; // d type is RadialAreaDatum @@ -759,7 +758,7 @@ radialAreaAngRAccessorFn = radialArea.innerRadius(); defaultRadialArea = defaultRadialArea.outerRadius(20); -radialArea = radialArea.outerRadius(function (d, t, data) { +radialArea = radialArea.outerRadius((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Outer radius of first point: ', data[0].outerRadius); // data type is Array return d.outerRadius; // d type is RadialAreaDatum @@ -771,7 +770,7 @@ radialAreaAngRAccessorFnMaybe = radialArea.outerRadius(); defaultRadialArea = defaultRadialArea.defined(true); -radialArea = radialArea.defined(function (d, t, data) { +radialArea = radialArea.defined((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Inner radius of first point: ', data[0].innerRadius); // data type is Array return !d.missing; // d type is RadialAreaDatum @@ -792,13 +791,13 @@ currentCurveFactory = radialArea.curve(); defaultRadialArea([[10, 10], [20, 10], [20, 20]]); -let radialAreaData: RadialAreaDatum[] = [ +const radialAreaData: RadialAreaDatum[] = [ { startAngle: 0, innerRadius: 10, endAngle: 0, outerRadius: 30, missing: false }, { startAngle: Math.PI / 2, innerRadius: 20, endAngle: Math.PI / 2, outerRadius: 40, missing: false }, { startAngle: Math.PI, innerRadius: 30, endAngle: Math.PI, outerRadius: 30, missing: false } ]; -let radialAreaPathStringMaybe: string | null = radialArea(radialAreaData); +const radialAreaPathStringMaybe: string | null = radialArea(radialAreaData); // Get RadialLine Generators from RadialArea generator ======================================================== @@ -818,7 +817,7 @@ areaRadialLineGenerator = radialArea.lineOuterRadius(); let lineOnlyGenerator: d3Shape.CurveGeneratorLineOnly; -let lineOnlyFactory: d3Shape.CurveFactoryLineOnly = d3Shape.curveBundle; +const lineOnlyFactory: d3Shape.CurveFactoryLineOnly = d3Shape.curveBundle; lineOnlyGenerator = lineOnlyFactory(path()); lineOnlyGenerator = lineOnlyFactory(context!); // force context to be non-null with post-fix for mock @@ -925,7 +924,7 @@ interface SymbolDatum { let customSymbol: d3Shape.SymbolType; customSymbol = { - draw: function (context: CanvasPathMethods, size: number): void { + draw(context: CanvasPathMethods, size: number): void { // draw custom symbol using canvas path methods } }; @@ -955,7 +954,7 @@ svgSymbol = svgSymbol.context(null); // use as path string generator for SVG canvasSymbol = canvasSymbol.size(30); -svgSymbol = svgSymbol.size(function (d) { +svgSymbol = svgSymbol.size(d => { return d.size; // datum type is SymbolDatum }); @@ -966,7 +965,7 @@ sizeAccessorFn = svgSymbol.size(); canvasSymbol = canvasSymbol.type(d3Shape.symbolDiamond); -svgSymbol = svgSymbol.type(function (d) { +svgSymbol = svgSymbol.type(d => { let t: d3Shape.SymbolType; switch (d.type) { // datum type is SymbolDatum case 'circle': @@ -990,14 +989,14 @@ typeAccessorFn = svgSymbol.type(); // use with canvas canvasSymbol(); -let symbolDatum: SymbolDatum = { +const symbolDatum: SymbolDatum = { size: 30, type: 'circle' }; -let pSymbol: Selection = select('.symbol-path'); // mock -let wrongSymbol1: Selection = select('.symbol-path'); // mock -let wrongSymbol2: Selection = select('.symbol-path'); // mock +const pSymbol: Selection = select('.symbol-path'); // mock +const wrongSymbol1: Selection = select('.symbol-path'); // mock +const wrongSymbol2: Selection = select('.symbol-path'); // mock pSymbol.attr('d', svgSymbol); // wrongSymbol1.attr('d', svgSymbol); // fails, incompatible this contexts @@ -1023,10 +1022,10 @@ class Symbolizer { break; } this.symbol = d3Shape.symbol() - .size(function (this: Symbolizer, d?: SymbolDatum) { + .size(function(this: Symbolizer, d?: SymbolDatum) { return d ? d.size : this.size; }) - .type(function (this: Symbolizer, d?: SymbolDatum) { + .type(function(this: Symbolizer, d?: SymbolDatum) { let type = this.type; if (d && d.type) { switch (d.type) { @@ -1052,7 +1051,7 @@ class Symbolizer { } } -let sym = new Symbolizer(100, 'square'); +const sym = new Symbolizer(100, 'square'); pathStringMaybe = sym.getPathString(); pathStringMaybe = sym.getPathString({ size: 10, type: 'circle' }); @@ -1060,7 +1059,7 @@ pathStringMaybe = sym.getPathString({ size: 10, type: 'circle' }); // Test pre-fab symbols =============================================================== -let symbolArray: d3Shape.SymbolType[] = d3Shape.symbols; +const symbolArray: d3Shape.SymbolType[] = d3Shape.symbols; customSymbol = d3Shape.symbolCircle; customSymbol = d3Shape.symbolCross; @@ -1087,13 +1086,13 @@ interface StackKey { let key: StackKey; -let keys: StackKey[] = [ +const keys: StackKey[] = [ { name: 'bananas', label: 'Bananas' }, { name: 'apples', label: 'Apples' }, { name: 'oranges', label: 'Oranges' } ]; -let stackData: StackDatum[] = [ +const stackData: StackDatum[] = [ { values: { bananas: 10, apples: 20, oranges: 10 } }, { values: { bananas: 10, apples: 25, oranges: 0 } }, { values: { bananas: 20, apples: 20, oranges: 30 } }, @@ -1118,7 +1117,7 @@ overlyComplicatedStack = d3Shape.stack(); defaultStack = defaultStack.keys(['bananas', 'apples', 'oranges']); -overlyComplicatedStack = overlyComplicatedStack.keys(function (data: StackDatum[], keys: StackKey[]) { +overlyComplicatedStack = overlyComplicatedStack.keys((data: StackDatum[], keys: StackKey[]) => { return keys; }); @@ -1129,7 +1128,7 @@ keysAccessor = overlyComplicatedStack.keys(); defaultStack = defaultStack.value(30); -overlyComplicatedStack = overlyComplicatedStack.value(function (d, key, j, data) { +overlyComplicatedStack = overlyComplicatedStack.value((d, key, j, data) => { return d.values[key.name]; }); @@ -1172,7 +1171,7 @@ seriesArray = overlyComplicatedStack(stackData, keys); // Test SeriesPoint and Series interfaces ============================================ -let series: d3Shape.Series = seriesArray[0]; +const series: d3Shape.Series = seriesArray[0]; let seriesPoint: d3Shape.SeriesPoint; seriesPoint = series[0]; key = series.key; @@ -1187,7 +1186,7 @@ seriesDatum = seriesPoint.data; // Test stack orders =============================================================== let order: number[]; -let seriesAnyAny: d3Shape.Series = seriesArray[0]; +const seriesAnyAny: d3Shape.Series = seriesArray[0]; order = d3Shape.stackOrderAscending(seriesAnyAny); order = d3Shape.stackOrderDescending(seriesAnyAny); diff --git a/d3-shape/index.d.ts b/d3-shape/index.d.ts index 3292eae937..367a9dee2b 100644 --- a/d3-shape/index.d.ts +++ b/d3-shape/index.d.ts @@ -371,11 +371,15 @@ export interface PieArcDatum { */ index: number; /** - * The start angle of the arc. If the pie generator was configured to be used for the arc generator, than the units are in radians with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + * The start angle of the arc. + * If the pie generator was configured to be used for the arc generator, + * then the units are in radians with 0 at -y (12 o’clock) and positive angles proceeding clockwise. */ startAngle: number; /** - * The end angle of the arc. If the pie generator was configured to be used for the arc generator, than the units are in radians with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + * The end angle of the arc. + * If the pie generator was configured to be used for the arc generator, + * then the units are in radians with 0 at -y (12 o’clock) and positive angles proceeding clockwise. */ endAngle: number; /** @@ -1160,7 +1164,8 @@ export interface Area { * * The default accessor for defined returns a constant boolean value of true, thus assumes that the input data is always defined. * When an area is generated, the defined accessor will be invoked for each element in the input data array, being passed the element d, the index i, and the array data as three arguments. - * If the given element is defined (i.e., if the defined accessor returns a truthy value for this element), the x0, x1, y0 and y1 accessors will subsequently be evaluated and the point will be added to the current area segment. + * If the given element is defined (i.e., if the defined accessor returns a truthy value for this element), + * the x0, x1, y0 and y1 accessors will subsequently be evaluated and the point will be added to the current area segment. * Otherwise, the element will be skipped, the current area segment will be ended, and a new area segment will be generated for the next defined point. * As a result, the generated area may have several discrete segments. * @@ -1176,8 +1181,10 @@ export interface Area { * The default accessor for defined returns a constant boolean value of true, thus assumes that the input data is always defined. * * The default accessor for defined returns a constant boolean value of true, thus assumes that the input data is always defined. - * When an area is generated, the defined accessor will be invoked for each element in the input data array, being passed the element d, the index i, and the array data as three arguments. - * If the given element is defined (i.e., if the defined accessor returns a truthy value for this element), the x0, x1, y0 and y1 accessors will subsequently be evaluated and the point will be added to the current area segment. + * When an area is generated, the defined accessor will be invoked for each element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + * If the given element is defined (i.e., if the defined accessor returns a truthy value for this element), + * the x0, x1, y0 and y1 accessors will subsequently be evaluated and the point will be added to the current area segment. * Otherwise, the element will be skipped, the current area segment will be ended, and a new area segment will be generated for the next defined point. * As a result, the generated area may have several discrete segments. * @@ -2095,7 +2102,8 @@ export interface Series extends Array> { /** * A stack generator. * - * Some shape types can be stacked, placing one shape adjacent to another. For example, a bar chart of monthly sales might be broken down into a multi-series bar chart by product category, stacking bars vertically. + * Some shape types can be stacked, placing one shape adjacent to another. + * For example, a bar chart of monthly sales might be broken down into a multi-series bar chart by product category, stacking bars vertically. * This is equivalent to subdividing a bar chart by an ordinal dimension (such as product category) and applying a color encoding. * * Stacked charts can show overall value and per-category value simultaneously; however, it is typically harder to compare across categories, as only the bottom layer of the stack is aligned. @@ -2140,7 +2148,8 @@ export interface Stack { * A series (layer) is generated for each key. Keys are typically strings, but they may be arbitrary values. * The series’ key is passed to the value accessor, along with each data point, to compute the point’s value. * - * @param keys An accessor function returning the array of keys. The accessor function is invoked with the "this" context of the Stack generator and passed the same arguments passed into the generator. + * @param keys An accessor function returning the array of keys. + * The accessor function is invoked with the "this" context of the Stack generator and passed the same arguments passed into the generator. */ keys(keys: (this: This, data: Datum[], ...args: any[]) => Key[]): this; @@ -2208,7 +2217,8 @@ export interface Stack { /** * Sets the offset accessor to the specified function and returns this stack generator. * - * @param offset A function which is passed the generated series array and the order index array. The offset function is then responsible for updating the lower and upper values in the series array to layout the stack. + * @param offset A function which is passed the generated series array and the order index array. + * The offset function is then responsible for updating the lower and upper values in the series array to layout the stack. */ offset(offset: (series: Series, order: number[]) => void): this; diff --git a/d3-transition/d3-transition-tests.ts b/d3-transition/d3-transition-tests.ts index 1feeabf042..c2917aaf94 100644 --- a/d3-transition/d3-transition-tests.ts +++ b/d3-transition/d3-transition-tests.ts @@ -39,12 +39,12 @@ interface CircleDatum { color: string; } -let dimensions: SVGDatum = { +const dimensions: SVGDatum = { width: 500, height: 300 }; -let startCircleData: CircleDatum[] = [ +const startCircleData: CircleDatum[] = [ { nodeId: 'n1', name: 'node_1', @@ -65,7 +65,7 @@ let startCircleData: CircleDatum[] = [ } ]; -let endCircleData: CircleDatum[] = [ +const endCircleData: CircleDatum[] = [ { nodeId: 'n1', name: 'node_1', @@ -97,33 +97,33 @@ let circles: Selection; circles = select('svg') .datum(dimensions) - .attr('width', function (d) { return d.width; }) - .attr('height', function (d) { return d.height; }) + .attr('width', d => d.width) + .attr('height', d => d.height) .selectAll() .data(startCircleData) .enter() .append('circle') - .attr('cx', function (d) { return d.cx; }) - .attr('cy', function (d) { return d.cy; }) - .attr('r', function (d) { return d.r; }) - .style('stroke', function (d) { return d.color; }) - .style('fill', function (d) { return d.color; }); + .attr('cx', d => d.cx) + .attr('cy', d => d.cy) + .attr('r', d => d.r) + .style('stroke', d => d.color) + .style('fill', d => d.color); circles = circles - .data(endCircleData, function (d) { return d.nodeId; }); + .data(endCircleData, d => d.nodeId); -let enterCircles = circles +const enterCircles = circles .enter() .append('circle') - .classed('big', function (d) { return d.r > 10; }) - .attr('cx', function (d) { return d.cx; }) - .attr('cy', function (d) { return d.cy; }) - .attr('r', function (d) { return d.r; }) - .style('stroke', function (d) { return d.color; }) - .style('fill', function (d) { return d.color; }); + .classed('big', d => d.r > 10) + .attr('cx', d => d.cx) + .attr('cy', d => d.cy) + .attr('r', d => d.r) + .style('stroke', d => d.color) + .style('fill', d => d.color); -let exitCircles = circles.exit(); // Note: need to re-type datum type, as the exit selection elements have the 'old data' +const exitCircles = circles.exit(); // Note: need to re-type datum type, as the exit selection elements have the 'old data' // -------------------------------------------------------------------------- // Create Transition from Selection @@ -159,21 +159,19 @@ newEnterTransition = enterCircles.transition(differentDatumTypeTransition); // duration() --------------------------------------------------------------- enterTransition = enterTransition.duration(2000); // settable and chainable -let duration: number = enterTransition.duration(); +const duration: number = enterTransition.duration(); // delay() --------------------------------------------------------------- enterTransition = enterTransition.delay(500); // settable and chainable -let delay: number = enterTransition.delay(); +const delay: number = enterTransition.delay(); // ease() --------------------------------------------------------------- let easingFn: (normalizedTime: number) => number; -enterTransition = enterTransition.ease(function (t) { - return t; -}); // settable and chainable +enterTransition = enterTransition.ease(t => t); // settable and chainable easingFn = enterTransition.ease(); // -------------------------------------------------------------------------- @@ -190,7 +188,7 @@ interface ParagraphDatum { } // assume body was previously selected and its data were set to BodyDatum type using .datum() -let bodyTransition: d3Transition.Transition = select('body').transition(); +const bodyTransition: d3Transition.Transition = select('body').transition(); // select() ------------------------------------------------------------------ @@ -198,12 +196,12 @@ let bodyTransition: d3Transition.Transition = bodyTransition.select('div'); -firstDivTransition = bodyTransition.select(function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | ArrayLike = g; +firstDivTransition = bodyTransition.select(function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | ArrayLike = g; console.log('Body Datum foo', d.foo); // d is of type BodyDatum return this.querySelector('div')!; // 'this' type is HTMLElement, return type is HTMLDivElement @@ -217,12 +215,12 @@ firstDivTransition = bodyTransition.select(function (d, i, g) { let paragraphsTransition: d3Transition.Transition = firstDivTransition.selectAll('p'); -paragraphsTransition = firstDivTransition.selectAll(function (d, i, g) { - let that: HTMLDivElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLDivElement[] | ArrayLike = g; +paragraphsTransition = firstDivTransition.selectAll(function(d, i, g) { + const that: HTMLDivElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLDivElement[] | ArrayLike = g; console.log('Body Datum foo', d.foo); // d is of type BodyDatum return this.querySelectorAll('p'); // 'this' type is HTMLElement, return type is HTMLParagraphElement }); @@ -233,12 +231,12 @@ paragraphsTransition = firstDivTransition.selectAll = g; +exitTransition = exitTransition.filter(function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; // console.log(this.x) // fails, x property not defined on SVGCircleElement return this.r.baseVal.value < i * d.r; // this-type SVGCircleElement, datum tpye CircleDatum }); @@ -251,16 +249,16 @@ let filterdGElements2: d3Transition.Transition('.any-svg-type').transition().filter('g'); // filterdGElements2 = selectAll('.any-type').transition().filter('g'); // fails without using narrowing generic on filter method -filterdGElements2 = selectAll('.any-svg-type').transition().filter(function (d, i, g) { - let that: SVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGElement[] | ArrayLike = g; +filterdGElements2 = selectAll('.any-svg-type').transition().filter(function(d, i, g) { + const that: SVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGElement[] | ArrayLike = g; return that.tagName === 'g' || that.tagName === 'G'; }); // filterdGElements2 = selectAll('.any-svg-type').transition().filter(function(){ -// let that: SVGElement = this; +// const that: SVGElement = this; // return that.tagName === 'g'|| that.tagName === 'G'; // }); // fails without using narrowing generic on filter method @@ -281,21 +279,19 @@ enterTransition = enterTransition // re-assignment test chaining return-type .attr('stroke', 'blue'); // string enterTransition = enterTransition // re-assignment test chaining return-type - .attr('cx', function (d, i, g) { - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; + .attr('cx', function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; console.log('Pre-change center x-coordinate: ', this.cx.baseVal.value); // this context SVGCircleElement if (group.length > 0) { console.log('Owner SVG Element of first group element:', g[0].ownerSVGElement); // group : Array } return d.cx; // numeric return value }) - .attr('stroke', function (d) { - return d.color; // string return value - }); + .attr('stroke', d => d.color); // string return value enterTransition = enterTransition .style('fill', 'blue') // string @@ -304,30 +300,28 @@ enterTransition = enterTransition .style('stroke', 'green', 'important'); enterTransition = enterTransition - .style('fill', function (d, i, g) { - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; + .style('fill', function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; console.log('Client Rectangle Top: ', this.getBoundingClientRect().top); // this context SVGCircleElement if (g.length > 0) { console.log('Radius of first group element:', g[0].r.baseVal.value); // group : Array } return d.color; // string return value }) - .style('hidden', function () { - return true; - }, null) // boolean return + test: priority = null - // .style('stroke', function () { return 'green'; }, 'test') // fails, test: invalid priority value - .style('stroke', function () { return 'green'; }, 'important'); // string return + test: priority = 'important'; + .style('hidden', () => true, null) // boolean return + test: priority = null + // .style('stroke', function() { return 'green'; }, 'test') // fails, test: invalid priority value + .style('stroke', () => 'green', 'important'); // string return + test: priority = 'important'; select('body') .datum({ test: 'New text.' }) .transition().duration(500) - .text('Let us start with this transition text.') + .text('const us start with this transition text.') .transition().duration(100) - .text(function (d) { return d.test; }); // selection datum type + .text(d => d.test); // selection datum type // test, when it is not certain, whether an element of the type to be selected exists @@ -337,12 +331,12 @@ maybeG1 = selectAll('svg') .selectAll('circle') .transition() .duration(500) - .attr('fill', function (d, i, g) { - let that: SVGCircleElement | null = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: Array | ArrayLike = g; + .attr('fill', function(d, i, g) { + const that: SVGCircleElement | null = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: Array | ArrayLike = g; if (that) { return that.r.baseVal.value < 5 ? 'slateblue' : 'seagreen'; @@ -354,19 +348,19 @@ maybeG1 = selectAll('svg') // Tweening Function Use ===================================================== -enterTransition = enterTransition.attrTween('r', function (d, i, g) { - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; +enterTransition = enterTransition.attrTween('r', function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; console.log(this.r.baseVal.value); // this type is SVGCircleElement return interpolateString(0, d.r); // datum type is CircleDatum }); -exitTransition = exitTransition.styleTween('fill', function (d, i, group) { +exitTransition = exitTransition.styleTween('fill', function(d, i, group) { console.log(this.r.baseVal.value); // this type is SVGCircleElement - let c: string = select(this).style('fill'); + const c: string = select(this).style('fill'); return interpolateRgb(c, d.color); // datum type is CircleDatum }); @@ -377,16 +371,16 @@ let tweenFnAccessor: undefined | ((this: SVGCircleElement, datum?: CircleDatum, updateTransition = updateTransition.tween('fillColor', null); // remove named tween // chainable -updateTransition = updateTransition.tween('fillColor', function (d, i, g) { - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; - let c: string | null = that.getAttribute('fill'); - let interpolator = interpolateRgb(c ? c : 'blue', d.color); // datum type CircleDatum +updateTransition = updateTransition.tween('fillColor', function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; + const c: string | null = that.getAttribute('fill'); + const interpolator = interpolateRgb(c ? c : 'blue', d.color); // datum type CircleDatum console.log('Radius ', this.r.baseVal.value); // this type SVGCircleElement - return function (t) { + return t => { that.setAttribute('fill', interpolator(t)); }; }); @@ -414,12 +408,12 @@ exitTransition.remove(); let listener: undefined | ((this: SVGCircleElement, datum: CircleDatum, index: number, group: SVGCircleElement[] | ArrayLike) => void); -enterTransition = enterTransition.on('end', function (d, i, g) { - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; +enterTransition = enterTransition.on('end', function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; console.log('transition end radius: ', this.r.baseVal.value); // SVGCircleElement console.log('end event datum color property: ', d.color); // CircleDatum type }); @@ -445,12 +439,12 @@ enterTransition = enterTransition.on('end', null); // check chaining return type // each(valueFn: (this: GElement, datum?: Datum, index?: number, group?: Array | ArrayLike) => void): Transition; // returns 'this' transition -enterTransition = enterTransition.each(function (d, i, g) { // check chaining return type by re-assigning - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; +enterTransition = enterTransition.each(function(d, i, g) { // check chaining return type by re-assigning + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; if (this.r.baseVal.value < d.r) { // this of type SVGCircleElement, datum of type CircleDatum console.log('Color of circles with current radius smaller than data radius: ', d.color); } @@ -461,33 +455,33 @@ enterTransition = enterTransition.each(function (d, i, g) { // check chaining r function changeExitColor(transition: d3Transition.Transition, fill: string, stroke: string) { transition - .style('fill', function (d) { return (d.r < 10) ? fill : 'black'; }) // datum type is CircleDatum - .style('stroke', function (d) { return (this.r.baseVal.value < 10) ? stroke : 'black'; }); // this type is SVGCircleElement + .style('fill', d => (d.r < 10) ? fill : 'black') // datum type is CircleDatum + .style('stroke', function(d) { return (this.r.baseVal.value < 10) ? stroke : 'black'; }); // this type is SVGCircleElement } // returns 'this' transition exitTransition = exitTransition.call(changeExitColor, 'midnightblue', 'black'); // check chaining return type by re-assigning -// exitTransition.call(function (transition: d3Transition.Transition): void { +// exitTransition.call(function(transition: d3Transition.Transition): void { // // fails, group element types of selection not compatible: SVGCircleElement v HTMLDivElement // }); -// exitTransition.call(function (transition: d3Transition.Transition): void { +// exitTransition.call(function(transition: d3Transition.Transition): void { // // fails, group datum types of selection not compatible: CircleDatum v DivDatum // }); // empty() ------------------------------------------------------------------------------- -let empty: boolean = enterTransition.empty(); +const empty: boolean = enterTransition.empty(); // node() and nodes() -------------------------------------------------------------------- -let firstCircleNode: SVGCircleElement = enterTransition.node()!; -let circleNodes: SVGCircleElement[] = enterTransition.nodes(); +const firstCircleNode: SVGCircleElement = enterTransition.node()!; +const circleNodes: SVGCircleElement[] = enterTransition.nodes(); // size() -------------------------------------------------------------------------------- -let size: number = enterTransition.size(); +const size: number = enterTransition.size(); // -------------------------------------------------------------------------- // Sequencing transitions on the same selection diff --git a/d3-transition/index.d.ts b/d3-transition/index.d.ts index 22527c81ad..e2e49f6c2a 100644 --- a/d3-transition/index.d.ts +++ b/d3-transition/index.d.ts @@ -461,7 +461,8 @@ export interface Transition): this; diff --git a/d3-zoom/d3-zoom-tests.ts b/d3-zoom/d3-zoom-tests.ts index 4806479476..f4a1c0944e 100644 --- a/d3-zoom/d3-zoom-tests.ts +++ b/d3-zoom/d3-zoom-tests.ts @@ -16,7 +16,7 @@ import { interpolateZoom, interpolate, interpolateArray, ZoomInterpolator, ZoomV // Preparatory Steps // -------------------------------------------------------------------------- -let points: Array<[number, number]> = [ +const points: Array<[number, number]> = [ [10, 10], [20, 20], [50, 50] ]; @@ -28,12 +28,12 @@ interface CanvasDatum { radius: number; } -let canvas = select('canvas') +const canvas = select('canvas') .datum({ width: 500, height: 400, radius: 2.5 }) - .attr('width', function (d) { return d.width; }) - .attr('height', function (d) { return d.height; }); + .attr('width', d => d.width) + .attr('height', d => d.height); -let context = canvas.node()!.getContext('2d'); +const context = canvas.node()!.getContext('2d'); function drawPointsOnCanvas(radius: number) { if (context) { @@ -44,8 +44,7 @@ function drawPointsOnCanvas(radius: number) { } function drawPointOnCanvas(radius: number) { - - return function (point: [number, number]) { + return (point: [number, number]) => { if (context) { context.moveTo(point[0] + radius, point[1]); context.arc(point[0], point[1], radius, 0, 2 * Math.PI); @@ -62,19 +61,19 @@ interface SVGDatum { filterBrushEvent: boolean; } -let svg = select('svg') +const svg = select('svg') .datum({ width: 500, height: 500, filterBrushEvent: true }) - .attr('width', function (d) { return d.width; }) - .attr('height', function (d) { return d.height; }); + .attr('width', d => d.width) + .attr('height', d => d.height); -let g = svg.append('g'); +const g = svg.append('g'); g.selectAll() .data<[number, number]>(points) .enter().append('circle') - .attr('cx', function (d) { return d[0]; }) - .attr('cy', function (d) { return d[1]; }) + .attr('cx', d => d[0]) + .attr('cy', d => d[1]) .attr('r', 2.5); // For test of using zoomBehavior to transform selections and transitions ---- @@ -86,9 +85,6 @@ interface GroupDatum { toK: number; } -let groupsSelection: Selection; -let groupsTransition: Transition; - // -------------------------------------------------------------------------- // Test Define ZoomBehaviour @@ -99,7 +95,7 @@ let groupsTransition: Transition; function zoomedCanvas(this: HTMLCanvasElement, d: CanvasDatum) { // Cast d3 event to D3ZoomEvent to be used in zoom event handler - let e = > event; + const e = > event; if (context) { context.save(); context.clearRect(0, 0, this.width, this.height); // this element @@ -121,7 +117,7 @@ canvasZoom = d3Zoom.zoom() function zoomedSVGOverlay(this: SVGRectElement) { // Cast d3 event to D3ZoomEvent to be used in zoom event handler - let e = > event; + const e = > event; g.attr('transform', e.transform.toString()); } @@ -134,10 +130,9 @@ svgZoom = d3Zoom.zoom(); // filter() ---------------------------------------------------------------- // chainable -svgZoom = svgZoom.filter(function (d, i, group) { - +svgZoom = svgZoom.filter(function(d, i, group) { // Cast d3 event to D3ZoomEvent to be used in filter logic - let e = > event; + const e = > event; console.log('Overlay Rectangle width: ', this.width.baseVal.value); // this typing is SVGRectElement return e.sourceEvent.type !== 'brush' || !d.filterBrushEvent; // datum type is SVGDatum (as propagated to SVGRectElement with zoom event attached) @@ -156,7 +151,7 @@ extentAccessor = svgZoom.extent(); svgZoom = svgZoom.extent([[0, 0], [200, 200]]); // chainable with accessor function -svgZoom = svgZoom.extent(function (d, i, group) { +svgZoom = svgZoom.extent(function(d, i, group) { console.log('Overlay Rectangle width: ', this.width.baseVal.value); // this typing is SVGRectElement return [[0, 0], [d.width, d.height]]; // datum type is SVGDatum }); @@ -183,7 +178,7 @@ translateExtent = svgZoom.translateExtent(); // chainable svgZoom = svgZoom.duration(500); -let duration: number = svgZoom.duration(); +const duration: number = svgZoom.duration(); // interpolate() -------------------------------------------------------------- @@ -234,14 +229,14 @@ canvas.call(canvasZoom); // SVG Example -------------------------------------------------------------- // attach the zoom behavior to an overlay svg rectangle -let svgOverlay: Selection = svg.append('rect') - .attr('width', function (d) { return d.width; }) - .attr('height', function (d) { return d.height; }) +const svgOverlay: Selection = svg.append('rect') + .attr('width', d => d.width) + .attr('height', d => d.height) .style('fill', 'none') .style('pointer-events', 'all') .call(svgZoom); -let svgOverlayTransition = svgOverlay.transition(); +const svgOverlayTransition = svgOverlay.transition(); // -------------------------------------------------------------------------- // Test Use ZoomBehaviour @@ -253,11 +248,11 @@ let svgOverlayTransition = svgOverlay.transition(); svgZoom.transform(svgOverlay, d3Zoom.zoomIdentity); // svgZoom.transform(groupsSelection, d3Zoom.zoomIdentity); // fails, as groupSelection mismachtes DOM Element type and datum type -svgZoom.transform(svgOverlay, function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; +svgZoom.transform(svgOverlay, function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return d3Zoom.zoomIdentity; @@ -267,11 +262,11 @@ svgOverlayTransition.call(svgZoom.transform, d3Zoom.zoomIdentity); // svgZoom.transform(groupsTransition, d3Zoom.zoomIdentity); // fails, as groupTransition mismachtes DOM Element type and datum type svgZoom.transform(svgOverlayTransition, d3Zoom.zoomIdentity); -svgZoom.transform(svgOverlayTransition, function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; +svgZoom.transform(svgOverlayTransition, function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return d3Zoom.zoomIdentity; @@ -286,22 +281,22 @@ svgZoom.translateBy(svgOverlay, 20, 50); svgZoom.translateBy( svgOverlay, 20, - function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; }); svgZoom.translateBy( svgOverlay, - function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; @@ -309,20 +304,20 @@ svgZoom.translateBy( 50); svgZoom.translateBy( svgOverlay, - function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; }, - function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; @@ -335,22 +330,22 @@ svgZoom.translateBy(svgOverlayTransition, 20, 50); svgZoom.translateBy( svgOverlayTransition, 20, - function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; }); svgZoom.translateBy( svgOverlayTransition, - function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; @@ -358,20 +353,20 @@ svgZoom.translateBy( 50); svgZoom.translateBy( svgOverlayTransition, - function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; }, - function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; @@ -383,11 +378,11 @@ svgZoom.translateBy( svgZoom.scaleBy(svgOverlay, 3); // svgZoom.scaleBy(groupsSelection, 3); // fails, as groupSelection mismachtes DOM Element type and datum type -svgZoom.scaleBy(svgOverlay, function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; +svgZoom.scaleBy(svgOverlay, function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 3; @@ -396,11 +391,11 @@ svgZoom.scaleBy(svgOverlay, function (datum, index, groups) { svgZoom.scaleBy(svgOverlayTransition, 3); // svgZoom.scaleBy(groupsTransition, 3); // fails, as groupTransition mismachtes DOM Element type and datum type -svgZoom.scaleBy(svgOverlayTransition, function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; +svgZoom.scaleBy(svgOverlayTransition, function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 3; @@ -412,11 +407,11 @@ svgZoom.scaleBy(svgOverlayTransition, function (datum, index, groups) { svgZoom.scaleTo(svgOverlay, 3); // svgZoom.scaleBy(groupsSelection, 3); // fails, as groupSelection mismachtes DOM Element type and datum type -svgZoom.scaleTo(svgOverlay, function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; +svgZoom.scaleTo(svgOverlay, function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 3; @@ -425,11 +420,11 @@ svgZoom.scaleTo(svgOverlay, function (datum, index, groups) { svgZoom.scaleTo(svgOverlayTransition, 3); // svgZoom.scaleBy(groupsTransition, 3); // fails, as groupTransition mismachtes DOM Element type and datum type -svgZoom.scaleTo(svgOverlayTransition, function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; +svgZoom.scaleTo(svgOverlayTransition, function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; @@ -439,12 +434,12 @@ svgZoom.scaleTo(svgOverlayTransition, function (datum, index, groups) { // Test Zoom Event Interface // -------------------------------------------------------------------------- -let e: d3Zoom.D3ZoomEvent = event; // mock assignment +const e: d3Zoom.D3ZoomEvent = event; // mock assignment -let target: d3Zoom.ZoomBehavior = e.target; -let type: 'start' | 'zoom' | 'end' | string = e.type; -let zoomTransform: d3Zoom.ZoomTransform = e.transform; -let sourceEvent: any = e.sourceEvent; +const target: d3Zoom.ZoomBehavior = e.target; +const type: 'start' | 'zoom' | 'end' | string = e.type; +const zoomTransform: d3Zoom.ZoomTransform = e.transform; +const sourceEvent: any = e.sourceEvent; // -------------------------------------------------------------------------- // Test Zoom Transforms @@ -458,17 +453,17 @@ zTransform = d3Zoom.zoomTransform(canvas.node()!); // Test ZoomTransform ------------------------------------------------------- -let x: number = zTransform.x; -let y: number = zTransform.y; -let k: number = zTransform.k; +const x: number = zTransform.x; +const y: number = zTransform.y; +const k: number = zTransform.k; -let transformedPoint: [number, number] = zTransform.apply([15, 20]); -let transformedX: number = zTransform.applyX(15); -let transformedY: number = zTransform.applyY(20); +const transformedPoint: [number, number] = zTransform.apply([15, 20]); +const transformedX: number = zTransform.applyX(15); +const transformedY: number = zTransform.applyY(20); -let invertedPoint: [number, number] = zTransform.invert([150, 240]); -let invertedX: number = zTransform.invertX(150); -let invertedY: number = zTransform.invertY(240); +const invertedPoint: [number, number] = zTransform.invert([150, 240]); +const invertedX: number = zTransform.invertX(150); +const invertedY: number = zTransform.invertY(240); // TODO: reScaleX, reScaleY @@ -477,7 +472,7 @@ let linearScale: ScaleLinear = scaleLinear(); linearScale = zTransform.rescaleX(linearScale); linearScale = zTransform.rescaleY(linearScale); -let transformation: string = zTransform.toString(); +const transformation: string = zTransform.toString(); zTransform = zTransform.translate(50, 40); diff --git a/d3-zoom/index.d.ts b/d3-zoom/index.d.ts index 9e0d2b72ec..87a55e9b2a 100644 --- a/d3-zoom/index.d.ts +++ b/d3-zoom/index.d.ts @@ -577,10 +577,12 @@ export interface D3ZoomEvent = d3.selection(); +const d: d3.Selection = d3.selection(); diff --git a/d3/tslint.json b/d3/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/d3/tslint.json +++ b/d3/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/dagre-d3/tslint.json b/dagre-d3/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/dagre-d3/tslint.json +++ b/dagre-d3/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/dagre/dagre-tests.ts b/dagre/dagre-tests.ts index d8004fa3da..2855055451 100644 --- a/dagre/dagre-tests.ts +++ b/dagre/dagre-tests.ts @@ -1,7 +1,7 @@ namespace DagreTests { const gDagre = new dagre.graphlib.Graph(); gDagre.setGraph({}) - .setDefaultEdgeLabel(function(){ return ; }) + .setDefaultEdgeLabel(() => {}) .setNode("a", {}) .setEdge("b", "c") .setEdge("c", "d", {class: "class"}); diff --git a/dagre/tslint.json b/dagre/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/dagre/tslint.json +++ b/dagre/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/datatables-buttons/datatables-buttons-tests.ts b/datatables.net-buttons/datatables.net-buttons-tests.ts similarity index 95% rename from datatables-buttons/datatables-buttons-tests.ts rename to datatables.net-buttons/datatables.net-buttons-tests.ts index 52a21db894..2dcdd26ff4 100644 --- a/datatables-buttons/datatables-buttons-tests.ts +++ b/datatables.net-buttons/datatables.net-buttons-tests.ts @@ -1,5 +1,5 @@ /// -/// +/// $(document).ready(function () { diff --git a/datatables-buttons/index.d.ts b/datatables.net-buttons/index.d.ts similarity index 98% rename from datatables-buttons/index.d.ts rename to datatables.net-buttons/index.d.ts index 2ce52d8483..b4ed4b0eb5 100644 --- a/datatables-buttons/index.d.ts +++ b/datatables.net-buttons/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// +/// declare namespace DataTables { export interface Settings { diff --git a/datatables-buttons/tsconfig.json b/datatables.net-buttons/tsconfig.json similarity index 91% rename from datatables-buttons/tsconfig.json rename to datatables.net-buttons/tsconfig.json index 0793cd2eb3..5e407ab2d8 100644 --- a/datatables-buttons/tsconfig.json +++ b/datatables.net-buttons/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "datatables-buttons-tests.ts" + "datatables.net-buttons-tests.ts" ] } \ No newline at end of file diff --git a/datatables.net-fixedheader/datatables.net-fixedheader-tests.ts b/datatables.net-fixedheader/datatables.net-fixedheader-tests.ts index 8b3b2ab70f..949bca825c 100644 --- a/datatables.net-fixedheader/datatables.net-fixedheader-tests.ts +++ b/datatables.net-fixedheader/datatables.net-fixedheader-tests.ts @@ -1,8 +1,7 @@ /// -/// - -$(document).ready(function() { +/// +$(document).ready(() => { var config: DataTables.Settings = { // FixedHeader extension options fixedHeader: { diff --git a/datatables.net-fixedheader/index.d.ts b/datatables.net-fixedheader/index.d.ts index e72360f933..caf3987d35 100644 --- a/datatables.net-fixedheader/index.d.ts +++ b/datatables.net-fixedheader/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Jared Szechy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// +/// declare namespace DataTables { export interface Settings { diff --git a/datatables.net-select/datatables.net-select-tests.ts b/datatables.net-select/datatables.net-select-tests.ts index 02c3249cf7..aa1851931c 100644 --- a/datatables.net-select/datatables.net-select-tests.ts +++ b/datatables.net-select/datatables.net-select-tests.ts @@ -1,8 +1,7 @@ /// -/// - -$(document).ready(function() { +/// +$(document).ready(() => { var config: DataTables.Settings = { // Select extension options select: { diff --git a/datatables.net-select/index.d.ts b/datatables.net-select/index.d.ts index 1365ab991e..96529a10c1 100644 --- a/datatables.net-select/index.d.ts +++ b/datatables.net-select/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Jared Szechy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// +/// declare namespace DataTables { export interface Settings { diff --git a/jquery.datatables/jquery.datatables-tests.ts b/datatables.net/datatables.net-tests.ts similarity index 98% rename from jquery.datatables/jquery.datatables-tests.ts rename to datatables.net/datatables.net-tests.ts index 1bf6e26593..0134581ee1 100644 --- a/jquery.datatables/jquery.datatables-tests.ts +++ b/datatables.net/datatables.net-tests.ts @@ -43,10 +43,17 @@ $(document).ready(function () { sort: "asc" }; - var colDataFunc: DataTables.FunctionColumnData = function (row, type, set, meta) { + var colDataFunc: DataTables.FunctionColumnData = (row: any, type: 'set' | 'display' | 'sort' | 'filter' | 'type', set: any, meta: DataTables.CellMetaSettings) => { meta.col; meta.row; meta.settings; + switch (type) { + case 'set': + row.value = set; + return; + default: + return row.value; + } }; var colRenderObject: DataTables.ObjectColumnRender = { @@ -276,7 +283,7 @@ $(document).ready(function () { bScrollbarLeft: true, bScrollOversize: true } - + //#endregion //#region "Init" @@ -901,7 +908,7 @@ $(document).ready(function () { //#region "Methods-Static" - // Variable is a stand-in for $.fn.dataTable. See extension of JQueryStatic at the top of jquery.dataTables.d.ts. + // Variable is a stand-in for $.fn.dataTable. See extension of JQueryStatic at the top of index.d.ts. var staticFn: DataTables.StaticFunctions; // With boolean parameter type, always returns DataTables.DataTable[]. diff --git a/jquery.datatables/index.d.ts b/datatables.net/index.d.ts similarity index 99% rename from jquery.datatables/index.d.ts rename to datatables.net/index.d.ts index 5d1bbd50c9..2640dbabe6 100644 --- a/jquery.datatables/index.d.ts +++ b/datatables.net/index.d.ts @@ -1587,7 +1587,8 @@ declare namespace DataTables { } interface FunctionColumnData { - (row: any, t: string, s: any, meta: CellMetaSettings): void; + (row: any, t: 'set', s: any, meta: CellMetaSettings): void; + (row: any, t: 'display' | 'sort' | 'filter' | 'type', s: undefined, meta: CellMetaSettings): any; } interface ObjectColumnData { diff --git a/jquery.datatables/tsconfig.json b/datatables.net/tsconfig.json similarity index 92% rename from jquery.datatables/tsconfig.json rename to datatables.net/tsconfig.json index 0831b7cc76..b48881c33b 100644 --- a/jquery.datatables/tsconfig.json +++ b/datatables.net/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "jquery.datatables-tests.ts" + "datatables.net-tests.ts" ] } \ No newline at end of file diff --git a/dc/dc-tests.ts b/dc/dc-tests.ts index 9d2688fdf0..643594276d 100644 --- a/dc/dc-tests.ts +++ b/dc/dc-tests.ts @@ -180,6 +180,8 @@ d3.json("data/yelp_test_set_business.json", (yelp_data:IYelpData[]) => { .xAxis() .tickFormat((v: string) => v); + lineChart.legend(dc.legend().x(200).y(10).itemHeight(13).gap(5)); + rowChart .width(340) .height(850) diff --git a/dc/index.d.ts b/dc/index.d.ts index e7be4f86aa..9f9d7d3a57 100644 --- a/dc/index.d.ts +++ b/dc/index.d.ts @@ -111,14 +111,14 @@ declare namespace dc { } export interface Legend { - x: IGetSet; - y: IGetSet; - gap: IGetSet; - itemHeight: IGetSet; - horizontal: IGetSet; - legendWidth: IGetSet; - itemWidth: IGetSet; - autoItemWidth: IGetSet; + x: IGetSet; + y: IGetSet; + gap: IGetSet; + itemHeight: IGetSet; + horizontal: IGetSet; + legendWidth: IGetSet; + itemWidth: IGetSet; + autoItemWidth: IGetSet; render: () => void; } diff --git a/deepmerge/deepmerge-tests.ts b/deepmerge/deepmerge-tests.ts index 7854f7adf1..4106de1275 100644 --- a/deepmerge/deepmerge-tests.ts +++ b/deepmerge/deepmerge-tests.ts @@ -1,13 +1,13 @@ import * as deepmerge from "deepmerge"; const x = { foo: { bar: 3 }, - array: [ { does: 'work', too: [ 1, 2, 3 ] } ] } + array: [ { does: 'work', too: [ 1, 2, 3 ] } ] }; const y = { foo: { baz: 4 }, quux: 5, - array: [ { does: 'work', too: [ 4, 5, 6 ] }, { really: 'yes' } ] } + array: [ { does: 'work', too: [ 4, 5, 6 ] }, { really: 'yes' } ] }; const expected = { foo: { bar: 3, baz: 4 }, array: [ { does: 'work', too: [ 1, 2, 3, 4, 5, 6 ] }, { really: 'yes' } ], - quux: 5 } + quux: 5 }; -const result = deepmerge(x, y); \ No newline at end of file +const result = deepmerge(x, y); \ No newline at end of file diff --git a/del/tslint.json b/del/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/del/tslint.json +++ b/del/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/discontinuous-range/discontinuous-range-tests.ts b/discontinuous-range/discontinuous-range-tests.ts index 9f93b0a061..8b31d11b11 100644 --- a/discontinuous-range/discontinuous-range-tests.ts +++ b/discontinuous-range/discontinuous-range-tests.ts @@ -5,12 +5,12 @@ const rangeOne: DiscontinuousRange = new DiscontinuousRange(3); const rangeTwo: DiscontinuousRange = new DiscontinuousRange(3, 5); // add -const resultOne: DiscontinuousRange = rangeOne.add(6,10); +const resultOne: DiscontinuousRange = rangeOne.add(6, 10); const resultTwo: DiscontinuousRange = rangeTwo.add(11); const resultThree: DiscontinuousRange = rangeOne.add(rangeTwo); // subtract -const resultFour: DiscontinuousRange = rangeOne.subtract(7,8); +const resultFour: DiscontinuousRange = rangeOne.subtract(7, 8); const resultFive: DiscontinuousRange = rangeTwo.subtract(11); const resultSix: DiscontinuousRange = rangeOne.subtract(rangeTwo); diff --git a/dockerode/dockerode-tests.ts b/dockerode/dockerode-tests.ts index e1533e91f7..3bd1c30097 100644 --- a/dockerode/dockerode-tests.ts +++ b/dockerode/dockerode-tests.ts @@ -16,7 +16,7 @@ const docker5 = new Docker({ }); const docker6 = new Docker({ - protocol: 'https', //you can enforce a protocol + protocol: 'https', // you can enforce a protocol host: '192.168.1.10', port: process.env.DOCKER_PORT || 2375, ca: 'ca', diff --git a/dockerode/index.d.ts b/dockerode/index.d.ts index c317d5d32e..968199436a 100644 --- a/dockerode/index.d.ts +++ b/dockerode/index.d.ts @@ -184,6 +184,7 @@ declare namespace Dockerode { Created: number; Ports: Port[]; Labels: { [label: string]: string }; + State: string; Status: string; HostConfig: { NetworkMode: string; diff --git a/dockerode/tsconfig.json b/dockerode/tsconfig.json index a077f02e3c..2a83a71968 100644 --- a/dockerode/tsconfig.json +++ b/dockerode/tsconfig.json @@ -1,20 +1,22 @@ { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "dockerode-tests.ts" - ] + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dockerode-tests.ts" + ] } \ No newline at end of file diff --git a/dockerode/tslint.json b/dockerode/tslint.json index 785a601162..377cc837d4 100644 --- a/dockerode/tslint.json +++ b/dockerode/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/dookie/dookie-tests.ts b/dookie/dookie-tests.ts index d2fa907669..44cd6ec7ac 100644 --- a/dookie/dookie-tests.ts +++ b/dookie/dookie-tests.ts @@ -1,8 +1,8 @@ import {push, pull} from './index'; -(async ()=>{ +(async () => { - await push('mongodb://localhost:27017/test', {test:[{ok:1},{ok:2}]}); + await push('mongodb://localhost:27017/test', {test: [{ok: 1}, {ok: 2}]}); })(); diff --git a/dookie/tsconfig.json b/dookie/tsconfig.json index d795a39145..0c926cf7ff 100644 --- a/dookie/tsconfig.json +++ b/dookie/tsconfig.json @@ -1,6 +1,9 @@ { "compilerOptions": { "module": "commonjs", + "lib": [ + "es6" + ], "target": "es6", "noImplicitAny": true, "noImplicitThis": true, @@ -17,4 +20,4 @@ "index.d.ts", "dookie-tests.ts" ] -} +} \ No newline at end of file diff --git a/dot/tslint.json b/dot/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/dot/tslint.json +++ b/dot/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/dropkickjs/dropkickjs-tests.ts b/dropkickjs/dropkickjs-tests.ts index af46b43c02..206554da09 100644 --- a/dropkickjs/dropkickjs-tests.ts +++ b/dropkickjs/dropkickjs-tests.ts @@ -1,13 +1,11 @@ -/// - -//constructor +// constructor var constructorNoOptions = new Dropkick('#my-select'); var constructorNoOptions2 = new Dropkick(new HTMLSelectElement()); var constructorOptions = new Dropkick('#my-select', {}); var constructorOptions2 = new Dropkick(new HTMLSelectElement(), {}); -//options -var options : DropkickOptions = { +// options +var options: DropkickOptions = { disabled: true, form: new HTMLFormElement(), length: 1, @@ -21,12 +19,12 @@ var options : DropkickOptions = { close() { }, open() { }, initialize: () => { } -} +}; var withFullOptions = new Dropkick('#test', options); var dk = new Dropkick('#test'); -//fields (same as options) +// fields (same as options) var o1 = dk.disabled; var o2 = dk.form; var o3 = dk.length; @@ -37,7 +35,7 @@ var o7 = dk.selectedIndex; var o8 = dk.selectedOptions; var o9 = dk.value; -//methods +// methods dk.add('new'); dk.add(new HTMLSelectElement()); dk.add('new', 'old'); @@ -75,11 +73,11 @@ var node4 = dk.select(4, true); var node5 = dk.selectOne(4); var node6 = dk.selectOne(4, true); -//real life example +// real life example var fieldValue = ''; -var selectOptions : DropkickOptions = { +var selectOptions: DropkickOptions = { open(this: Dropkick) { - const optionsList = (this).data.elem.lastChild; //undocumented but useful data field + const optionsList = ( this).data.elem.lastChild; // undocumented but useful data field if (optionsList.scrollWidth > optionsList.offsetWidth) { optionsList.style.width = optionsList.scrollWidth + 25 + 'px'; } diff --git a/dropkickjs/tsconfig.json b/dropkickjs/tsconfig.json index e0699ecf5c..07855ffa97 100644 --- a/dropkickjs/tsconfig.json +++ b/dropkickjs/tsconfig.json @@ -1,7 +1,10 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6", + "dom" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, diff --git a/dropkickjs/tslint.json b/dropkickjs/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/dropkickjs/tslint.json +++ b/dropkickjs/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/duplexer2/duplexer2-tests.ts b/duplexer2/duplexer2-tests.ts index d611b69144..cfc945adb7 100644 --- a/duplexer2/duplexer2-tests.ts +++ b/duplexer2/duplexer2-tests.ts @@ -1,7 +1,7 @@ import stream = require("stream"); import duplexer2 = require("duplexer2"); -let writable = new stream.Writable({ objectMode: true }), +const writable = new stream.Writable({ objectMode: true }), readable = new stream.Readable({ objectMode: true }); writable.once("finish", () => { @@ -10,7 +10,7 @@ writable.once("finish", () => { }, 500); }); -let duplex = duplexer2(writable, readable); +const duplex = duplexer2(writable, readable); duplex.on("data", (e: any) => { console.log("got data", JSON.stringify(e)); diff --git a/easeljs/index.d.ts b/easeljs/index.d.ts index a5916a56f2..d47f631728 100644 --- a/easeljs/index.d.ts +++ b/easeljs/index.d.ts @@ -735,6 +735,7 @@ declare namespace createjs { intersection(rect: Rectangle): Rectangle; intersects(rect: Rectangle): boolean; isEmpty(): boolean; + pad(top: number, left: number, bottom: number, right: number): Rectangle; setValues(x?: number, y?: number, width?: number, height?: number): Rectangle; toString(): string; union(rect: Rectangle): Rectangle; diff --git a/ecurve/ecurve-tests.ts b/ecurve/ecurve-tests.ts index 1c73a7e648..c2214c6905 100644 --- a/ecurve/ecurve-tests.ts +++ b/ecurve/ecurve-tests.ts @@ -7,49 +7,49 @@ import BigInteger = require('bigi'); import cs = require('coinstring'); -var ecparams = ecurve.getCurveByName('secp256k1') -console.log(ecparams.n.toString(16)) +var ecparams = ecurve.getCurveByName('secp256k1'); +console.log(ecparams.n.toString(16)); // => fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 -console.log(ecparams.G.getEncoded().toString('hex')) //getEncoded() returns type 'Buffer' instead of 'BigInteger' +console.log(ecparams.G.getEncoded().toString('hex')); // getEncoded() returns type 'Buffer' instead of 'BigInteger' // => 0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798 -console.log(ecparams.h.toString(16)) +console.log(ecparams.h.toString(16)); // => 1 -var privateKey = new Buffer("1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd", 'hex') +var privateKey = new Buffer("1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd", 'hex'); -var ecparams = ecurve.getCurveByName('secp256k1') -var curvePt = ecparams.G.multiply(BigInteger.fromBuffer(privateKey)) -var x = curvePt.affineX.toBuffer(32) -var y = curvePt.affineY.toBuffer(32) +var ecparams = ecurve.getCurveByName('secp256k1'); +var curvePt = ecparams.G.multiply(BigInteger.fromBuffer(privateKey)); +var x = curvePt.affineX.toBuffer(32); +var y = curvePt.affineY.toBuffer(32); -var publicKey = Buffer.concat([new Buffer([0x04]), x, y]) -console.log(publicKey.toString('hex')) +var publicKey = Buffer.concat([new Buffer([0x04]), x, y]); +console.log(publicKey.toString('hex')); // => 04d0988bfa799f7d7ef9ab3de97ef481cd0f75d2367ad456607647edde665d6f6fbdd594388756a7beaf73b4822bc22d36e9bda7db82df2b8b623673eefc0b7495 -//alternatively -publicKey = curvePt.getEncoded(false) //false forces uncompressed public key -console.log(publicKey.toString('hex')) +// alternatively +publicKey = curvePt.getEncoded(false); // false forces uncompressed public key +console.log(publicKey.toString('hex')); // => 04d0988bfa799f7d7ef9ab3de97ef481cd0f75d2367ad456607647edde665d6f6fbdd594388756a7beaf73b4822bc22d36e9bda7db82df2b8b623673eefc0b7495 -//want compressed? -publicKey = curvePt.getEncoded(true) //true forces compressed public key -console.log(publicKey.toString('hex')) +// want compressed? +publicKey = curvePt.getEncoded(true); // true forces compressed public key +console.log(publicKey.toString('hex')); // => 03d0988bfa799f7d7ef9ab3de97ef481cd0f75d2367ad456607647edde665d6f6f -var sha = crypto.createHash('sha256').update(publicKey).digest() -var pubkeyHash = crypto.createHash('rmd160').update(sha).digest() +var sha = crypto.createHash('sha256').update(publicKey).digest(); +var pubkeyHash = crypto.createHash('rmd160').update(sha).digest(); // pubkeyHash of compressed public key -console.log(pubkeyHash.toString('hex')) +console.log(pubkeyHash.toString('hex')); // => a1c2f92a9dacbd2991c3897724a93f338e44bdc1 // address of compressed public key -console.log(cs.encode(pubkeyHash, 0x0)) //<-- 0x0 is for public addresses +console.log(cs.encode(pubkeyHash, 0x0)); // <-- 0x0 is for public addresses // => 1FkKMsKNJqWSDvTvETqcCeHcUQQ64kSC6s -console.log(cs.encode(privateKey, 0x80)) //<--- 0x80 is for private addresses +console.log(cs.encode(privateKey, 0x80)); // <--- 0x80 is for private addresses // => 5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD -console.log(cs.encode(Buffer.concat([privateKey, new Buffer([0])]), 0x80)) // <-- compressed private address +console.log(cs.encode(Buffer.concat([privateKey, new Buffer([0])]), 0x80)); // <-- compressed private address // => KwomKti1X3tYJUUMb1TGSM2mrZk1wb1aHisUNHCQXTZq5aqzCxDY \ No newline at end of file diff --git a/electron/index.d.ts b/electron/index.d.ts index 448df1915f..0b98ae1944 100644 --- a/electron/index.d.ts +++ b/electron/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Electron v1.4.8 // Project: http://electron.atom.io/ -// Definitions by: jedmao , rhysd , Milan Burda , aliib +// Definitions by: jedmao , rhysd , Milan Burda , aliib , Daniel Perez Alvarez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -398,6 +398,20 @@ declare namespace Electron { * This method can only be called before app is ready. */ disableHardwareAcceleration(): void; + /** + * Sets the counter badge for current app. Setting the count to 0 will hide the badge. + * + * @returns True when the call succeeded, otherwise returns false. + * + * Note: This API is only available on macOS and Linux. + */ + setBadgeCount(count: number): boolean; + /** + * @returns The current value displayed in the counter badge. + * + * Note: This API is only available on macOS and Linux. + */ + getBadgeCount(): number; /** * @returns whether current desktop environment is Unity launcher. (Linux) * @@ -505,20 +519,6 @@ declare namespace Electron { * Note: This API is only available on macOS. */ getBadge(): string; - /** - * Sets the counter badge for current app. Setting the count to 0 will hide the badge. - * - * @returns True when the call succeeded, otherwise returns false. - * - * Note: This API is only available on macOS and Linux. - */ - setBadgeCount(count: number): boolean; - /** - * @returns The current value displayed in the counter badge. - * - * Note: This API is only available on macOS and Linux. - */ - getBadgeCount(): number; /** * Hides the dock icon. * diff --git a/electron/test/main.ts b/electron/test/main.ts index 9912b62eea..276a15d851 100644 --- a/electron/test/main.ts +++ b/electron/test/main.ts @@ -232,7 +232,8 @@ app.dock.setBadge('foo'); var id = app.dock.bounce('informational'); app.dock.cancelBounce(id); app.dock.setIcon('/path/to/icon.png'); -app.dock.setBadgeCount(app.dock.getBadgeCount() + 1); + +app.setBadgeCount(app.getBadgeCount() + 1); app.setUserTasks([ { diff --git a/ember/ember-tests.ts b/ember/ember-tests.ts index dda0e157c4..91e1f61f6f 100644 --- a/ember/ember-tests.ts +++ b/ember/ember-tests.ts @@ -1,4 +1,4 @@ -var App : any; +var App: any; App = Em.Application.create(); @@ -12,7 +12,7 @@ App.country.get('presidentName'); App.president = Em.Object.create({ firstName: 'Barack', lastName: 'Obama', - fullName: function () { + fullName: function() { return this.get('firstName') + ' ' + this.get('lastName'); }.property() }); @@ -33,7 +33,7 @@ declare class MyPerson2 extends Em.Object { } var tom = Person1.create({ name: 'Tom Dale', - helloWorld: function() { + helloWorld() { this.say('Hi my name is ' + this.get('name')); } }); @@ -106,14 +106,13 @@ App.userController = Em.Object.create({ }) }); -Handlebars.registerHelper('highlight', function(property: string, options: any) { - return new Handlebars.SafeString('' + "some value" + ''); -}); +Handlebars.registerHelper('highlight', (property: string, options: any) => + new Handlebars.SafeString('' + "some value" + '')); var coolView = App.CoolView.create(); var Person2 = Em.Object.extend({ - sayHello: function() { + sayHello() { console.log('Hello from ' + this.get('name')); } }); @@ -146,7 +145,7 @@ people2.everyProperty('isHappy', true); people2.someProperty('isHappy', true); // Examples taken from http://emberjs.com/api/classes/Em.RSVP.Promise.html -var promise = new Em.RSVP.Promise(function(resolve: Function, reject: Function) { +var promise = new Em.RSVP.Promise((resolve: Function, reject: Function) => { // on success resolve('ok!'); @@ -154,9 +153,9 @@ var promise = new Em.RSVP.Promise(function(resolve: Function, re reject('no-k!'); }); -promise.then(function(value: any) { +promise.then((value: any) => { // on fulfillment -}, function(reason: any) { +}, (reason: any) => { // on rejection }); diff --git a/ember/tslint.json b/ember/tslint.json index e2cf959984..fcd9410184 100644 --- a/ember/tslint.json +++ b/ember/tslint.json @@ -3,6 +3,7 @@ "rules": { // Heavy use of Function type in this older package. "forbidden-types": false, + "no-misused-new": false, // not sure what this means "no-single-declare-module": false } diff --git a/env-to-object/env-to-object-tests.ts b/env-to-object/env-to-object-tests.ts index e2c1fd4e53..7bc1db3727 100644 --- a/env-to-object/env-to-object-tests.ts +++ b/env-to-object/env-to-object-tests.ts @@ -1,34 +1,34 @@ import * as envToObject from 'env-to-object'; const map = { - 'NODE_ENV': { - 'keypath': 'env', - 'type': 'string' + NODE_ENV: { + keypath: 'env', + type: 'string' }, - 'PORT': { - 'keypath': 'server.port', - 'type': 'number' + PORT: { + keypath: 'server.port', + type: 'number' }, - 'SSL': { - 'keypath': 'server.ssl', - 'type': 'boolean' + SSL: { + keypath: 'server.ssl', + type: 'boolean' }, - 'LOG_LEVEL': { - 'keypath': 'logger.level', - 'type': 'string' + LOG_LEVEL: { + keypath: 'logger.level', + type: 'string' }, - 'INT': { - 'keypath': 'int', - 'type': 'integer', - 'radix': '2' + INT: { + keypath: 'int', + type: 'integer', + radix: '2' } }; -const result1:any = envToObject(map); -const result2:any = envToObject(map, { +const result1: any = envToObject(map); +const result2: any = envToObject(map, { parsers: { 'my-custom-type': (str: string, opts: any) => { - let foo: any = JSON.parse(str); + const foo: any = JSON.parse(str); return foo; } } diff --git a/env-to-object/tsconfig.json b/env-to-object/tsconfig.json index 68efe0c7ca..316a2acdf6 100644 --- a/env-to-object/tsconfig.json +++ b/env-to-object/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "env-to-object-tests.ts" ] -} +} \ No newline at end of file diff --git a/enzyme/index.d.ts b/enzyme/index.d.ts index 66c86d1166..fc498ca78a 100644 --- a/enzyme/index.d.ts +++ b/enzyme/index.d.ts @@ -1,6 +1,10 @@ // Type definitions for Enzyme 2.7 // Project: https://github.com/airbnb/enzyme -// Definitions by: Marian Palkus , Cap3 , Ivo Stratev , Tom Crockett , jwbay +// Definitions by: Marian Palkus +// Cap3 +// Ivo Stratev +// Tom Crockett +// jwbay // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -435,7 +439,8 @@ export interface ReactWrapper extends CommonWrapper { * * The method is intentionally not "fluent" (in that it doesn't return this) because you should not be doing anything with this wrapper after this method is called. * - * Using the attachTo is not generally recommended unless it is absolutely necessary to test something. It is your responsibility to clean up after yourself at the end of the test if you do decide to use it, though. + * Using the attachTo is not generally recommended unless it is absolutely necessary to test something. + * It is your responsibility to clean up after yourself at the end of the test if you do decide to use it, though. */ detach(): void; diff --git a/enzyme/tslint.json b/enzyme/tslint.json index f9e30021f4..377cc837d4 100644 --- a/enzyme/tslint.json +++ b/enzyme/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/es6-weak-map/es6-weak-map-tests.ts b/es6-weak-map/es6-weak-map-tests.ts index aec03c03d1..68f5ea7f43 100644 --- a/es6-weak-map/es6-weak-map-tests.ts +++ b/es6-weak-map/es6-weak-map-tests.ts @@ -2,7 +2,7 @@ import WeakMap = require('es6-weak-map'); new WeakMap<{}, string>(); -var tuples: [number, string][] = [ [0, 'foo'], [1, 'bar'] ]; +var tuples: Array<[number, string]> = [ [0, 'foo'], [1, 'bar'] ]; new WeakMap(tuples); var map = new WeakMap<{}, string>(); diff --git a/expect/expect-tests.ts b/expect/expect-tests.ts index 37ecefb566..3e08e0d747 100644 --- a/expect/expect-tests.ts +++ b/expect/expect-tests.ts @@ -1,12 +1,11 @@ /// -import {Expectation, Extension, Spy, createSpy, isSpy, assert, spyOn, extend, restoreSpies} - from 'expect'; +import {Expectation, Extension, Spy, createSpy, isSpy, assert, spyOn, extend, restoreSpies} from 'expect'; import * as expect from 'expect'; -describe('chaining assertions', function () { - it('should allow chaining for array-like applications', function () { +describe('chaining assertions', () => { + it('should allow chaining for array-like applications', () => { expect([ 1, 2, 'foo', 3 ]) .toExist() .toBeAn(Array) @@ -14,7 +13,7 @@ describe('chaining assertions', function () { .toExclude('bar'); }); - it('should allow chaining for number checking', function () { + it('should allow chaining for number checking', () => { expect(3.14) .toExist() .toBeLessThan(4.2) @@ -24,16 +23,16 @@ describe('chaining assertions', function () { }); }); -describe('createSpy', function () { - describe('when given a function', function () { - it('returns a spy function', function () { +describe('createSpy', () => { + describe('when given a function', () => { + it('returns a spy function', () => { const spy = createSpy(() => { return; }); expect(spy).toBeA(Function); }); }); }); -describe('A spy', function () { +describe('A spy', () => { let targetContext: any, targetArguments: any; const target = { method() { @@ -49,7 +48,7 @@ describe('A spy', function () { targetContext = targetArguments = null; }); - it('is a spy', function () { + it('is a spy', () => { expect(isSpy(spy)).toBe(true); }); @@ -59,15 +58,15 @@ describe('A spy', function () { expect(createSpy((a, b, c) => a * b * c).length).toBe(3); }); - it('has a destroy method', function () { + it('has a destroy method', () => { expect(spy.destroy).toBeA(Function); }); - it('has a restore method', function () { + it('has a restore method', () => { expect(spy.restore).toBeA(Function); }); - it('has a reset method', function () { + it('has a reset method', () => { expect(spy.reset).toBeA(Function); }); @@ -78,90 +77,90 @@ describe('A spy', function () { expect(spy.calls.length).toEqual(0); }); - it('knows how many times it has been called', function () { + it('knows how many times it has been called', () => { spy(); spy(); expect(spy.calls.length).toEqual(2); }); - it('knows the arguments it was called with', function () { + it('knows the arguments it was called with', () => { spy(1, 2, 3); expect(spy).toHaveBeenCalledWith(1, 2, 3); }); - describe('that calls some other function', function () { + describe('that calls some other function', () => { let otherContext: any, otherArguments: any; function otherFn() { otherContext = this; otherArguments = Array.prototype.slice.call(arguments, 0); - }; + } - beforeEach(function () { + beforeEach(() => { spy.andCall(otherFn); otherContext = otherArguments = null; }); - it('calls that function', function () { + it('calls that function', () => { spy(); expect(otherContext).toNotBe(null); }); - it('uses the correct context', function () { + it('uses the correct context', () => { const context = {}; spy.call(context); expect(otherContext).toBe(context); }); - it('passes the arguments through', function () { + it('passes the arguments through', () => { spy(1, 2, 3); expect(otherArguments).toEqual([ 1, 2, 3 ]); }); }); - describe('that calls through', function () { - beforeEach(function () { + describe('that calls through', () => { + beforeEach(() => { spy.andCallThrough(); }); - it('calls the original function', function () { + it('calls the original function', () => { spy(); expect(targetContext).toNotBe(null); }); - it('uses the correct context', function () { + it('uses the correct context', () => { const context = {}; spy.call(context); expect(targetContext).toBe(context); }); - it('passes the arguments through', function () { + it('passes the arguments through', () => { spy(1, 2, 3); expect(targetArguments).toEqual([ 1, 2, 3 ]); }); }); - describe('with a thrown value', function () { - beforeEach(function () { + describe('with a thrown value', () => { + beforeEach(() => { spy.andThrow('hello'); }); - it('throws the correct value', function () { + it('throws the correct value', () => { expect(spy).toThrow('hello'); }); }); - describe('with a return value', function () { - beforeEach(function () { + describe('with a return value', () => { + beforeEach(() => { spy.andReturn('hello'); }); - it('returns the correct value', function () { + it('returns the correct value', () => { expect(spy()).toEqual('hello'); }); }); }); -describe('expect.extend', function () { +describe('expect.extend', () => { const ColorAssertions: Extension = { toBeAColor() { assert( @@ -174,16 +173,16 @@ describe('expect.extend', function () { let assertSpy: Spy<{}>; - beforeEach(function () { + beforeEach(() => { extend(ColorAssertions); assertSpy = spyOn(expect, 'assert'); }); - afterEach(function () { + afterEach(() => { assertSpy.restore(); }); - it('works', function () { + it('works', () => { interface ColorExpectation extends Expectation { toBeAColor(): Expectation; } @@ -192,42 +191,42 @@ describe('expect.extend', function () { }); }); -describe('restoreSpies', function () { - describe('with one spy', function () { - const original = function () { return; }; +describe('restoreSpies', () => { + describe('with one spy', () => { + const original = () => { return; }; const target = { method: original }; - beforeEach(function () { + beforeEach(() => { spyOn(target, 'method'); }); - it('works with spyOn()', function () { + it('works with spyOn()', () => { expect(target.method).toNotEqual(original); restoreSpies(); expect(target.method).toEqual(original); }); - it('is idempotent', function () { + it('is idempotent', () => { expect(target.method).toNotEqual(original); restoreSpies(); restoreSpies(); expect(target.method).toEqual(original); }); - it('can work even on createSpy()', function () { + it('can work even on createSpy()', () => { createSpy(original); restoreSpies(); }); }); - describe('with multiple spies', function () { - const originals = [ function () { return; }, function () { return; } ]; + describe('with multiple spies', () => { + const originals = [ () => { return; }, () => { return; } ]; const targets = [ { method: originals[0] }, { method: originals[1] } ]; - it('still works', function () { + it('still works', () => { spyOn(targets[0], 'method'); spyOn(targets[1], 'method'); @@ -242,119 +241,119 @@ describe('restoreSpies', function () { }); }); -describe('A function that was spied on', function () { +describe('A function that was spied on', () => { const video = { play(...args: any[]) { return; } }; let spy: Spy<{}>; - beforeEach(function () { + beforeEach(() => { spy = spyOn(video, 'play'); video.play('some', 'args'); }); - it('tracks the number of calls', function () { + it('tracks the number of calls', () => { expect(spy.calls.length).toEqual(1); }); - it('tracks the context that was used', function () { + it('tracks the context that was used', () => { expect(spy.calls[0].context).toBe(video); }); - it('tracks the arguments that were used', function () { + it('tracks the arguments that were used', () => { expect(spy.calls[0].arguments).toEqual([ 'some', 'args' ]); }); - it('was called', function () { + it('was called', () => { expect(spy).toHaveBeenCalled(); }); - it('was called with the correct args', function () { + it('was called with the correct args', () => { expect(spy).toHaveBeenCalledWith('some', 'args'); }); - it('can be restored', function () { + it('can be restored', () => { expect(video.play).toEqual(spy); spy.restore(); expect(video.play).toNotEqual(spy); }); }); -describe('A function that was spied on but not called', function () { +describe('A function that was spied on but not called', () => { const video = { - play () { return; } + play() { return; } }; let spy: Spy<{}>; - beforeEach(function () { + beforeEach(() => { spy = spyOn(video, 'play'); }); - it('number of calls to be zero', function () { + it('number of calls to be zero', () => { expect(spy.calls.length).toEqual(0); }); - it('was not called', function () { + it('was not called', () => { expect(spy).toNotHaveBeenCalled(); }); }); -describe('toBeA', function () { - it('requires the value to be a function or string', function () { - expect(function () { +describe('toBeA', () => { + it('requires the value to be a function or string', () => { + expect(() => { expect('actual').toBeA(4); }).toThrow(/must be a function or a string/); }); - it('does not throw when the actual value is an instanceof the constructor', function () { - expect(function () { + it('does not throw when the actual value is an instanceof the constructor', () => { + expect(() => { expect(new Expectation('foo')).toBeA(Expectation); }).toNotThrow(); }); - it('throws when the actual value is not an instanceof the constructor', function () { - expect(function () { + it('throws when the actual value is not an instanceof the constructor', () => { + expect(() => { expect('actual').toBeA(Expectation); }).toThrow(/to be/); }); - it('does not throw when the expected value is the typeof the actual value', function () { - expect(function () { + it('does not throw when the expected value is the typeof the actual value', () => { + expect(() => { expect(4).toBeA('number'); expect(NaN).toBeA('number'); // hahaha }).toNotThrow(); }); - it('throws when the expected value is not the typeof the actual value', function () { - expect(function () { + it('throws when the expected value is not the typeof the actual value', () => { + expect(() => { expect('actual').toBeA('number'); }).toThrow(/to be/); }); - it('does not throw when the actual value is an array', function () { - expect(function () { + it('does not throw when the actual value is an array', () => { + expect(() => { expect([]).toBeAn('array'); }).toNotThrow(); }); - it('throws when the actual value is not an array', function () { - expect(function () { + it('throws when the actual value is not an array', () => { + expect(() => { expect('actual').toBeAn('array'); }).toThrow(/to be/); }); }); -describe('toBeGreaterThan', function () { - it('does not throw when the actual value is greater than the expected value', function () { - expect(function () { +describe('toBeGreaterThan', () => { + it('does not throw when the actual value is greater than the expected value', () => { + expect(() => { expect(3).toBeGreaterThan(2); }).toNotThrow(); }); - it('throws when the actual value is not greater than the expected value', function () { - expect(function () { + it('throws when the actual value is not greater than the expected value', () => { + expect(() => { expect(2).toBeGreaterThan(3); }).toThrow(/to be greater than/); }); @@ -380,15 +379,15 @@ describe('toBeGreaterThanOrEqualTo', () => { }); }); -describe('toBeLessThan', function () { - it('does not throw when the actual value is less than the expected value', function () { - expect(function () { +describe('toBeLessThan', () => { + it('does not throw when the actual value is less than the expected value', () => { + expect(() => { expect(2).toBeLessThan(3); }).toNotThrow(); }); - it('throws when the actual value is not less than the expected value', function () { - expect(function () { + it('throws when the actual value is not less than the expected value', () => { + expect(() => { expect(3).toBeLessThan(2); }).toThrow(/to be less than/); }); @@ -414,47 +413,47 @@ describe('toBeLessThanOrEqualTo', () => { }); }); -describe('toBeTruthy', function () { - it('does not throw on truthy actual values', function () { - expect(function () { +describe('toBeTruthy', () => { + it('does not throw on truthy actual values', () => { + expect(() => { expect(1).toBeTruthy(); expect({ hello: 'world' }).toBeTruthy(); expect([ 1, 2, 3 ]).toBeTruthy(); }).toNotThrow(); }); - it('throws on falsy actual values', function () { - expect(function () { + it('throws on falsy actual values', () => { + expect(() => { expect(0).toBeTruthy(); }).toThrow(); - expect(function () { + expect(() => { expect(null).toBeTruthy(); }).toThrow(); - expect(function () { + expect(() => { expect(undefined).toBeTruthy(); }).toThrow(); }); }); -describe('toBeFalsy', function () { - it('throws on truthy values', function () { - expect(function () { +describe('toBeFalsy', () => { + it('throws on truthy values', () => { + expect(() => { expect(42).toBeFalsy(); }).toThrow(); - expect(function () { + expect(() => { expect({ foo: 'bar' }).toBeFalsy(); }).toThrow(); - expect(function () { + expect(() => { expect([]).toBeFalsy(); }).toThrow(); }); - it('does not throw with falsy actual values', function () { - expect(function () { + it('does not throw with falsy actual values', () => { + expect(() => { expect(0).toBeFalsy(); expect(null).toBeFalsy(); expect(undefined).toBeFalsy(); @@ -462,20 +461,20 @@ describe('toBeFalsy', function () { }); }); -describe('toEqual', function () { - it('works', function () { - expect(function () { +describe('toEqual', () => { + it('works', () => { + expect(() => { expect('actual').toEqual('expected'); }).toThrow(/Expected 'actual' to equal 'expected'/); }); - it('works with objects that have the same keys in different order', function () { + it('works with objects that have the same keys in different order', () => { const a = { a: 'a', b: 'b', c: 'c' }; const b = { b: 'b', c: 'c', a: 'a' }; expect(a).toEqual(b); }); - it('shows diff', function () { + it('shows diff', () => { try { expect('actual').toEqual('expected'); } catch (err) { @@ -486,21 +485,21 @@ describe('toEqual', function () { }); }); -describe('toExclude', function () { - it('requires the actual value to be an array or string', function () { - expect(function () { +describe('toExclude', () => { + it('requires the actual value to be an array or string', () => { + expect(() => { expect(1).toExclude(2); }).toThrow(/must be an array or a string/); }); - it('does not throw when an array does not contain the expected value', function () { - expect(function () { + it('does not throw when an array does not contain the expected value', () => { + expect(() => { expect([ 1, 2, 3 ]).toExclude(4); }).toNotThrow(); }); - it('throws when an array contains the expected value', function () { - expect(function () { + it('throws when an array contains the expected value', () => { + expect(() => { expect([ 1, 2, 3 ]).toExclude(2); }).toThrow(/to exclude/); }); @@ -523,14 +522,14 @@ describe('toExclude', function () { }).toNotThrow(); }); - it('does not throw when an array does not contain the expected value', function () { - expect(function () { + it('does not throw when an array does not contain the expected value', () => { + expect(() => { expect('hello world').toExclude('goodbye'); }).toNotThrow(); }); - it('throws when a string contains the expected value', function () { - expect(function () { + it('throws when a string contains the expected value', () => { + expect(() => { expect('hello world').toExclude('hello'); }).toThrow(/to exclude/); }); @@ -592,47 +591,47 @@ describe('toExcludeKeys', () => { }); }); -describe('toExist', function () { - it('does not throw on truthy actual values', function () { - expect(function () { +describe('toExist', () => { + it('does not throw on truthy actual values', () => { + expect(() => { expect(1).toExist(); expect({ hello: 'world' }).toExist(); expect([ 1, 2, 3 ]).toExist(); }).toNotThrow(); }); - it('throws on falsy actual values', function () { - expect(function () { + it('throws on falsy actual values', () => { + expect(() => { expect(0).toExist(); }).toThrow(); - expect(function () { + expect(() => { expect(null).toExist(); }).toThrow(); - expect(function () { + expect(() => { expect(undefined).toExist(); }).toThrow(); }); }); -describe('toNotExist', function () { - it('throws on truthy values', function () { - expect(function () { +describe('toNotExist', () => { + it('throws on truthy values', () => { + expect(() => { expect(42).toNotExist(); }).toThrow(); - expect(function () { + expect(() => { expect({ foo: 'bar' }).toNotExist(); }).toThrow(); - expect(function () { + expect(() => { expect([]).toNotExist(); }).toThrow(); }); - it('does not throw with falsy actual values', function () { - expect(function () { + it('does not throw with falsy actual values', () => { + expect(() => { expect(0).toNotExist(); expect(null).toNotExist(); expect(undefined).toNotExist(); @@ -1037,11 +1036,11 @@ describe('toNotEqual', () => { expect(a).toNotEqual(b); }); - }; + } }); -describe('withArgs', function () { - const fn = function (arg1: any, arg2: any) { +describe('withArgs', () => { + const fn = (arg1: any, arg2: any) => { if (arg1 === 'first' && typeof arg2 === 'undefined') { throw new Error('first arg found'); } @@ -1050,20 +1049,20 @@ describe('withArgs', function () { } }; - it('invokes actual function with args', function () { - expect(function () { + it('invokes actual function with args', () => { + expect(() => { expect(fn).withArgs('first').toThrow(/first arg found/); }).toNotThrow(); }); - it('can be chained', function () { - expect(function () { + it('can be chained', () => { + expect(() => { expect(fn).withArgs('first').withArgs('second').toThrow(/both args found/); }).toNotThrow(); }); - it('throws when actual is not a function', function () { - expect(function () { + it('throws when actual is not a function', () => { + expect(() => { expect('not a function').withArgs('first'); }).toThrow(/must be a function/); }); diff --git a/express-mysql-session/tsconfig.json b/express-mysql-session/tsconfig.json index 5af8734c24..f897d59bc8 100644 --- a/express-mysql-session/tsconfig.json +++ b/express-mysql-session/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "express-mysql-session-tests.ts" ] -} +} \ No newline at end of file diff --git a/extract-zip/extract-zip-tests.ts b/extract-zip/extract-zip-tests.ts index 33b3a714af..b4c35224e7 100644 --- a/extract-zip/extract-zip-tests.ts +++ b/extract-zip/extract-zip-tests.ts @@ -1,7 +1,7 @@ import * as extract from 'extract-zip'; -let str = 'str'; -let num = 0; +const str = 'str'; +const num = 0; let options: extract.Options = { dir: str, diff --git a/fabric/fabric-tests.ts b/fabric/fabric-tests.ts index d0b4ef197b..923b29d896 100644 --- a/fabric/fabric-tests.ts +++ b/fabric/fabric-tests.ts @@ -6,15 +6,15 @@ function sample1() { selection: false, }); - canvas.on('object:moving', function(e: fabric.IEvent) { + canvas.on('object:moving', (e: fabric.IEvent) => { e.target.opacity = 0.5; }); - canvas.on('object:modified', function(e: fabric.IEvent) { + canvas.on('object:modified', (e: fabric.IEvent) => { e.target.opacity = 1; }); for (var i = 0, len = 15; i < len; i++) { - fabric.Image.fromURL('../assets/ladybug.png', function(img) { + fabric.Image.fromURL('../assets/ladybug.png', img => { img.set({ left: fabric.util.getRandomInt(0, 600), top: fabric.util.getRandomInt(0, 500), @@ -36,11 +36,11 @@ function sample2() { var dot: fabric.Circle, i: number, t1: number, t2: number, - startTimer = function() { + startTimer = () => { t1 = new Date().getTime(); return t1; }, - stopTimer = function() { + stopTimer = () => { t2 = new Date().getTime(); return t2 - t1; }, @@ -89,16 +89,16 @@ function sample2() { function sample3() { - var $: (id: string) => HTMLElement = function(id: string) { return document.getElementById(id) }; + var $: (id: string) => HTMLElement = (id: string) => document.getElementById(id); function applyFilter(index: number, filter: any) { - var obj: fabric.Image = canvas.getActiveObject(); + var obj: fabric.Image = canvas.getActiveObject(); obj.filters[index] = filter; obj.applyFilters(canvas.renderAll.bind(canvas)); } function applyFilterValue(index: number, prop: string, value: any) { - var obj: fabric.Image = canvas.getActiveObject(); + var obj: fabric.Image = canvas.getActiveObject(); if (obj.filters[index]) { obj.applyFilters(canvas.renderAll.bind(canvas)); } @@ -108,24 +108,24 @@ function sample3() { f = fabric.Image.filters; canvas.on({ - 'object:selected': function() { - fabric.util.toArray(document.getElementsByTagName('input')).forEach(function(el) { el.disabled = false; }) + 'object:selected': () => { + fabric.util.toArray(document.getElementsByTagName('input')).forEach(el => { el.disabled = false; }); var filters = ['grayscale', 'invert', 'remove-white', 'sepia', 'sepia2', 'brightness', 'noise', 'gradient-transparency', 'pixelate', 'blur', 'sharpen']; for (var i = 0; i < filters.length; i++) { - var checkBox = $(filters[i]); - var image = canvas.getActiveObject(); + var checkBox = $(filters[i]); + var image = canvas.getActiveObject(); checkBox.checked = !!image.filters[i]; } }, - 'selection:cleared': function() { - fabric.util.toArray(document.getElementsByTagName('input')).forEach(function(el) { el.disabled = true; }) + 'selection:cleared': () => { + fabric.util.toArray(document.getElementsByTagName('input')).forEach(el => { el.disabled = true; }); } }); - fabric.Image.fromURL('../assets/printio.png', function(img) { + fabric.Image.fromURL('../assets/printio.png', img => { var oImg = img.set({ left: 300, top: 300, angle: -15 }).scale(0.9); canvas.add(oImg).renderAll(); canvas.setActiveObject(oImg); @@ -139,8 +139,8 @@ function sample3() { }; $('remove-white').onclick = function(this: HTMLInputElement) { applyFilter(2, this.checked && new f.RemoveWhite({ - threshold: parseInt(($('remove-white-threshold')).value), - distance: parseInt(($('remove-white-distance')).value) + threshold: parseInt(( $('remove-white-threshold')).value, 10), + distance: parseInt(( $('remove-white-distance')).value, 10) })); }; $('remove-white-threshold').onchange = function(this: HTMLInputElement) { @@ -157,7 +157,7 @@ function sample3() { }; $('brightness').onclick = function(this: HTMLInputElement) { applyFilter(5, this.checked && new f.Brightness({ - brightness: parseInt(($('brightness-value')).value, 10) + brightness: parseInt(( $('brightness-value')).value, 10) })); }; $('brightness-value').onchange = function(this: HTMLInputElement) { @@ -165,7 +165,7 @@ function sample3() { }; $('noise').onclick = function(this: HTMLInputElement) { applyFilter(6, this.checked && new f.Noise({ - noise: parseInt(($('noise-value')).value, 10) + noise: parseInt(( $('noise-value')).value, 10) })); }; $('noise-value').onchange = function(this: HTMLInputElement) { @@ -173,7 +173,7 @@ function sample3() { }; $('gradient-transparency').onclick = function(this: HTMLInputElement) { applyFilter(7, this.checked && new f.GradientTransparency({ - threshold: parseInt(($('gradient-transparency-value')).value, 10) + threshold: parseInt(( $('gradient-transparency-value')).value, 10) })); }; $('gradient-transparency-value').onchange = function(this: HTMLInputElement) { @@ -181,7 +181,7 @@ function sample3() { }; $('pixelate').onclick = function(this: HTMLInputElement) { applyFilter(8, this.checked && new f.Pixelate({ - blocksize: parseInt(($('pixelate-value')).value, 10) + blocksize: parseInt(( $('pixelate-value')).value, 10) })); }; $('pixelate-value').onchange = function(this: HTMLInputElement) { @@ -213,7 +213,7 @@ function sample3() { function sample4() { var canvas = new fabric.Canvas('c'); - var $: (id: string) => HTMLElement = function(id: string) { return document.getElementById(id); }; + var $: (id: string) => HTMLElement = id => document.getElementById(id); var rect = new fabric.Rect({ width: 100, @@ -225,25 +225,25 @@ function sample4() { canvas.add(rect); - var angleControl = $('angle-control'); + var angleControl = $('angle-control'); angleControl.onchange = function(this: HTMLInputElement) { rect.setAngle(+this.value).setCoords(); canvas.renderAll(); }; - var scaleControl = $('scale-control'); + var scaleControl = $('scale-control'); scaleControl.onchange = function(this: HTMLInputElement) { rect.scale(+this.value).setCoords(); canvas.renderAll(); }; - var topControl = $('top-control'); + var topControl = $('top-control'); topControl.onchange = function(this: HTMLInputElement) { rect.setTop(+this.value).setCoords(); canvas.renderAll(); }; - var leftControl = $('left-control'); + var leftControl = $('left-control'); leftControl.onchange = function(this: HTMLInputElement) { rect.setLeft(+this.value).setCoords(); canvas.renderAll(); @@ -274,10 +274,10 @@ declare module "fabric" { } function sample5() { - var makeCircle = function(left: number, top: number, line1?: fabric.Line, line2?: fabric.Line, line3?: fabric.Line, line4?: fabric.Line): fabric.Circle { - var c = new fabric.Circle({ - left: left, - top: top, + var makeCircle = (left: number, top: number, line1?: fabric.Line, line2?: fabric.Line, line3?: fabric.Line, line4?: fabric.Line): fabric.Circle => { + var c = new fabric.Circle({ + left, + top, strokeWidth: 5, radius: 12, fill: '#fff', @@ -290,7 +290,7 @@ function sample5() { c.line4 = line4; c.hasControls = c.hasBorders = false; return c; - } + }; function makeLine(coords: number[]) { return new fabric.Line(coords, { @@ -321,8 +321,8 @@ function sample5() { makeCircle(line6.x2, line6.y2, line6) ); - canvas.on('object:moving', function(e) { - var p = e.target; + canvas.on('object:moving', e => { + var p = e.target; p.line1 && p.line1.set({ 'x2': p.left, 'y2': p.top }); p.line2 && p.line2.set({ 'x1': p.left, 'y1': p.top }); p.line3 && p.line3.set({ 'x1': p.left, 'y1': p.top }); @@ -333,7 +333,7 @@ function sample5() { function sample6() { var canvas = new fabric.Canvas('c'); - fabric.loadSVGFromURL('../assets/135.svg', function(objects) { + fabric.loadSVGFromURL('../assets/135.svg', objects => { var obj = objects[0].scale(0.25); canvas.centerObject(obj); canvas.add(obj); @@ -343,10 +343,10 @@ function sample6() { canvas.add(obj.clone(() => { }).set({ left: 100, top: 400, angle: -15 })); canvas.add(obj.clone(() => { }).set({ left: 480, top: 400, angle: 15 })); - canvas.on('mouse:move', function(options) { + canvas.on('mouse:move', options => { var p = canvas.getPointer(options.e); - canvas.forEachObject(function(obj) { + canvas.forEachObject(obj => { var distX = Math.abs(p.x - obj.left), distY = Math.abs(p.y - obj.top), dist = Math.round(Math.sqrt(Math.pow(distX, 2) + Math.pow(distY, 2))); @@ -368,9 +368,9 @@ function sample7() { var canvas = new fabric.Canvas('c', { selection: false }); - setInterval(function() { - fabric.Image.fromURL('../assets/ladybug.png', function(obj) { - var img = obj; + setInterval(() => { + fabric.Image.fromURL('../assets/ladybug.png', obj => { + var img = obj; img.set('left', fabric.util.getRandomInt(200, 600)).set('top', -50); img.movingLeft = !!Math.round(Math.random()); canvas.add(img); @@ -379,14 +379,13 @@ function sample7() { var animate = (function animate() { - canvas.forEachObject(function(obj) { - var img = obj; + canvas.forEachObject(obj => { + var img = obj; img.left += (img.movingLeft ? -1 : 1); img.top += 1; if (img.left > 900 || img.top > 500) { canvas.remove(img); - } - else { + } else { img.setAngle(img.getAngle() + 2); } }); @@ -404,7 +403,7 @@ function sample8() { str = '0' + str; } return str; - }; + } var getRandomInt = fabric.util.getRandomInt; @@ -428,19 +427,18 @@ function sample8() { // canvas.controlsAboveOverlay = true; function updateComplexity() { - setTimeout(function() { - var element = document.getElementById('complexity').childNodes[1]; + setTimeout(() => { + var element = document.getElementById('complexity').childNodes[1]; element.innerHTML = ' ' + canvas.complexity(); }, 100); } - document.getElementById('commands').onclick = function(ev: any) { + document.getElementById('commands').onclick = (ev: any) => { var ev: any = ev || window.event; if (ev.preventDefault) { - ev.preventDefault() - } - else if (ev.returnValue) { + ev.preventDefault(); + } else if (ev.returnValue) { ev.returnValue = false; } @@ -455,14 +453,14 @@ function sample8() { top = fabric.util.getRandomInt(0 + offset, 500 - offset), angle = fabric.util.getRandomInt(-20, 40), width = fabric.util.getRandomInt(30, 50), - opacity = (function(min: number, max: number) { return Math.random() * (max - min) + min; })(0.5, 1); + opacity = ((min: number, max: number) => Math.random() * (max - min) + min)(0.5, 1); switch (className) { case 'rect': canvas.add(new fabric.Rect({ - left: left, - top: top, + left, + top, fill: '#' + getRandomColor(), width: 50, height: 50, @@ -472,8 +470,8 @@ function sample8() { case 'circle': canvas.add(new fabric.Circle({ - left: left, - top: top, + left, + top, fill: '#' + getRandomColor(), radius: 50, opacity: 0.8 @@ -482,8 +480,8 @@ function sample8() { case 'triangle': canvas.add(new fabric.Triangle({ - left: left, - top: top, + left, + top, fill: '#' + getRandomColor(), width: 50, height: 50, @@ -492,11 +490,11 @@ function sample8() { break; case 'image1': - fabric.Image.fromURL('../assets/pug.jpg', function(image) { + fabric.Image.fromURL('../assets/pug.jpg', image => { image.set({ - left: left, - top: top, - angle: angle, + left, + top, + angle, padding: 10, cornersize: 10 }); @@ -506,11 +504,11 @@ function sample8() { break; case 'image2': - fabric.Image.fromURL('../assets/logo.png', function(image) { + fabric.Image.fromURL('../assets/logo.png', image => { image.set({ - left: left, - top: top, - angle: angle, + left, + top, + angle, padding: 10, cornersize: 10 }); @@ -521,15 +519,16 @@ function sample8() { break; case 'shape': - var id: any = element.id, match: RegExpExecArray; - if (match = /\d+$/.exec(id)) { - fabric.loadSVGFromURL('../assets/' + match[0] + '.svg', function(objects, options) { + var id: any = element.id; + const match = /\d+$/.exec(id); + if (match) { + fabric.loadSVGFromURL('../assets/' + match[0] + '.svg', (objects, options) => { var loadedObject = fabric.util.groupSVGElements(objects, options); loadedObject.set({ - left: left, - top: top, - angle: angle, + left, + top, + angle, padding: 10, cornersize: 10 }); @@ -552,46 +551,43 @@ function sample8() { updateComplexity(); }; - document.getElementById('execute').onclick = function() { - var code = (document.getElementById('canvas-console')).value; + document.getElementById('execute').onclick = () => { + var code = ( document.getElementById('canvas-console')).value; if (!(/^\s+$/).test(code)) { - eval(code); + eval(code); // tslint:disable-line:no-eval } }; - document.getElementById('rasterize').onclick = function() { + document.getElementById('rasterize').onclick = () => { if (!fabric.Canvas.supports('toDataURL')) { alert('This browser doesn\'t provide means to serialize canvas to an image'); - } - else { + } else { window.open(canvas.toDataURL('png')); } }; var removeSelectedEl = document.getElementById('remove-selected'); - removeSelectedEl.onclick = function() { + removeSelectedEl.onclick = () => { var activeObject = canvas.getActiveObject(), activeGroup = canvas.getActiveGroup(); if (activeObject) { canvas.remove(activeObject); - } - else if (activeGroup) { + } else if (activeGroup) { var objectsInGroup = activeGroup.getObjects(); canvas.discardActiveGroup(); - objectsInGroup.forEach(function(object) { + objectsInGroup.forEach(object => { canvas.remove(object); }); } }; - var supportsInputOfType = function(type: string) { - return function() { - var el = document.createElement('input'); + var supportsInputOfType = (type: string) => { + return () => { + var el = document.createElement('input'); try { el.type = type; - } - catch (err) { } + } catch (err) { } return el.type === type; }; }; @@ -600,14 +596,14 @@ function sample8() { supportsColorpicker = supportsInputOfType('color'); if (supportsSlider()) { - (function() { + (() => { var controls = document.getElementById('controls'); - var sliderLabel = document.createElement('label'); + var sliderLabel = document.createElement('label'); sliderLabel.htmlFor = 'opacity'; sliderLabel.innerHTML = 'Opacity: '; - var slider = document.createElement('input'); + var slider = document.createElement('input'); try { slider.type = 'range'; } catch (err) { } @@ -632,15 +628,15 @@ function sample8() { } if (supportsColorpicker()) { - (function() { + (() => { var controls = document.getElementById('controls'); - var label = document.createElement('label'); + var label = document.createElement('label'); label.htmlFor = 'color'; label.innerHTML = 'Color: '; label.style.marginLeft = '10px'; - var colorpicker = document.createElement('input'); + var colorpicker = document.createElement('input'); colorpicker.type = 'color'; colorpicker.id = 'color'; colorpicker.style.width = '40px'; @@ -663,7 +659,7 @@ function sample8() { } var lockHorizontallyEl = document.getElementById('lock-horizontally'); - lockHorizontallyEl.onclick = function() { + lockHorizontallyEl.onclick = () => { var activeObject: any = canvas.getActiveObject(); if (activeObject) { activeObject.lockMovementX = !activeObject.lockMovementX; @@ -674,7 +670,7 @@ function sample8() { }; var lockVerticallyEl = document.getElementById('lock-vertically'); - lockVerticallyEl.onclick = function() { + lockVerticallyEl.onclick = () => { var activeObject: any = canvas.getActiveObject(); if (activeObject) { activeObject.lockMovementY = !activeObject.lockMovementY; @@ -685,7 +681,7 @@ function sample8() { }; var lockScalingXEl = document.getElementById('lock-scaling-x'); - lockScalingXEl.onclick = function() { + lockScalingXEl.onclick = () => { var activeObject: any = canvas.getActiveObject(); if (activeObject) { activeObject.lockScalingX = !activeObject.lockScalingX; @@ -696,7 +692,7 @@ function sample8() { }; var lockScalingYEl = document.getElementById('lock-scaling-y'); - lockScalingYEl.onclick = function() { + lockScalingYEl.onclick = () => { var activeObject: any = canvas.getActiveObject(); if (activeObject) { activeObject.lockScalingY = !activeObject.lockScalingY; @@ -707,7 +703,7 @@ function sample8() { }; var lockRotationEl = document.getElementById('lock-rotation'); - lockRotationEl.onclick = function() { + lockRotationEl.onclick = () => { var activeObject: any = canvas.getActiveObject(); if (activeObject) { activeObject.lockRotation = !activeObject.lockRotation; @@ -738,7 +734,7 @@ function sample8() { activeObjectButtons.push(colorEl); } - for (var i = activeObjectButtons.length; i--;) { + for (var i = activeObjectButtons.length; i--; ) { activeObjectButtons[i]; } @@ -748,7 +744,7 @@ function sample8() { function onObjectSelected(e: fabric.IEvent) { var selectedObject = e.target; - for (var i = activeObjectButtons.length; i--;) { + for (var i = activeObjectButtons.length; i--; ) { activeObjectButtons[i]; } @@ -759,40 +755,39 @@ function sample8() { lockRotationEl.innerHTML = (selectedObject.lockRotation ? 'Unlock rotation' : 'Lock rotation'); } - canvas.on('selection:cleared', function(e) { - for (var i = activeObjectButtons.length; i--;) { + canvas.on('selection:cleared', e => { + for (var i = activeObjectButtons.length; i--; ) { activeObjectButtons[i]; } }); var drawingModeEl = document.getElementById('drawing-mode'), drawingOptionsEl = document.getElementById('drawing-mode-options'), - drawingColorEl = document.getElementById('drawing-color'), - drawingLineWidthEl = document.getElementById('drawing-line-width'); + drawingColorEl = document.getElementById('drawing-color'), + drawingLineWidthEl = document.getElementById('drawing-line-width'); - drawingModeEl.onclick = function() { + drawingModeEl.onclick = () => { var canvasWithDrawingMode: any = canvas; canvasWithDrawingMode.isDrawingMode = !canvasWithDrawingMode.isDrawingMode; if (canvasWithDrawingMode.isDrawingMode) { drawingModeEl.innerHTML = 'Cancel drawing mode'; drawingModeEl.className = 'is-drawing'; drawingOptionsEl.style.display = ''; - } - else { + } else { drawingModeEl.innerHTML = 'Enter drawing mode'; drawingModeEl.className = ''; drawingOptionsEl.style.display = 'none'; } }; - canvas.on('path:created', function() { + canvas.on('path:created', () => { updateComplexity(); }); - drawingColorEl.onchange = function() { + drawingColorEl.onchange = () => { canvas.freeDrawingColor = drawingColorEl.value; }; - drawingLineWidthEl.onchange = function() { + drawingLineWidthEl.onchange = () => { canvas.freeDrawingLineWidth = parseInt(drawingLineWidthEl.value, 10) || 1; // disallow 0, NaN, etc. }; @@ -803,7 +798,7 @@ function sample8() { var text = 'Lorem ipsum dolor sit amet,\nconsectetur adipisicing elit,\nsed do eiusmod tempor incididunt\nut labore et dolore magna aliqua.\n' + 'Ut enim ad minim veniam,\nquis nostrud exercitation ullamco\nlaboris nisi ut aliquip ex ea commodo consequat.'; - document.getElementById('add-text').onclick = function() { + document.getElementById('add-text').onclick = () => { var textSample = new fabric.Text(text.slice(0, getRandomInt(0, text.length)), { left: getRandomInt(350, 400), top: getRandomInt(350, 400), @@ -819,7 +814,7 @@ function sample8() { }; - document.onkeydown = function(e) { + document.onkeydown = e => { var obj = canvas.getActiveObject() || canvas.getActiveGroup(); if (obj && e.keyCode === 8) { // this is horrible. need to fix, so that unified interface can be used @@ -829,25 +824,24 @@ function sample8() { // groupObjects.forEach(function(obj) { // canvas.remove(obj); // }); - } - else { - //canvas.remove(obj); + } else { + // canvas.remove(obj); } canvas.renderAll(); // return false; } }; - setTimeout(function() { + setTimeout(() => { canvas.calcOffset(); }, 100); if (document.location.search.indexOf('guidelines') > -1) { - //initCenteringGuidelines(canvas); - //initAligningGuidelines(canvas); + // initCenteringGuidelines(canvas); + // initAligningGuidelines(canvas); } - gradientifyBtn.onclick = function() { + gradientifyBtn.onclick = () => { var obj = canvas.getActiveObject(); if (obj) { obj.setGradient("fill", { @@ -862,13 +856,13 @@ function sample8() { } }; - var textEl = document.getElementById('text'); + var textEl = document.getElementById('text'); if (textEl) { textEl.onfocus = function() { var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - this.value = (activeObject).text; + this.value = ( activeObject).text; } }; textEl.onkeyup = function(e) { @@ -876,9 +870,8 @@ function sample8() { if (activeObject) { if (!this.value) { canvas.discardActiveObject(); - } - else { - (activeObject).text = this.value; + } else { + ( activeObject).text = this.value; } canvas.renderAll(); } @@ -889,9 +882,9 @@ function sample8() { if (cmdUnderlineBtn) { activeObjectButtons.push(cmdUnderlineBtn); cmdUnderlineBtn.onclick = function() { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - activeObject.textDecoration = (activeObject.textDecoration == 'underline' ? '' : 'underline'); + activeObject.textDecoration = (activeObject.textDecoration === 'underline' ? '' : 'underline'); this.className = activeObject.textDecoration ? 'selected' : ''; canvas.renderAll(); } @@ -902,9 +895,9 @@ function sample8() { if (cmdLinethroughBtn) { activeObjectButtons.push(cmdLinethroughBtn); cmdLinethroughBtn.onclick = function() { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - activeObject.textDecoration = (activeObject.textDecoration == 'line-through' ? '' : 'line-through'); + activeObject.textDecoration = (activeObject.textDecoration === 'line-through' ? '' : 'line-through'); this.className = activeObject.textDecoration ? 'selected' : ''; canvas.renderAll(); } @@ -915,9 +908,9 @@ function sample8() { if (cmdOverlineBtn) { activeObjectButtons.push(cmdOverlineBtn); cmdOverlineBtn.onclick = function() { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - activeObject.textDecoration = (activeObject.textDecoration == 'overline' ? '' : 'overline'); + activeObject.textDecoration = (activeObject.textDecoration === 'overline' ? '' : 'overline'); this.className = activeObject.textDecoration ? 'selected' : ''; canvas.renderAll(); } @@ -928,9 +921,9 @@ function sample8() { if (cmdBoldBtn) { activeObjectButtons.push(cmdBoldBtn); cmdBoldBtn.onclick = function() { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - activeObject.fontWeight = (activeObject.fontWeight == 'bold' ? '' : 'bold'); + activeObject.fontWeight = (activeObject.fontWeight === 'bold' ? '' : 'bold'); this.className = activeObject.fontWeight ? 'selected' : ''; canvas.renderAll(); } @@ -941,9 +934,9 @@ function sample8() { if (cmdItalicBtn) { activeObjectButtons.push(cmdItalicBtn); cmdItalicBtn.onclick = function() { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - activeObject.fontStyle = (activeObject.fontStyle == 'italic' ? '' : 'italic'); + activeObject.fontStyle = (activeObject.fontStyle === 'italic' ? '' : 'italic'); this.className = activeObject.fontStyle ? 'selected' : ''; canvas.renderAll(); } @@ -954,7 +947,7 @@ function sample8() { if (cmdShadowBtn) { activeObjectButtons.push(cmdShadowBtn); cmdShadowBtn.onclick = function() { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.shadow = !activeObject.shadow ? 'rgba(0,0,0,0.2) 2px 2px 10px' : ''; this.className = activeObject.shadow ? 'selected' : ''; @@ -967,7 +960,7 @@ function sample8() { if (textAlignSwitch) { activeObjectButtons.push(textAlignSwitch); textAlignSwitch.onchange = function(this: HTMLInputElement) { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.textAlign = this.value.toLowerCase(); canvas.renderAll(); @@ -979,7 +972,7 @@ function sample8() { if (fontFamilySwitch) { activeObjectButtons.push(fontFamilySwitch); fontFamilySwitch.onchange = function(this: HTMLInputElement) { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.fontFamily = this.value; canvas.renderAll(); @@ -990,7 +983,7 @@ function sample8() { var bgColorField = document.getElementById('text-bg-color'); if (bgColorField) { bgColorField.onchange = function(this: HTMLInputElement) { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.backgroundColor = this.value; canvas.renderAll(); @@ -1001,7 +994,7 @@ function sample8() { var strokeColorField = document.getElementById('text-stroke-color'); if (strokeColorField) { strokeColorField.onchange = function(this: HTMLInputElement) { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.stroke = this.value; canvas.renderAll(); @@ -1010,10 +1003,10 @@ function sample8() { } if (supportsSlider) { - (function() { + (() => { var container = document.getElementById('text-controls'); - var slider = document.createElement('input'); - var label = document.createElement('label'); + var slider = document.createElement('input'); + var label = document.createElement('label'); label.innerHTML = 'Line height: '; try { slider.type = 'range'; } catch (err) { } slider.min = "0"; @@ -1024,22 +1017,22 @@ function sample8() { label.appendChild(slider); slider.title = "Line height"; slider.onchange = function() { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.lineHeight = +this.value; canvas.renderAll(); } }; - canvas.on('object:selected', function(e: fabric.IEvent) { - slider.value = String((e.target).lineHeight); + canvas.on('object:selected', (e: fabric.IEvent) => { + slider.value = String(( e.target).lineHeight); }); })(); } - document.getElementById('load-svg').onclick = function() { - var svg = (document.getElementById('svg-console')).value; - fabric.loadSVGFromString(svg, function(objects, options) { + document.getElementById('load-svg').onclick = () => { + var svg = ( document.getElementById('svg-console')).value; + fabric.loadSVGFromString(svg, (objects, options) => { var obj = fabric.util.groupSVGElements(objects, options); canvas.add(obj).centerObject(obj).renderAll(); obj.setCoords(); @@ -1049,6 +1042,6 @@ function sample8() { function sample9() { var canvas = new fabric.Canvas('c'); - canvas.setBackgroundImage('yolo.jpg', () => { "a" }, { opacity: 45 }); - canvas.setBackgroundImage('yolo.jpg', () => { "a" }); + canvas.setBackgroundImage('yolo.jpg', () => { "a"; }, { opacity: 45 }); + canvas.setBackgroundImage('yolo.jpg', () => { "a"; }); } diff --git a/fabric/tsconfig.json b/fabric/tsconfig.json index 13faaee670..ab7021e0c9 100644 --- a/fabric/tsconfig.json +++ b/fabric/tsconfig.json @@ -6,7 +6,7 @@ "dom" ], "noImplicitAny": true, - "noImplicitThis": false, + "noImplicitThis": true, "strictNullChecks": false, "baseUrl": "../", "typeRoots": [ diff --git a/fabric/tslint.json b/fabric/tslint.json index 9f552c56eb..525190cf34 100644 --- a/fabric/tslint.json +++ b/fabric/tslint.json @@ -7,4 +7,4 @@ "no-empty-interface": false, "unified-signatures": false } -} \ No newline at end of file +} diff --git a/falcor/index.d.ts b/falcor/index.d.ts index fe3af19544..1bf3c9ba23 100644 --- a/falcor/index.d.ts +++ b/falcor/index.d.ts @@ -35,7 +35,10 @@ export { ///////////////////////////////////////////////////// /** - * A DataSource is an interface which can be implemented to expose JSON Graph information to a Model. Every DataSource is associated with a single JSON Graph object. Models execute JSON Graph operations (get, set, and call) to retrieve values from the DataSource’s JSON Graph object. DataSources may retrieve JSON Graph information from anywhere, including device memory, a remote machine, or even a lazily-run computation. + * A DataSource is an interface which can be implemented to expose JSON Graph information to a Model. + * Every DataSource is associated with a single JSON Graph object. + * Models execute JSON Graph operations (get, set, and call) to retrieve values from the DataSource’s JSON Graph object. + * DataSources may retrieve JSON Graph information from anywhere, including device memory, a remote machine, or even a lazily-run computation. **/ export abstract class DataSource { @@ -83,12 +86,14 @@ type ModelOnChange = () => void; type ModelErrorSelector = (jsonGraphError: any) => any; /** - * This function is invoked every time a value in the Model cache is about to be replaced with a new value. If the function returns true, the existing value is replaced with a new value and the version flag on all of the value's ancestors in the tree are incremented. + * This function is invoked every time a value in the Model cache is about to be replaced with a new value. + * If the function returns true, the existing value is replaced with a new value and the version flag on all of the value's ancestors in the tree are incremented. **/ type ModelComparator = (existingValue: any, newValue: any) => boolean; /** - * A Model object is used to execute commands against a {@link JSONGraph} object. {@link Model}s can work with a local JSONGraph cache, or it can work with a remote {@link JSONGraph} object through a {@link DataSource}. + * A Model object is used to execute commands against a {@link JSONGraph} object + * {@link Model}s can work with a local JSONGraph cache, or it can work with a remote {@link JSONGraph} object through a {@link DataSource}. **/ export class Model { constructor(options?: ModelOptions); @@ -100,7 +105,9 @@ export class Model { get(...path: Array): ModelResponse>; /** - * Sets the value at one or more places in the JSONGraph model. The set method accepts one or more {@link PathValue}s, each of which is a combination of a location in the document and the value to place there. In addition to accepting {@link PathValue}s, the set method also returns the values after the set operation is complete. + * Sets the value at one or more places in the JSONGraph model. + * The set method accepts one or more {@link PathValue}s, each of which is a combination of a location in the document and the value to place there. + * In addition to accepting {@link PathValue}s, the set method also returns the values after the set operation is complete. **/ set(...args: PathValue[]): ModelResponse>; set(...args: PathValue[]): ModelResponse>; @@ -127,7 +134,9 @@ export class Model { invalidate(...path: PathSet[]): void; /** - * Returns a new {@link Model} bound to a location within the {@link JSONGraph}. The bound location is never a {@link Reference}: any {@link Reference}s encountered while resolving the bound {@link Path} are always replaced with the {@link Reference}s target value. For subsequent operations on the {@link Model}, all paths will be evaluated relative to the bound path. Deref allows you to: + * Returns a new {@link Model} bound to a location within the {@link JSONGraph}. + * The bound location is never a {@link Reference}: any {@link Reference}s encountered while resolving the bound {@link Path} are always replaced with the {@link Reference}s target value. + * For subsequent operations on the {@link Model}, all paths will be evaluated relative to the bound path. Deref allows you to: * - Expose only a fragment of the {@link JSONGraph} to components, rather than the entire graph * - Hide the location of a {@link JSONGraph} fragment from components * - Optimize for executing multiple operations and path looksup at/below the same location in the {@link JSONGraph} @@ -162,7 +171,8 @@ export class Model { getVersion(path?: Path): number; /** - * Returns a clone of the {@link Model} that enables batching. Within the configured time period, paths for get operations are collected and sent to the {@link DataSource} in a batch. Batching can be more efficient if the {@link DataSource} access the network, potentially reducing the number of HTTP requests to the server. + * Returns a clone of the {@link Model} that enables batching. Within the configured time period, paths for get operations are collected and sent to the {@link DataSource} in a batch. + * Batching can be more efficient if the {@link DataSource} access the network, potentially reducing the number of HTTP requests to the server. **/ batch(schedulerOrDelay?: number | Scheduler): Model; // FIXME what's a valid type for scheduler? @@ -172,7 +182,8 @@ export class Model { unbatch(): Model; /** - * Returns a clone of the {@link Model} that treats errors as values. Errors will be reported in the same callback used to report data. Errors will appear as objects in responses, rather than being sent to the {@link Observable~onErrorCallback} callback of the {@link ModelResponse}. + * Returns a clone of the {@link Model} that treats errors as values. Errors will be reported in the same callback used to report data. + * Errors will appear as objects in responses, rather than being sent to the {@link Observable~onErrorCallback} callback of the {@link ModelResponse}. **/ treatErrorsAsValues(): Model; @@ -182,12 +193,14 @@ export class Model { asDataSource(): DataSource; /** - * Returns a clone of the {@link Model} that boxes values returning the wrapper ({@link Atom}, {@link Reference}, or {@link Error}), rather than the value inside it. This allows any metadata attached to the wrapper to be inspected. + * Returns a clone of the {@link Model} that boxes values returning the wrapper ({@link Atom}, {@link Reference}, or {@link Error}), rather than the value inside it. + * This allows any metadata attached to the wrapper to be inspected. **/ boxValues(): Model; /** - * Returns a clone of the {@link Model} that unboxes values, returning the value inside of the wrapper ({@link Atom}, {@link Reference}, or {@link Error}), rather than the wrapper itself. This is the default mode. + * Returns a clone of the {@link Model} that unboxes values, returning the value inside of the wrapper ({@link Atom}, {@link Reference}, or {@link Error}), rather than the wrapper itself. + * This is the default mode. **/ unboxValues(): Model; @@ -227,12 +240,17 @@ interface Thenable { export class Observable{ /** - * The forEach method is a synonym for {@link Observable.prototype.subscribe} and triggers the execution of the Observable, causing the values within to be pushed to a callback. An Observable is like a pipe of water that is closed. When forEach is called, we open the valve and the values within are pushed at us. These values can be received using either callbacks or an {@link Observer} object. + * The forEach method is a synonym for {@link Observable.prototype.subscribe} and triggers the execution of the Observable, causing the values within to be pushed to a callback. + * An Observable is like a pipe of water that is closed. + * When forEach is called, we open the valve and the values within are pushed at us. + * These values can be received using either callbacks or an {@link Observer} object. **/ forEach(onNext?: ObservableOnNextCallback, onError?: ObservableOnErrorCallback , onCompleted?: ObservableOnCompletedCallback ): Subscription; /** - * The subscribe method is a synonym for {@link Observable.prototype.forEach} and triggers the execution of the Observable, causing the values within to be pushed to a callback. An Observable is like a pipe of water that is closed. When forEach is called, we open the valve and the values within are pushed at us. These values can be received using either callbacks or an {@link Observer} object. + * The subscribe method is a synonym for {@link Observable.prototype.forEach} and triggers the execution of the Observable, causing the values within to be pushed to a callback. + * An Observable is like a pipe of water that is closed. + * When forEach is called, we open the valve and the values within are pushed at us. These values can be received using either callbacks or an {@link Observer} object. **/ subscribe(onNext?: ObservableOnNextCallback, onError?: ObservableOnErrorCallback , onCompleted?: ObservableOnCompletedCallback ): Subscription; } @@ -243,12 +261,14 @@ export class Observable{ type ObservableOnNextCallback = (value: T) => void; /** - * This callback accepts an error that occurred while evaluating the operation underlying the {@link Observable} stream. When this callback is invoked, the {@link Observable} stream ends and no more values will be received by the {@link Observable~onNextCallback}. + * This callback accepts an error that occurred while evaluating the operation underlying the {@link Observable} stream. + * When this callback is invoked, the {@link Observable} stream ends and no more values will be received by the {@link Observable~onNextCallback}. **/ type ObservableOnErrorCallback = (error: Error) => void; /** - * This callback is invoked when the {@link Observable} stream ends. When this callback is invoked the {@link Observable} stream has ended, and therefore the {@link Observable~onNextCallback} will not receive any more values. + * This callback is invoked when the {@link Observable} stream ends. + * When this callback is invoked the {@link Observable} stream has ended, and therefore the {@link Observable~onNextCallback} will not receive any more values. **/ type ObservableOnCompletedCallback = () => void; diff --git a/falcor/test/index.ts b/falcor/test/index.ts index 4fdba89022..2798b72645 100644 --- a/falcor/test/index.ts +++ b/falcor/test/index.ts @@ -1,6 +1,6 @@ import falcor = require('falcor'); -let dataSource: falcor.DataSource; +declare const dataSource: falcor.DataSource; dataSource.get([['someParam']]).subscribe(jsonGraphEnvelope => { console.log(jsonGraphEnvelope.jsonGraph); }); @@ -84,7 +84,7 @@ model.invalidate(['items', 0, 'name'], ['items', 1, 'name']); model.invalidate(['items', {from: 0, to: 1}, 'name']); model.get('items[0].["name", "id"]').then(res => { - const derefedModel = model.deref(res.json.items[0]) + const derefedModel = model.deref(res.json.items[0]); derefedModel.get('name', 'id'); }); diff --git a/falcor/tslint.json b/falcor/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/falcor/tslint.json +++ b/falcor/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/fetch-mock/fetch-mock-tests.ts b/fetch-mock/fetch-mock-tests.ts index f16aab11c9..d3ea2c374c 100644 --- a/fetch-mock/fetch-mock-tests.ts +++ b/fetch-mock/fetch-mock-tests.ts @@ -24,14 +24,14 @@ fetchMock.calls().unmatched[0][0].toUpperCase(); fetchMock.calls("http://test.com")[0][0].toUpperCase(); (fetchMock.calls("http://test.com")[0][1] as RequestInit).body; -let doneStatus: boolean = fetchMock.done(); -let doneStatusArguments: boolean = fetchMock.done("http://test.com"); +const doneStatus: boolean = fetchMock.done(); +const doneStatusArguments: boolean = fetchMock.done("http://test.com"); -let calledStatus: boolean = fetchMock.called(); -let calledStatusArguments = fetchMock.called("http://test.com"); +const calledStatus: boolean = fetchMock.called(); +const calledStatusArguments = fetchMock.called("http://test.com"); (fetchMock.lastCall()[1] as RequestInit).body; -let lastUrl: string = fetchMock.lastUrl(); +const lastUrl: string = fetchMock.lastUrl(); fetchMock.lastOptions(); fetchMock.get("http://test.com", 200); diff --git a/fine-uploader/index.d.ts b/fine-uploader/index.d.ts index 75184f1baf..dab4e720ea 100644 --- a/fine-uploader/index.d.ts +++ b/fine-uploader/index.d.ts @@ -76,6 +76,7 @@ declare namespace qq { onLeave?: string; // default: The files are being uploaded, if you leave now the upload will be canceled. retryFailTooManyItemsError?: string; // default: Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}. typeError?: string; // default: {file} has an invalid extension. Valid extension(s): {extensions}. + // tslint:disable-next-line:max-line-length unsupportedBrowserIos8Safari?: string; // default: Unrecoverable error - this browser does not permit file uploading of any kind due to serious bugs in iOS8 Safari. Please use iOS8 Chrome until Apple fixes these issues. } @@ -115,7 +116,13 @@ declare namespace qq { } interface ScalingOptions { - customResizer?: (blob: File | Blob, height: number, image: HTMLImageElement, sourceCanvas: HTMLCanvasElement, targetCanvas: HTMLCanvasElement, width: number) => Promise | undefined; // default: undefined + customResizer?: ( + blob: File | Blob, + height: number, + image: HTMLImageElement, + sourceCanvas: HTMLCanvasElement, + targetCanvas: HTMLCanvasElement, + width: number) => Promise | undefined; // default: undefined defaultQuality?: number; // default: 80 defaultType?: string | null; // default: null failureText?: string; // default: Failed to scale @@ -127,7 +134,9 @@ declare namespace qq { /** * From Documentation: - * An array containing size objects that describe scaled versions of each submitted image that should be generated and uploaded. A size object should usually contain a name String property (which will be appended to the file name of the scaled file), and must always contain a maxSize integer property. A type MIME string property is optional. + * An array containing size objects that describe scaled versions of each submitted image that should be generated and uploaded. + * A size object should usually contain a name String property (which will be appended to the file name of the scaled file), and must always contain a maxSize integer property. + * A type MIME string property is optional. */ interface Size { name: string; @@ -203,7 +212,8 @@ declare namespace qq { onTotalProgress?: (totalUploadedBytes: number, totalBytes: number) => void; onUpload?: (id: number, name: string) => void; onUploadChunk?: (id: number, name: string, chunkData: ChunkData) => void; - onUploadChunkSuccess?: (id: number, chunkData: ChunkData, responseJSON: T, xhr: XMLHttpRequest) => void; // ignore xhr: XDomainRequest as it is not compatible for all versions of TypeScript + // ignore xhr: XDomainRequest as it is not compatible for all versions of TypeScript + onUploadChunkSuccess?: (id: number, chunkData: ChunkData, responseJSON: T, xhr: XMLHttpRequest) => void; onValidate?: (data: ValidateMetadata, buttonContainer: HTMLElement) => void; onValidateBatch?: (fileOrBlobDataArray: ValidateMetadata[], buttomContainer: HTMLElement) => void; } diff --git a/fine-uploader/test/blobs.ts b/fine-uploader/test/blobs.ts index a8f3ab3370..99e5355460 100644 --- a/fine-uploader/test/blobs.ts +++ b/fine-uploader/test/blobs.ts @@ -1,11 +1,9 @@ -/// - function testBlob() { - let config: qq.BasicOptions = { + const config: qq.BasicOptions = { blobs: { defaultName: "hi.png" } }; - let uploader = new qq.FineUploaderBasic(config); + const uploader = new qq.FineUploaderBasic(config); } diff --git a/fine-uploader/test/callbacks.ts b/fine-uploader/test/callbacks.ts index 273f792dd9..eba85ad2a0 100644 --- a/fine-uploader/test/callbacks.ts +++ b/fine-uploader/test/callbacks.ts @@ -1,16 +1,14 @@ -/// - class CallbacksTest { constructor(private opts: qq.CallbackOptions) { } testCallbacks() { - let opts = this.opts; + const opts = this.opts; - type CustomType = { + interface CustomType { myTypeOfClass: string; - }; + } opts.onAutoRetry = (id, name, attemptNumber) => {}; diff --git a/fine-uploader/test/camera.ts b/fine-uploader/test/camera.ts index 0186080032..b42a080778 100644 --- a/fine-uploader/test/camera.ts +++ b/fine-uploader/test/camera.ts @@ -1,12 +1,10 @@ -/// - function cameraTest() { const cameraButton = new HTMLButtonElement(); const cameraOptions: qq.CameraOptions = { button: cameraButton, ios: false - } + }; const config: qq.BasicOptions = { camera: cameraOptions diff --git a/fine-uploader/test/chunking.ts b/fine-uploader/test/chunking.ts index 4c914f029a..386dd67738 100644 --- a/fine-uploader/test/chunking.ts +++ b/fine-uploader/test/chunking.ts @@ -1,5 +1,3 @@ -/// - function chunkingTest() { const chunkingOptions: qq.ChunkingOptions = { diff --git a/fine-uploader/test/core.ts b/fine-uploader/test/core.ts index a91a5b157d..dbc06e95d6 100644 --- a/fine-uploader/test/core.ts +++ b/fine-uploader/test/core.ts @@ -1,11 +1,9 @@ -/// - function testCore() { - let button: HTMLElement = new HTMLButtonElement() + const button: HTMLElement = new HTMLButtonElement(); - let config: qq.BasicOptions = { + const config: qq.BasicOptions = { autoUpload: true, - button: button, + button, debug: true, disableCancelForFormUploads: true, formatFileName: (rawFileName: string) => { @@ -15,5 +13,5 @@ function testCore() { multiple: true }; - let uploader = new qq.FineUploaderBasic(config); + const uploader = new qq.FineUploaderBasic(config); } diff --git a/fine-uploader/test/cors.ts b/fine-uploader/test/cors.ts index d0abddff37..771b210208 100644 --- a/fine-uploader/test/cors.ts +++ b/fine-uploader/test/cors.ts @@ -1,11 +1,9 @@ -/// - function corsTest() { const corsOptions: qq.CorsOptions = { allowXdr: true, expected: true, sendCredentials: true - } + }; const config: qq.BasicOptions = { cors: corsOptions diff --git a/fine-uploader/test/deleteFile.ts b/fine-uploader/test/deleteFile.ts index 7372f1135f..49c3e68890 100644 --- a/fine-uploader/test/deleteFile.ts +++ b/fine-uploader/test/deleteFile.ts @@ -1,5 +1,3 @@ -/// - function deleteFileTest() { interface CustomHeader { myOption: string; @@ -9,7 +7,7 @@ function deleteFileTest() { myParam: string; } - let deleteFileOptions: qq.DeleteFileOptions = { + const deleteFileOptions: qq.DeleteFileOptions = { customHeader: { myOption: "ewwww" }, @@ -22,9 +20,9 @@ function deleteFileTest() { }; - let config: qq.BasicOptions = { + const config: qq.BasicOptions = { deleteFile: deleteFileOptions }; - let uploader = new qq.FineUploaderBasic(config); + const uploader = new qq.FineUploaderBasic(config); } diff --git a/fine-uploader/test/extraButtons.ts b/fine-uploader/test/extraButtons.ts index abc2194c30..eef709bea8 100644 --- a/fine-uploader/test/extraButtons.ts +++ b/fine-uploader/test/extraButtons.ts @@ -1,14 +1,12 @@ -/// - function extraButtons() { - type Validation = { - myValue: string - }; + interface Validation { + myValue: string; + } - let element: HTMLElement = new HTMLElement(); + const element: HTMLElement = new HTMLElement(); - let extraButtonOptions: qq.ExtraButtonsOptions = { - element: element, + const extraButtonOptions: qq.ExtraButtonsOptions = { + element, fileInputTitle: "inputTitle", folders: true, multiple: false, @@ -17,9 +15,9 @@ function extraButtons() { } }; - let config: qq.BasicOptions = { + const config: qq.BasicOptions = { extraButtons: extraButtonOptions }; - let uploader = new qq.FineUploaderBasic(config); + const uploader = new qq.FineUploaderBasic(config); } diff --git a/fine-uploader/test/form.ts b/fine-uploader/test/form.ts index d280de7a03..ccc08b69a1 100644 --- a/fine-uploader/test/form.ts +++ b/fine-uploader/test/form.ts @@ -1,15 +1,13 @@ -/// - function formTest() { - let formOptions: qq.FormOptions = { + const formOptions: qq.FormOptions = { element: "qq-form", autoUpload: true, interceptSubmit: true }; - let config: qq.BasicOptions = { + const config: qq.BasicOptions = { form: formOptions }; - let uploader = new qq.FineUploaderBasic(config); + const uploader = new qq.FineUploaderBasic(config); } diff --git a/fine-uploader/test/message.ts b/fine-uploader/test/message.ts index fa3d11adb6..726584bf7b 100644 --- a/fine-uploader/test/message.ts +++ b/fine-uploader/test/message.ts @@ -1,7 +1,5 @@ -/// - function messageTest() { - let messageOptions: qq.MessagesOptions = { + const messageOptions: qq.MessagesOptions = { emptyError: "emptyError", maxHeightImageError: "maxHeightImageError", maxWidthImageError: "error occurred", @@ -15,9 +13,9 @@ function messageTest() { unsupportedBrowserIos8Safari: "error occurred" }; - let config: qq.BasicOptions = { + const config: qq.BasicOptions = { messages: messageOptions }; - let uploader = new qq.FineUploaderBasic(config); + const uploader = new qq.FineUploaderBasic(config); } diff --git a/fine-uploader/test/method.ts b/fine-uploader/test/method.ts index 27e5144aa0..1adb13db81 100644 --- a/fine-uploader/test/method.ts +++ b/fine-uploader/test/method.ts @@ -1,13 +1,11 @@ -/// - class TestMethods { constructor(private uploader: qq.FineUploaderBasic) { } testAddFiles() { - type ParamType = { + interface ParamType { field: string; - }; + } const params: ParamType = { field: 'hiiiii' @@ -21,9 +19,9 @@ class TestMethods { } testAddInitialFiles() { - type InitialFiles = { + interface InitialFiles { myField: number; - }; + } const initialFiles: InitialFiles[] = [{ myField: 1324 @@ -43,22 +41,22 @@ class TestMethods { return new Blob(); }); } - ) + ); } testGetUploads() { - type ResponseType = { + interface ResponseType { hi: string; } - let response: ResponseType | ResponseType[] = this.uploader.getUploads({ + const response: ResponseType | ResponseType[] = this.uploader.getUploads({ status: "proggresssssssesees" }); } testSetCustomHeaders() { - type CustomHeader = { - customField: number - }; + interface CustomHeader { + customField: number; + } this.uploader.setCustomHeaders({ customField: 1234 @@ -66,9 +64,9 @@ class TestMethods { } testSetDeleteCustomHeaders() { - type CustomHeader = { - customField: number - }; + interface CustomHeader { + customField: number; + } this.uploader.setDeleteFileCustomHeaders({ customField: 1234 @@ -76,7 +74,7 @@ class TestMethods { } testSetDeleteFileParams() { - type CustomParams = { + interface CustomParams { paramField: boolean; } this.uploader.setDeleteFileParams({ @@ -85,9 +83,9 @@ class TestMethods { } testSetParams() { - type CustomParams = { + interface CustomParams { customParams: number; - }; + } this.uploader.setParams({ customParams: 1234 @@ -100,8 +98,8 @@ class TestMethods { this.uploader.clearStoredFiles(); const shouldContinue: boolean = this.uploader.continueUpload(1234); this.uploader.deleteFile(1234); - let elem: HTMLElement = this.uploader.getButton(1234); - let fileOrBlob: File | Blob = this.uploader.getFile(1234); + const elem: HTMLElement = this.uploader.getButton(1234); + const fileOrBlob: File | Blob = this.uploader.getFile(1234); let num: number = this.uploader.getInProgress(); let s: string = this.uploader.getName(1234); num = this.uploader.getParentId(1234); @@ -110,7 +108,7 @@ class TestMethods { num = this.uploader.getSize(1234); s = this.uploader.getUuid(1234); this.uploader.log("why am i doing this?", "info"); - let b: boolean = this.uploader.pauseUpload(1234); + const b: boolean = this.uploader.pauseUpload(1234); this.uploader.reset(); this.uploader.retry(1234); const blobPromise: Promise = this.uploader.scaleImage(1234, { @@ -135,7 +133,7 @@ class TestMethods { uiTests() { this.uploader.addExtraDropzone(new HTMLElement()); let elem: HTMLElement = this.uploader.getDropTarget(1234); - let n: number = this.uploader.getId(elem); + const n: number = this.uploader.getId(elem); elem = this.uploader.getItemByFileId(n); this.uploader.removeExtraDropzone(elem); } diff --git a/fine-uploader/test/paste.ts b/fine-uploader/test/paste.ts index 5122238c75..9b3c7d9007 100644 --- a/fine-uploader/test/paste.ts +++ b/fine-uploader/test/paste.ts @@ -1,12 +1,10 @@ -/// - function pasteTest() { const targetElement: HTMLElement = new HTMLElement(); const pasteOptions: qq.PasteOptions = { defaultName: "pasted_image", - targetElement: targetElement - } + targetElement + }; const config: qq.BasicOptions = { paste: pasteOptions diff --git a/fine-uploader/test/request.ts b/fine-uploader/test/request.ts index a93ee6edb2..54b29c9be9 100644 --- a/fine-uploader/test/request.ts +++ b/fine-uploader/test/request.ts @@ -1,13 +1,11 @@ -/// - function requestTest() { - type CustomHeader = { + interface CustomHeader { customHeader: string; - }; + } - type CustomParam = { + interface CustomParam { customParam: boolean; - }; + } const requestOptions: qq.RequestOptions = { customHeaders: { diff --git a/fine-uploader/test/resume.ts b/fine-uploader/test/resume.ts index 2b4d475bc0..dc588d19f5 100644 --- a/fine-uploader/test/resume.ts +++ b/fine-uploader/test/resume.ts @@ -1,5 +1,3 @@ -/// - function resumeTest() { const resumeOptions: qq.ResumeOptions = { recordsExpireIn: 10, diff --git a/fine-uploader/test/retry.ts b/fine-uploader/test/retry.ts index 6b94b93002..85c9f71af3 100644 --- a/fine-uploader/test/retry.ts +++ b/fine-uploader/test/retry.ts @@ -1,5 +1,3 @@ -/// - function retryTest() { const retryOptions: qq.RetryOptions = { diff --git a/fine-uploader/test/scaling.ts b/fine-uploader/test/scaling.ts index e57089d103..5e8ff3dc51 100644 --- a/fine-uploader/test/scaling.ts +++ b/fine-uploader/test/scaling.ts @@ -1,5 +1,3 @@ -/// - function scalingTest() { const scalingOptions: qq.ScalingOptions = { customResizer: (blob, height, image, sourceCanvas, targetCanvas, width) => { diff --git a/fine-uploader/test/session.ts b/fine-uploader/test/session.ts index 9728c657b5..7d8d6069b9 100644 --- a/fine-uploader/test/session.ts +++ b/fine-uploader/test/session.ts @@ -1,13 +1,11 @@ -/// - function sessionTest() { - type CustomHeader = { + interface CustomHeader { customHeader: string; - }; + } - type CustomParam = { + interface CustomParam { customParam: boolean; - }; + } const sessionOptions: qq.SessionOptions = { customHeaders: { diff --git a/fine-uploader/test/text.ts b/fine-uploader/test/text.ts index 4b52a96570..e83ddb4bcf 100644 --- a/fine-uploader/test/text.ts +++ b/fine-uploader/test/text.ts @@ -1,5 +1,3 @@ -/// - function textTest() { const textOptions: qq.TextOptions = { defaultResponseError: "you have failed me for the last time", diff --git a/fine-uploader/test/validation.ts b/fine-uploader/test/validation.ts index b6400d44b8..60324157f9 100644 --- a/fine-uploader/test/validation.ts +++ b/fine-uploader/test/validation.ts @@ -1,5 +1,3 @@ -/// - function validationTest() { const validationOptions: qq.ValidationOptions = { diff --git a/fine-uploader/test/workarounds.ts b/fine-uploader/test/workarounds.ts index 2acfac455b..42fa5ceee7 100644 --- a/fine-uploader/test/workarounds.ts +++ b/fine-uploader/test/workarounds.ts @@ -1,5 +1,3 @@ -/// - function workaroundsTest() { const workaroundOptions: qq.WorkaroundOptions = { iosEmptyVideos: false, diff --git a/forever-monitor/forever-monitor-tests.ts b/forever-monitor/forever-monitor-tests.ts index e44a9c35b0..bc3c9a29f9 100644 --- a/forever-monitor/forever-monitor-tests.ts +++ b/forever-monitor/forever-monitor-tests.ts @@ -12,7 +12,7 @@ const child = new (forever.Monitor)('your-filename.js', { args: [] }); -child.on('exit', function() { +child.on('exit', () => { console.log('your-filename.js has exited after 3 restarts'); }); @@ -20,4 +20,4 @@ child.start() .on("start", () => console.log("started")) .restart() .stop() - .on("exit", () => console.log("STOPPED")) + .on("exit", () => console.log("STOPPED")); diff --git a/forever-monitor/tsconfig.json b/forever-monitor/tsconfig.json index 8c6d4986b5..e0d7d1d5ee 100644 --- a/forever-monitor/tsconfig.json +++ b/forever-monitor/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "forever-monitor-tests.ts" ] -} +} \ No newline at end of file diff --git a/format-unicorn/tslint.json b/format-unicorn/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/format-unicorn/tslint.json +++ b/format-unicorn/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/fs-promise/fs-promise-tests.ts b/fs-promise/fs-promise-tests.ts index a90ae03804..43decbd256 100644 --- a/fs-promise/fs-promise-tests.ts +++ b/fs-promise/fs-promise-tests.ts @@ -34,8 +34,8 @@ async function test() { await fs.move(src, dst); await fs.outputFile(path, "test"); await fs.outputFile(path, "test", writeOptions); - await fs.outputFile(path, new Buffer([1,2])); - await fs.outputFile(path, new Buffer([1,2]), writeOptions); + await fs.outputFile(path, new Buffer([1, 2])); + await fs.outputFile(path, new Buffer([1, 2]), writeOptions); await fs.outputJson(path, data); await fs.outputJson(path, data, writeJsonOptions); await fs.outputJSON(path, data, writeJsonOptions); @@ -43,7 +43,7 @@ async function test() { json = await fs.readJson(path, readJsonOptions); json = await fs.readJSON(path, readJsonOptions); await fs.remove(path); - let dirs: string[] = await fs.walk(dir); + const dirs: string[] = await fs.walk(dir); await fs.writeJson(path, data); await fs.writeJson(path, data, writeJsonOptions); await fs.writeJSON(path, data, writeJsonOptions); diff --git a/fullcalendar/fullcalendar-tests.ts b/fullcalendar/fullcalendar-tests.ts index 0303dc7f75..7640c85db6 100644 --- a/fullcalendar/fullcalendar-tests.ts +++ b/fullcalendar/fullcalendar-tests.ts @@ -13,7 +13,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - dayClick: function () { + dayClick() { alert('a day has been clicked!'); } }); @@ -68,13 +68,13 @@ $('#calendar').fullCalendar({ $('#calendar').fullCalendar('option', 'aspectRatio', 1.8); $('#calendar').fullCalendar({ - viewRender: function (view) { + viewRender(view) { alert('The new title of the view is ' + view.title); } }); $('#calendar').fullCalendar({ - windowResize: function (view) { + windowResize(view) { alert('The calendar has adjusted to a window resize'); } }); @@ -88,7 +88,7 @@ $('#calendar').fullCalendar({ var view = $('#calendar').fullCalendar('getView'); alert("The view's title is " + view.title); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -152,7 +152,7 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -217,7 +217,7 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -271,7 +271,7 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -336,7 +336,7 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -390,21 +390,21 @@ $(document).ready(function () { }); -$('#my-prev-button').click(function () { +$('#my-prev-button').click(() => { $('#calendar').fullCalendar('prev'); }); -$('#my-next-button').click(function () { +$('#my-next-button').click(() => { $('#calendar').fullCalendar('next'); }); -$('#my-today-button').click(function () { +$('#my-today-button').click(() => { $('#calendar').fullCalendar('today'); }); $('#calendar').fullCalendar('gotoDate', 1, 0, 1); -$('#my-button').click(function () { +$('#my-button').click(() => { var d = $('#calendar').fullCalendar('getDate'); alert("The current date of the calendar is " + d); }); @@ -429,7 +429,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - dayClick: function (date, allDay, jsEvent, view) { + dayClick(date, allDay, jsEvent, view) { if (allDay) { alert('Clicked on the entire day: ' + date); @@ -448,7 +448,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - eventClick: function (calEvent, jsEvent, view) { + eventClick(calEvent, jsEvent, view) { alert('Event: ' + calEvent.title); alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY); @@ -469,7 +469,7 @@ $('#calendar').fullCalendar({ } // other events here ], - eventClick: function (event) { + eventClick(event) { if (event.url) { window.open(event.url); return false; @@ -489,7 +489,7 @@ $('#calendar').fullCalendar({ custom_param1: 'something', custom_param2: 'somethingelse' }, - error: function () { + error() { alert('there was an error while fetching events!'); }, color: 'yellow', // a non-ajax option @@ -511,7 +511,7 @@ $('#calendar').fullCalendar({ custom_param1: 'something', custom_param2: 'somethingelse' }, - error: function () { + error() { alert('there was an error while fetching events!'); }, color: 'yellow', // a non-ajax option @@ -601,7 +601,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - events: function (start: moment.Moment, end: moment.Moment, timezone: string | boolean, callback: (events: FullCalendar.EventObject[]) => void) { + events(start: moment.Moment, end: moment.Moment, timezone: string | boolean, callback: (events: FullCalendar.EventObject[]) => void) { $.ajax({ url: 'myxmlfeed.php', dataType: 'xml', @@ -610,9 +610,9 @@ $('#calendar').fullCalendar({ start: Math.round(start.toDate().getTime() / 1000), end: Math.round(end.toDate().getTime() / 1000) }, - success: function (doc) { + success(doc) { var events: any[] = []; - $(doc).find('event').each(function () { + $(doc).find('event').each(() => { events.push({ title: $(this).attr('title'), start: $(this).attr('start') // will be parsed @@ -630,7 +630,7 @@ $('#calendar').fullCalendar({ // your event source { - events: function (start: moment.Moment, end: moment.Moment, timezone: string | boolean, callback: (events: FullCalendar.EventObject[]) => void) { + events(start: moment.Moment, end: moment.Moment, timezone: string | boolean, callback: (events: FullCalendar.EventObject[]) => void) { // ... }, color: 'yellow', // an option! @@ -651,7 +651,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - eventClick: function (event, element) { + eventClick(event, element) { event.title = "CLICKED!"; @@ -683,7 +683,7 @@ $('#calendar').fullCalendar({ } // more events here ], - eventRender: function (event: EventWithDescription, element: any, view: any) { + eventRender(event: EventWithDescription, element: any, view: any) { element.qtip({ content: event.description }); @@ -696,7 +696,7 @@ $('#my-draggable').draggable({ $('#calendar').fullCalendar({ droppable: true, - drop: function (date, allDay) { + drop(date, allDay) { alert("Dropped on " + date + " with allDay=" + allDay); } }); @@ -704,7 +704,7 @@ $('#calendar').fullCalendar({ $('#calendar').fullCalendar({ droppable: true, dropAccept: '.cool-event', - drop: function () { + drop() { alert('dropped!'); } }); @@ -712,7 +712,7 @@ $('#calendar').fullCalendar({ $('#draggable1').draggable(); $('#draggable2').draggable(); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -777,10 +777,10 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { /* initialize the external events -----------------------------------------------------------------*/ - $('#external-events div.external-event').each(function () { + $('#external-events div.external-event').each(() => { // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/) // it doesn't need to have a start or end @@ -810,7 +810,7 @@ $(document).ready(function () { }, editable: true, droppable: true, // this allows things to be dropped onto the calendar !!! - drop: function (date, allDay) { // this function is called when something is dropped + drop(date, allDay) { // this function is called when something is dropped // retrieve the dropped element's stored Event Object var originalEventObject = $(this).data('eventObject'); diff --git a/fullcalendar/index.d.ts b/fullcalendar/index.d.ts index 7d0945bb4c..5d6401b9df 100644 --- a/fullcalendar/index.d.ts +++ b/fullcalendar/index.d.ts @@ -1,10 +1,9 @@ -// Type definitions for FullCalendar 2.7.2 +// Type definitions for FullCalendar 2.7 // Project: http://fullcalendar.io/ // Definitions by: Neil Stalker , Marcelo Camargo , Patrick Niemann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// import * as moment from 'moment'; @@ -20,7 +19,7 @@ export interface Calendar { export interface BusinessHours { start: moment.Duration | string | Date; end: moment.Duration | string | Date; - dow: Array; + dow: number[]; } export interface Timespan { @@ -50,7 +49,7 @@ export interface Options extends AgendaOptions, EventDraggingResizingOptions, Dr weekMode?: string; weekNumbers?: boolean; weekNumberCalculation?: any; // String/Function - businessHours?: boolean | BusinessHours | Array; + businessHours?: boolean | BusinessHours | BusinessHours[]; height?: number; contentHeight?: number; aspectRatio?: number; @@ -83,10 +82,10 @@ export interface Options extends AgendaOptions, EventDraggingResizingOptions, Dr titleFormat?: any; // String buttonText?: ButtonTextObject; - monthNames?: Array; - monthNamesShort?: Array; - dayNames?: Array; - dayNamesShort?: Array; + monthNames?: string[]; + monthNamesShort?: string[]; + dayNames?: string[]; + dayNamesShort?: string[]; weekNumberTitle?: string; // Clicking & Hovering - http://fullcalendar.io/docs/mouse/ @@ -136,13 +135,13 @@ export interface Options extends AgendaOptions, EventDraggingResizingOptions, Dr eventAfterAllRender?: (view: ViewObject) => void; eventDestroy?: (event: EventObject, element: JQuery, view: ViewObject) => void; - //scheduler options - resourceAreaWidth?:number, - schedulerLicenseKey?:string, - customButtons?:any, - resourceLabelText?:any, - resourceColumns?:any, - displayEventTime?:any, + // scheduler options + resourceAreaWidth?: number; + schedulerLicenseKey?: string; + customButtons?: any; + resourceLabelText?: any; + resourceColumns?: any; + displayEventTime?: any; } /** @@ -218,7 +217,7 @@ export interface EventObject extends Timespan { title: string; allDay?: boolean; url?: string; - className?: string | Array; + className?: string | string[]; editable?: boolean; startEditable?: boolean; durationEditable?: boolean; @@ -253,7 +252,7 @@ export interface EventSource extends JQueryAjaxSettings { backgroundColor?: string; borderColor?: string; textColor?: string; - className?: any; // string/Array + className?: any; // string/string[] editable?: boolean; allDayDefault?: boolean; ignoreTimezone?: boolean; @@ -366,17 +365,17 @@ declare global { /** * Reports changes for multiple events and renders them on the calendar. */ - fullCalendar(method: 'updateEvents', events: Array): void; + fullCalendar(method: 'updateEvents', events: EventObject[]): void; /** * Retrieves events that FullCalendar has in memory. */ - fullCalendar(method: 'clientEvents', idOrfilter?: any): Array; + fullCalendar(method: 'clientEvents', idOrfilter?: any): EventObject[]; /** * Retrieves events that FullCalendar has in memory. */ - fullCalendar(method: 'clientEvents', idOrfilter?: (e: EventObject) => boolean): Array; + fullCalendar(method: 'clientEvents', idOrfilter?: (e: EventObject) => boolean): EventObject[]; /** * Removes events from the calendar. @@ -407,11 +406,11 @@ declare global { * Renders a new event on the calendar. */ fullCalendar(method: 'renderEvent', event: EventObject, stick?: boolean): void; - + /** * Renders new events on the calendar. */ - fullCalendar(method: 'renderEvents', events: Array, stick?: boolean): void; + fullCalendar(method: 'renderEvents', events: EventObject[], stick?: boolean): void; /** * Rerenders all events on the calendar. diff --git a/fullcalendar/tslint.json b/fullcalendar/tslint.json new file mode 100644 index 0000000000..fe03bea79d --- /dev/null +++ b/fullcalendar/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false, + "unified-signatures": false + } +} diff --git a/fullcalendar/v1/fullcalendar-tests.ts b/fullcalendar/v1/fullcalendar-tests.ts index 4cec7039de..56a9eb0024 100644 --- a/fullcalendar/v1/fullcalendar-tests.ts +++ b/fullcalendar/v1/fullcalendar-tests.ts @@ -11,7 +11,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - dayClick: function () { + dayClick: () => { alert('a day has been clicked!'); } }); @@ -66,13 +66,13 @@ $('#calendar').fullCalendar({ $('#calendar').fullCalendar('option', 'aspectRatio', 1.8); $('#calendar').fullCalendar({ - viewRender: function (view) { + viewRender: view => { alert('The new title of the view is ' + view.title); } }); $('#calendar').fullCalendar({ - windowResize: function (view) { + windowResize: view => { alert('The calendar has adjusted to a window resize'); } }); @@ -86,7 +86,7 @@ $('#calendar').fullCalendar({ var view = $('#calendar').fullCalendar('getView'); alert("The view's title is " + view.title); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -150,7 +150,7 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -215,7 +215,7 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -269,7 +269,7 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -334,7 +334,7 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -388,21 +388,21 @@ $(document).ready(function () { }); -$('#my-prev-button').click(function () { +$('#my-prev-button').click(() => { $('#calendar').fullCalendar('prev'); }); -$('#my-next-button').click(function () { +$('#my-next-button').click(() => { $('#calendar').fullCalendar('next'); }); -$('#my-today-button').click(function () { +$('#my-today-button').click(() => { $('#calendar').fullCalendar('today'); }); $('#calendar').fullCalendar('gotoDate', 1, 0, 1); -$('#my-button').click(function () { +$('#my-button').click(() => { var d = $('#calendar').fullCalendar('getDate'); alert("The current date of the calendar is " + d); }); @@ -427,7 +427,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - dayClick: function (date, allDay, jsEvent, view) { + dayClick(date, allDay, jsEvent, view) { if (allDay) { alert('Clicked on the entire day: ' + date); @@ -446,7 +446,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - eventClick: function (calEvent, jsEvent, view) { + eventClick(calEvent, jsEvent, view) { alert('Event: ' + calEvent.title); alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY); @@ -467,7 +467,7 @@ $('#calendar').fullCalendar({ } // other events here ], - eventClick: function (event) { + eventClick(event) { if (event.url) { window.open(event.url); return false; @@ -487,7 +487,7 @@ $('#calendar').fullCalendar({ custom_param1: 'something', custom_param2: 'somethingelse' }, - error: function () { + error: () => { alert('there was an error while fetching events!'); }, color: 'yellow', // a non-ajax option @@ -509,7 +509,7 @@ $('#calendar').fullCalendar({ custom_param1: 'something', custom_param2: 'somethingelse' }, - error: function () { + error: () => { alert('there was an error while fetching events!'); }, color: 'yellow', // a non-ajax option @@ -599,7 +599,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - events: function (start: any, end: any, callback: any) { + events(start: any, end: any, callback: any) { $.ajax({ url: 'myxmlfeed.php', dataType: 'xml', @@ -608,9 +608,9 @@ $('#calendar').fullCalendar({ start: Math.round(start.getTime() / 1000), end: Math.round(end.getTime() / 1000) }, - success: function (doc) { + success(doc) { var events: any[] = []; - $(doc).find('event').each(function () { + $(doc).find('event').each(() => { events.push({ title: $(this).attr('title'), start: $(this).attr('start') // will be parsed @@ -628,7 +628,7 @@ $('#calendar').fullCalendar({ // your event source { - events: function (start: any, end: any, callback: any) { + events(start: any, end: any, callback: any) { // ... }, color: 'yellow', // an option! @@ -649,7 +649,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - eventClick: function (event, element) { + eventClick(event, element) { event.title = "CLICKED!"; @@ -681,7 +681,7 @@ $('#calendar').fullCalendar({ } // more events here ], - eventRender: function (event: EventWithDescription, element: any) { + eventRender(event: EventWithDescription, element: any) { element.qtip({ content: event.description }); @@ -694,7 +694,7 @@ $('#my-draggable').draggable({ $('#calendar').fullCalendar({ droppable: true, - drop: function (date, allDay) { + drop(date, allDay) { alert("Dropped on " + date + " with allDay=" + allDay); } }); @@ -702,7 +702,7 @@ $('#calendar').fullCalendar({ $('#calendar').fullCalendar({ droppable: true, dropAccept: '.cool-event', - drop: function () { + drop: () => { alert('dropped!'); } }); @@ -710,7 +710,7 @@ $('#calendar').fullCalendar({ $('#draggable1').draggable(); $('#draggable2').draggable(); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -775,10 +775,10 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { /* initialize the external events -----------------------------------------------------------------*/ - $('#external-events div.external-event').each(function () { + $('#external-events div.external-event').each(() => { // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/) // it doesn't need to have a start or end @@ -808,7 +808,7 @@ $(document).ready(function () { }, editable: true, droppable: true, // this allows things to be dropped onto the calendar !!! - drop: function (date, allDay) { // this function is called when something is dropped + drop(date, allDay) { // this function is called when something is dropped // retrieve the dropped element's stored Event Object var originalEventObject = $(this).data('eventObject'); diff --git a/fullcalendar/v1/tslint.json b/fullcalendar/v1/tslint.json index 7d876390fe..fe03bea79d 100644 --- a/fullcalendar/v1/tslint.json +++ b/fullcalendar/v1/tslint.json @@ -1,7 +1,7 @@ { - "extends": "../../tslint.json", + "extends": "../tslint.json", "rules": { "forbidden-types": false, "unified-signatures": false } -} \ No newline at end of file +} diff --git a/fusioncharts/fusioncharts-tests.ts b/fusioncharts/fusioncharts-tests.ts index 77b912ba18..af71a2378a 100644 --- a/fusioncharts/fusioncharts-tests.ts +++ b/fusioncharts/fusioncharts-tests.ts @@ -1,51 +1,51 @@ import * as FusionCharts from "fusioncharts"; -FusionCharts.addEventListener('ready',(eventObject)=>{ +FusionCharts.addEventListener('ready', (eventObject) => { eventObject.stopPropagation(); }); -FusionCharts.ready((fusioncharts)=>{ +FusionCharts.ready((fusioncharts) => { }); FusionCharts.version; -FusionCharts('chartId').render();; +FusionCharts('chartId').render(); FusionCharts["debugger"].enable(true); -let chartData ={ +const chartData = { type: 'column2d', renderAt: 'chart-container', width: '450', height: '200', dataFormat: 'json', dataSource: { - "chart": { - "caption": "Monthly revenue for last year", - "subCaption": "Harry's SuperMart", + chart: { + caption: "Monthly revenue for last year", + subCaption: "Harry's SuperMart", }, - "data": [{ - "label": "Jan", - "value": "420000" + data: [{ + label: "Jan", + value: "420000" }, { - "label": "Feb", - "value": "810000" + label: "Feb", + value: "810000" } ] } }; -let chart = new FusionCharts(chartData); +const chart = new FusionCharts(chartData); chart.render(); chart.isActive(); -chart.addEventListener('ready',function(eventObject){ +chart.addEventListener('ready', eventObject => { eventObject.type; }); chart.chartType(); chart.addVariable(); chart.clone(); -chart.zoomTo(0,3); +chart.zoomTo(0, 3); chart.zoomOut(); chart.setJSONData(chartData); chart.ref; \ No newline at end of file diff --git a/gaea-model/gaea-model-tests.ts b/gaea-model/gaea-model-tests.ts deleted file mode 100644 index 1615c039e8..0000000000 --- a/gaea-model/gaea-model-tests.ts +++ /dev/null @@ -1,8 +0,0 @@ -function nameSpaceTest() { - let components = {} as GaeaModel.ViewportComponentInfo - // insert into parent - components.props = { - gaeaUniqueKey: '123', - gaeaName: 'componentName' - } -} \ No newline at end of file diff --git a/gaea-model/index.d.ts b/gaea-model/index.d.ts deleted file mode 100644 index ec2ebe9976..0000000000 --- a/gaea-model/index.d.ts +++ /dev/null @@ -1,493 +0,0 @@ -// Type definitions for gaea-model 1.0 -// Project: https://github.com/ascoders/gaea-model -// Definitions by: ascoders -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 - -import * as React from 'react'; - -export as namespace GaeaModel; - -export type Component = React.ComponentClass; - -/** - * 组件信息 - */ -export interface ComponentProps extends React.HTMLProps { - /** - * 唯一的 key,用来唯一标识这个组件,所有盖亚内部组件都以 gaea-old- 为前缀 - */ - gaeaUniqueKey: string; - /** - * 组件的中文名 - */ - gaeaName: string; - /** - * 组件图标,为 fontAwesome - */ - gaeaIcon?: string; - /** - * 编辑信息 - */ - gaeaEdit?: ComponentPropsGaeaEdit[]; - /** - * 事件定义 - */ - gaeaEvent?: GaeaEvent; - /** - * 是否在预览模式,preivew 会传入 true - */ - gaeaPreview?: boolean; - /** - * 是否可以拖入子元素 - */ - canDragIn?: boolean; - /** - * 存储事件设置 - */ - gaeaEventData?: EventData[]; - /** - * 存储native事件设置 - */ - gaeaNativeEventData?: EventData[]; - /** - * 存储变量信息 - */ - gaeaVariables?: { - [field: string]: VariableData; - }; - - [x: string]: any; -} - -/** - * 组件配置中数组配置 - */ -export interface ComponentPropsOptionsArray extends ComponentPropsGaeaEdit { - key: string; -} - -/** - * 组件配置中数组配置的值 - */ -export interface ComponentPropsOptionsArrayValue { - /** - * ComponentPropsOptionsArray 设置的 key - */ - key: string; - /** - * 用户填入的值 - */ - value: number | string; -} - -/** - * 组件配置 选择器配置 - */ -export interface ComponentPropsOptionsSelector { - key: string; - value: string; -} - -/** - * number 配置项 - */ -export interface Number { - // 为空时,是数字,否则会以字符串加后缀形式赋值 - key: string; - value: string; -} - -/** - * 组件的值 - */ -export type ComponentPropsOptionValue = number | string | boolean | ComponentPropsOptionsArrayValue[] | any; - -/** - * 组件配置 - */ -export interface ComponentPropsGaeaEdit { - /** - * 对应字段名 - */ - field: string; - /** - * 选项名称 - */ - label: string; - /** - * 编辑器类型 - */ - editor: string; - /** - * 是否可被编辑 - */ - editable: boolean; - /** - * 是否隐藏编辑工具 - */ - hideTool: boolean; - /** - * 当 editor 为 array 时的数组配置 - * 数组中的 key,和填入的值,会作为 Array 填入到 value 中 - */ - array?: ComponentPropsOptionsArrayValue[]; - /** - * 当 editor 为 selector 时的数组配置 - */ - selector?: ComponentPropsOptionsSelector[]; - /** - * 值类型, 默认为字符串 - */ - type?: string; - /** - * 为空时的值,默认为 null - */ - emptyValue?: any; - /** - * 控制 number 单位 - */ - number?: { - units: number[]; - currentUnit: string; - max?: number; - min?: number; - step?: number; - speed?: number; - inputRange?: number[]; - outputRange?: number[]; - slider?: boolean; - }; - /** - * 枚举实例 - */ - instance?: Array<{ - [key: string]: ComponentPropsOptionValue; - }>; -} - -/** - * 组合信息 - */ -export interface ComboComponentInfo extends ViewportComponentFullInfo { - // 组合名 - name: string; -} - -/** - * 获取发布列表的返回值 - */ -export interface GetPublishListResult { - // 版本 - version: string; - // 描述 - description: string; -} - -/** - * 版本信息 - */ -export interface VersionInfo { - content: string; -} - -/** - * 事件设置 - */ -export interface GaeaEvent { - triggers: EventTriggerCondition[]; - effects: EventAction[]; -} - -export interface EventData { - type: string; - event: string; - /** - * 因为事件可能 type 相同,因此记录是第几个 - */ - typeIndex: number; - eventIndex: number; - typeData?: EventTriggerEvent; - eventData?: EventActionJumpUrl | EventActionCall | EventActionEvent; -} - -export interface EventTriggerCondition { - name: string; - // 触发类型 - type: string; - // 是否由自己的生命周期触发 - selfCallback?: boolean; -} - -export interface EventAction { - name: string; - // 动作类型 - // call: 调用传进来的方法 - // jumpUrl: 跳转一个网址 - type: string; - call?: EventCallType; -} - -/** - * 事件定义类型 - */ -export interface EventCallType { - // 调用函数名称 - functionName: string; - // 调用参数 - param?: EventCallTypeParam[]; -} - -export interface EventCallTypeParam { - label: string; - field: string; - editor: string; // text -} - -/** - * 事件触发数据类型 - */ -export interface EventTriggerEvent { - listen?: string; -} - -export interface EventUpdatePropsEvent { - /** - * 修改后的 props - */ - props: ComponentProps; -} - -/** - * 事件动作数据类型 - */ -export interface EventActionJumpUrl { - url?: string; -} - -export interface EventActionCall { - // 函数在 map 里的 key - key?: string; -} - -export interface EventActionEvent { - emit?: string; -} - -export interface ExternalParameter { - /** - * 名称 - */ - name: string; - /** - * 类型 - * number string boolean - */ - type: string; -} - -/** - * 标识哪些字段用什么变量 - */ -export interface VariableData { - // 变量类型 - // 比如是外部传参,还是全局变量 - variableType: string; - // 变量的哪个字段 - variableField: string; - // 值类型 string number boolean - valueType: string; -} - -/** - * 插件信息 - */ -export interface Plugin extends React.ComponentClass { - // 插件安放位置 - position: string; - Action?: any; - Store?: any; -} - -/******************************************************************************************************** - * DIff - ********************************************************************************************************/ -export interface Diff { - // 操作类型 - type: 'add' | 'move' | 'remove' | 'exchange' | 'update' | 'paste' | 'reset' | 'addCombo' | 'addSource'; - // 操作组件的 mapUniqueKey - mapUniqueKey: string; - // 新增操作 - add?: { - // 新增组件的唯一标识 id - uniqueId: string; - // 父级 mapKey - parentMapUniqueKey: string; - // 插入的位置 - index: number; - }; - // 移动到另一个父元素 - move?: { - // 移动到的父级 mapKey - targetParentMapUniqueKey: string; - // 移动前父级 mapKey - sourceParentMapUniqueKey: string; - // 插入的位置 - targetIndex: number; - // 移除的位置 - sourceIndex: number; - }; - // 删除组件 - remove?: DiffRemove; - // 内部交换顺序 - exchange?: { - oldIndex: number; - newIndex: number; - }; - // 更新操作 - update?: { - oldValue: ComponentProps; - newValue: ComponentProps; - }; - // 粘贴操作 - paste?: DiffRemove; - // 重置组件 - reset?: { - // 重置前的信息 - beforeProps: ComponentProps; - beforeName: string; - }; - // 新增组合 - addCombo?: { - // 父级 mapKey - parentMapUniqueKey: string; - // 父级的 index - index: number; - // 组合的完整信息(不是 copy 的, 是真正对应的 mapUniqueKey) - componentInfo: ViewportComponentFullInfo; - }; - // 新增模板 - addSource?: { - // 父级 mapKey - parentMapUniqueKey: string; - // 父级的 index - index: number; - // 组合的完整信息(不是 copy 的, 是真正对应的 mapUniqueKey) - componentInfo: ViewportComponentFullInfo; - }; -} - -export interface DiffRemove extends ViewportComponentFullInfo { - // 父级元素 mapKey - parentMapUniqueKey: string; - // 删除的位置 - index: number; -} - -/******************************************************************************************************** - * Viewport - ********************************************************************************************************/ -/** - * 在视图中的组件属性 - */ -export interface ViewportComponentInfo { - /** - * props - */ - props: ComponentProps; - /** - * 子元素(canDragIn才有) - * 只存子元素在 map 中的 key - */ - layoutChilds?: string[]; - /** - * 父级 mapUniqueKey, 这样不但方便寻找父级,还能根据是否为 null 判断是否为根元素 - */ - parentMapUniqueKey: string; -} - -/** - * 当前正在移动元素的信息 - */ -export interface MovingComponent { - // 在编辑区域的组件信息 - mapUniqueKey: string; - // 是否是新拖拽的 - isNew: boolean; - // 组件的唯一标识, 新建的时候采用 - uniqueKey: string; - // 直接给 source 就直接用 - source: string; -} - -/** - * hover 元素的信息 - */ -export interface HoverComponentSpec { - left: number; - top: number; - width: number; - height: number; - hovering: boolean; -} - -/** - * 一个独立组件的完整信息 - */ -export interface ViewportComponentFullInfo { - // 组件的 mapUniqueKey - mapUniqueKey: string; - // 组件信息 - componentInfo: ViewportComponentInfo; - // 子元素列表 (包括非直接子集) - childs: { - [mapUniqueKey: string]: ViewportComponentInfo; - }; -} - -/** - * 当前拖拽元素信息 - */ -export interface CurrentDragComponentInfo { - // 类型 - type: 'new' | 'combo' | 'viewport'; - // 开始拖拽父级的 dom - dragStartParentElement: HTMLElement; - // 开始拖拽在父级中的位置 - dragStartIndex: number; - newInfo?: { - // 唯一 key,用来实例化组件 - uniqueKey: string; - }; - comboInfo?: { - // combo 信息 - source: string; - }; - viewportInfo?: { - // 当前拖拽组件的 mapUniqueKey - mapUniqueKey: string; - // 拖拽目标的 mapUniqueKey - targetMapUniqueKey?: string; - // 拖拽目标的 index - targetIndex?: number; - }; -} - -/******************************************************************************************************** - * Event - ********************************************************************************************************/ -/** - * 鼠标移动到组件上/树对应的组件上 - */ -export interface MouseHoverComponentEvent { - mapUniqueKey: string; - type: string; -} - -/** - * 修改某个组件选中状态 - */ -export interface ComponentSelectStatusEvent { - mapUniqueKey: string; - selected: boolean; -} diff --git a/gapi.auth2/gapi.auth2-tests.ts b/gapi.auth2/gapi.auth2-tests.ts index 2cfaa49980..621ca6f056 100644 --- a/gapi.auth2/gapi.auth2-tests.ts +++ b/gapi.auth2/gapi.auth2-tests.ts @@ -19,6 +19,22 @@ function test_getAuthInstance(){ var auth = gapi.auth2.getAuthInstance(); } +function test_signIn(){ + gapi.auth2.getAuthInstance().signIn({ + scope: 'email profile', + prompt: 'content' + }); +} + +function test_signInOptionsBuild(){ + var options = new gapi.auth2.SigninOptionsBuilder(); + options.setAppPackageName('com.example.app'); + options.setFetchBasicProfile(true); + options.setPrompt('select_account'); + options.setScope('profile').setScope('email'); + gapi.auth2.getAuthInstance().signIn(options); +} + function test_getAuthResponse(){ var user = gapi.auth2.getAuthInstance().currentUser.get(); var authResponse = user.getAuthResponse(); diff --git a/gapi.auth2/index.d.ts b/gapi.auth2/index.d.ts index 6037f0238e..6146a87e28 100644 --- a/gapi.auth2/index.d.ts +++ b/gapi.auth2/index.d.ts @@ -31,12 +31,7 @@ declare namespace gapi.auth2 { /** * Signs in the user using the specified options. */ - signIn(options?: { - app_package_name?: string; - fetch_basic_profile?: boolean; - prompt?: boolean; - scope?: string; - }, optionBuilder?: SigninOptionsBuilder): any; + signIn(options?: SigninOptions | SigninOptionsBuilder): any; /** * Signs out all accounts from the application. @@ -59,12 +54,8 @@ declare namespace gapi.auth2 { /** * Attaches the sign-in flow to the specified container's click handler. */ - attachClickHandler(container: any, options: { - app_package_name?: string; - fetch_basic_profile?: boolean; - prompt?: boolean; - scope?: string; - }, onsuccess: (googleUser: GoogleUser) => any, onfailure: (reason: string) => any): any; + attachClickHandler(container: any, options: SigninOptions, + onsuccess: (googleUser: GoogleUser) => any, onfailure: (reason: string) => any): any; } export interface IsSignedIn{ @@ -93,6 +84,32 @@ declare namespace gapi.auth2 { listen(listener: (user: GoogleUser) => any): void; } + export interface SigninOptions { + /** + * The package name of the Android app to install over the air. + * See Android app installs from your web site: + * https://developers.google.com/identity/sign-in/web/android-app-installs + */ + app_package_name?: string; + /** + * Fetch users' basic profile information when they sign in. + * Adds 'profile', 'email' and 'openid' to the requested scopes. + * True if unspecified. + */ + fetch_basic_profile?: boolean; + /** + * Specifies whether to prompt the user for re-authentication. + * See OpenID Connect Request Parameters: + * https://openid.net/specs/openid-connect-basic-1_0.html#RequestParameters + */ + prompt?: string; + /** + * The scopes to request, as a space-delimited string. + * Optional if fetch_basic_profile is not set to false. + */ + scope?: string; + } + export class SigninOptionsBuilder { setAppPackageName(name: string): any; setFetchBasicProfile(fetch: boolean): any; @@ -164,22 +181,12 @@ declare namespace gapi.auth2 { * When you use GoogleUser.signIn(), the sign-in flow skips the account chooser step. * See GoogleAuth.signIn(). */ - signIn(options?: { - app_package_name?: string; - fetch_basic_profile?: boolean; - prompt?: boolean; - scope?: string; - }, optionBuilder?: SigninOptionsBuilder): any; + signIn(options?: SigninOptions | SigninOptionsBuilder): any; /** - * + * See GoogleUser.signIn() */ - grant(options?: { - app_package_name?: string; - fetch_basic_profile?: boolean; - prompt?: boolean; - scope?: string; - }, optionBuilder?: SigninOptionsBuilder): any; + grant(options?: SigninOptions | SigninOptionsBuilder): any; /** * Get permission from the user to access the specified scopes offline. diff --git a/geodesy/tslint.json b/geodesy/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/geodesy/tslint.json +++ b/geodesy/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/geojson/geojson-tests.ts b/geojson/geojson-tests.ts index fb9ce24a0b..42ae99ce47 100644 --- a/geojson/geojson-tests.ts +++ b/geojson/geojson-tests.ts @@ -119,7 +119,7 @@ let multiPolygon: GeoJSON.MultiPolygon = { let geometryCollection: GeoJSON.GeometryCollection = { type: "GeometryCollection", - "geometries": [ + geometries: [ { type: "Point", coordinates: [100.0, 0.0] diff --git a/geolib/geolib-tests.ts b/geolib/geolib-tests.ts index 5386bf730b..e69de29bb2 100644 --- a/geolib/geolib-tests.ts +++ b/geolib/geolib-tests.ts @@ -1,201 +0,0 @@ -import "geolib"; -import PositionAsDecimal = geolib.PositionAsDecimal; -import CompassDirection = geolib.CompassDirection; -import Distance = geolib.Distance; -import Bound = geolib.Bound; - -let dist: number = geolib.getDistance( - {latitude: 51.5103, longitude: 7.49347}, - {latitude: "51° 31' N", longitude: "7° 28' E"} -); - -dist = geolib.getDistance( - {latitude: 51.5103, longitude: 7.49347}, - {latitude: "51° 31' N", longitude: "7° 28' E"} -); - -dist = geolib.getDistance( - {latitude: 51.5103, longitude: 7.49347}, - {latitude: "51° 31' N", longitude: "7° 28' E"}, - 1, - 1 -); - -// Working with W3C Geolocation API -navigator.geolocation.getCurrentPosition( - function(position) { - alert('You are ' + geolib.getDistance(position.coords, { - latitude: 51.525, - longitude: 7.4575 - }) + ' meters away from 51.525, 7.4575'); - }, - function() { - alert('Position could not be determined.') - }, - { - enableHighAccuracy: true - } -); - - -dist = geolib.getDistanceSimple( - {latitude: 51.5103, longitude: 7.49347}, - {latitude: "51° 31' N", longitude: "7° 28' E"} -); - -dist = geolib.getDistanceSimple( - {latitude: 51.5103, longitude: 7.49347}, - {latitude: "51° 31' N", longitude: "7° 28' E"}, - 1 -); - -let posAsDecimal: PositionAsDecimal = geolib.getCenter([ - {latitude: 52.516272, longitude: 13.377722}, - {latitude: 51.515, longitude: 7.453619}, - {latitude: 51.503333, longitude: -0.119722} -]); - -posAsDecimal = geolib.getCenter([ - {latitude: 52.516272, longitude: 13.377722}, - {latitude: 51.515, longitude: 7.453619}, - {latitude: 51.503333, longitude: -0.119722} -]); - -posAsDecimal = geolib.getCenterOfBounds([ - {latitude: 52.516272, longitude: 13.377722}, - {latitude: 51.515, longitude: 7.453619}, - {latitude: 51.503333, longitude: -0.119722}, - {latitude: 51.503333, longitude: -1.119722} -]); - - - -let bound: Bound = geolib.getBounds([ - {latitude: 52.516272, longitude: 13.377722, elevation: 1}, - {latitude: 51.515, longitude: 7.453619, elevation: 1}, - {latitude: 51.503333, longitude: -0.119722, elevation: 1}]); - -let isInside: boolean = geolib.isPointInside( - {latitude: 51.5125, longitude: 7.485}, - [ - {latitude: 51.50, longitude: 7.40}, - {latitude: 51.555, longitude: 7.40}, - {latitude: 51.555, longitude: 7.625}, - {latitude: 51.5125, longitude: 7.625} - ] -); // -> true - -// checks if 51.525, 7.4575 is within a radius of 5km from 51.5175, 7.4678 -let boolResult: boolean = geolib.isPointInCircle( - {latitude: 51.525, longitude: 7.4575}, - {latitude: 51.5175, longitude: 7.4678}, - 5000 -); - -let bearing: number = geolib.getRhumbLineBearing( - {latitude: 52.518611, longitude: 13.408056}, - {latitude: 51.519475, longitude: 7.46694444} -); - -bearing = geolib.getBearing( - {latitude: 52.518611, longitude: 13.408056}, - {latitude: 51.519475, longitude: 7.46694444} -); - -let compassDirection: CompassDirection = geolib.getCompassDirection( - {latitude: 52.518611, longitude: 13.408056}, - {latitude: 51.519475, longitude: 7.46694444} -); - -compassDirection = geolib.getCompassDirection( - {latitude: 52.518611, longitude: 13.408056}, - {latitude: 51.519475, longitude: 7.46694444}, - 'circle' -); - -// coords array -let distanceArray: Distance[] = geolib.orderByDistance({latitude: 51.515, longitude: 7.453619}, [ - {latitude: 52.516272, longitude: 13.377722}, - {latitude: 51.518, longitude: 7.45425}, - {latitude: 51.503333, longitude: -0.119722} -]); - -// coords object -distanceArray = geolib.orderByDistance({latitude: 51.515, longitude: 7.453619}, [ - {latitude: 52.516272, longitude: 13.377722}, - {latitude: 51.518, longitude: 7.45425}, - {latitude: 51.503333, longitude: -0.119722} -]); - - -// in this case set offset to 1 otherwise the nearest point will always be your reference point -let posAsDecimalArray: Distance[] = geolib.findNearest( - {latitude: 51.515, longitude: 7.453619}, - [ - {latitude: 52.516272, longitude: 13.377722}, - {latitude: 51.515, longitude: 7.453619}, - {latitude: 51.503333, longitude: -0.119722}, - {latitude: 55.751667, longitude: 37.617778}, - {latitude: 48.8583, longitude: 2.2945}, - {latitude: 59.3275, longitude: 18.0675}, - {latitude: 59.916911, longitude: 10.727567} - ], 1); - - -// Calculate distance from Berlin via Dortmund to London -dist = geolib.getPathLength([ - {latitude: 52.516272, longitude: 13.377722}, // Berlin - {latitude: 51.515, longitude: 7.453619}, // Dortmund - {latitude: 51.503333, longitude: -0.119722} // London -]); // -> 945235 - -let speed: number = geolib.getSpeed( - [ - {latitude: 51.567294, longitude: 7.38896, time: 1360231200880}, - {latitude: 52.54944, longitude: 13.468509, time: 1360245600880} - ], - {unit: 'mph'} -); // -> 66.9408 (mph) - -speed= geolib.getSpeed( - [ - {latitude: 51.567294, longitude: 7.38896, time: 1360231200880}, - {latitude: 52.54944, longitude: 13.468509, time: 1360245600880} - ] -); // -> 66.9408 (mph) - -let point1 = {latitude: 0.5, longitude: 0}; -let point2 = {latitude: 0, longitude: 10}; -let point3 = {latitude: 0, longitude: 15.5}; -let start = {latitude: 0, longitude: 0}; -let end = {latitude: 0, longitude: 15}; - -let isInLine1 = geolib.isPointInLine(point1, start, end) //-> false; -let isInLine2 = geolib.isPointInLine(point2, start, end) //-> true; -let isInLine3 = geolib.isPointInLine(point3, start, end) //-> false; - - -let convertResult: number = geolib.convertUnit('km', 14213, 2) // -> 14,21 -convertResult = geolib.convertUnit('km', 14213) // -> 14,21 - -let result: number = geolib.sexagesimal2decimal("51° 29' 46\" N") - -let resultString: string = geolib.decimal2sexagesimal(51.49611111); // -> 51° 29' 46.00 - -result = geolib.latitude({lat: 51.49611, lng: 7.38896}); // -> 51.49611 -result = geolib.longitude({lat: 51.49611, lng: 7.38896}); // -> 7.38896 - -result = geolib.useDecimal("51° 29' 46\" N"); // -> 51.59611111 -result = geolib.useDecimal(51.59611111) // -> 51.59611111 - -result = geolib.elevation({lat: 51.49611, lng: 7.38896}); - -let initialPoint = {latitude: 51.516272, longitude: 0.45425} -let radius = 100; -dist = 1234; -bearing = 45; - - -posAsDecimal = geolib.computeDestinationPoint(initialPoint, dist, bearing); -posAsDecimal = geolib.computeDestinationPoint(initialPoint, dist, bearing, radius); -// -> {"latitude":51.52411853234181,"longitude":0.4668623365950795} diff --git a/geopattern/geopattern-tests.ts b/geopattern/geopattern-tests.ts index 96ea652028..957da81c20 100644 --- a/geopattern/geopattern-tests.ts +++ b/geopattern/geopattern-tests.ts @@ -1,4 +1,3 @@ -/// /// var pattern = GeoPattern.generate('GitHub'); diff --git a/get-stdin/get-stdin-tests.ts b/get-stdin/get-stdin-tests.ts index d5b720234f..d77dff5924 100644 --- a/get-stdin/get-stdin-tests.ts +++ b/get-stdin/get-stdin-tests.ts @@ -6,4 +6,4 @@ getStdin().then(str => { getStdin.buffer().then(buffer => { console.log("Length " + buffer.length + buffer.toString()); -}) \ No newline at end of file +}); diff --git a/globule/globule-tests.ts b/globule/globule-tests.ts index d0e1eb3ccb..78697ba199 100644 --- a/globule/globule-tests.ts +++ b/globule/globule-tests.ts @@ -18,9 +18,9 @@ bResult = globule.isMatch('*.js', '/home/code'); bResult = globule.isMatch('*.js', '/home/code', { matchBase: true }); let mappings = globule.mapping(['*.js']); -let len = mappings.length; -let src = mappings[0].src; -let dest = mappings[0].dest; +const len = mappings.length; +const src = mappings[0].src; +const dest = mappings[0].dest; mappings = globule.mapping(['*.js'], { srcBase: '/home/code' }); mappings = globule.mapping(['*.js', '*.less']); diff --git a/globule/index.d.ts b/globule/index.d.ts index 595a4d2aec..4add1d4461 100644 --- a/globule/index.d.ts +++ b/globule/index.d.ts @@ -61,22 +61,22 @@ interface GlobuleStatic { */ find(pattern: string, pattern2: string, pattern3: string | string[], options?: FindOptions): string[]; - /** + /** * Given a set of source file paths, returns an array of src-dest file mapping objects */ mapping(filepaths: string[], options?: MappingOptions): OneMapping[]; - /** + /** * Given a set of source file paths, returns an array of src-dest file mapping objects */ mapping(options: MappingOptions): OneMapping[]; - /** + /** * Given a set of source file paths, returns an array of src-dest file mapping objects */ mapping(filepaths: string[], filepaths2: string[], options?: MappingOptions): OneMapping[]; - /** + /** * Given a set of source file paths, returns an array of src-dest file mapping objects */ mapping(filepaths: string[], filepaths2: string[], filepaths3: string[], options?: MappingOptions): OneMapping[]; diff --git a/globule/tsconfig.json b/globule/tsconfig.json index ec155b8b0f..55317b01f8 100644 --- a/globule/tsconfig.json +++ b/globule/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, diff --git a/google.analytics/google.analytics-tests.ts b/google.analytics/google.analytics-tests.ts index 82533e4bdf..6b7962899b 100644 --- a/google.analytics/google.analytics-tests.ts +++ b/google.analytics/google.analytics-tests.ts @@ -3,13 +3,13 @@ describe("tester Google Analytics Tracker _gat object", () => { it("can set ga script element", () => { - gaClassic = document.createElement("script"); + gaClassic = document.createElement("script"); }); it("can set aync to true", () => { gaClassic.async = true; }); it("can set src to string url", () => { - gaClassic.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; + gaClassic.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; }); it("can set type", () => { gaClassic.type = 'text/javascript'; @@ -27,10 +27,10 @@ describe('UniversalAnalytics', () => { ga('send', {hitType: 'event', eventCategory: 'Videos', eventAction: 'play', eventLabel: 'Fall Campaign'}); ga('send', 'event', 'Videos', 'play', 'Fall Campaign', {nonInteraction: true}); ga('send', 'pageview', '/page'); - ga('send', 'social', {'socialNetwork': 'facebook', 'socialAction': 'like', 'socialTarget': 'http://foo.com'}); - ga('send', 'social', {'socialNetwork': 'google+', 'socialAction': 'plus', 'socialTarget': 'http://foo.com'}); - ga('send', 'timing', {'timingCategory': 'category', 'timingVar': 'lookup', 'timingValue': 123}); - ga('send', 'timing', {'timingCategory': 'category', 'timingVar': 'lookup', 'timingValue': 123, 'timingLabel': 'label'}); + ga('send', 'social', {socialNetwork: 'facebook', socialAction: 'like', socialTarget: 'http://foo.com'}); + ga('send', 'social', {socialNetwork: 'google+', socialAction: 'plus', socialTarget: 'http://foo.com'}); + ga('send', 'timing', {timingCategory: 'category', timingVar: 'lookup', timingValue: 123}); + ga('send', 'timing', {timingCategory: 'category', timingVar: 'lookup', timingValue: 123, timingLabel: 'label'}); ga('trackerName.send', 'event', 'load'); ga.create('UA-65432-1', 'auto'); diff --git a/google.analytics/index.d.ts b/google.analytics/index.d.ts index 68c1c627c1..0f86e0be40 100644 --- a/google.analytics/index.d.ts +++ b/google.analytics/index.d.ts @@ -87,7 +87,7 @@ declare namespace UniversalAnalytics { getAll(): UniversalAnalytics.Tracker[]; getByName(name: string): UniversalAnalytics.Tracker; - remove(name:string): void; + remove(name: string): void; } interface Tracker { diff --git a/google.analytics/tslint.json b/google.analytics/tslint.json new file mode 100644 index 0000000000..e8bc207e33 --- /dev/null +++ b/google.analytics/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "../tslint.json", + "rules": { + "dt-header": false, + "forbidden-types": false, + "unified-signatures": false + } +} diff --git a/googlemaps/index.d.ts b/googlemaps/index.d.ts index f94b29525c..06eba68a94 100644 --- a/googlemaps/index.d.ts +++ b/googlemaps/index.d.ts @@ -1758,9 +1758,15 @@ declare namespace google.maps { } export class TrafficLayer extends MVCObject { - constructor(); - getMap(): void; + constructor(opts?: TrafficLayerOptions); + getMap(): Map; setMap(map: Map): void; + setOptions(options: TrafficLayerOptions): void; + } + + export interface TrafficLayerOptions { + autoRefresh?: boolean; + map?: Map; } export class TransitLayer extends MVCObject { diff --git a/graphql-relay/graphql-relay-tests.ts b/graphql-relay/graphql-relay-tests.ts index f1b18a4521..723ffa393b 100644 --- a/graphql-relay/graphql-relay-tests.ts +++ b/graphql-relay/graphql-relay-tests.ts @@ -43,13 +43,13 @@ forwardConnectionArgs.first = 10; backwardConnectionArgs.before = "b"; backwardConnectionArgs.last = 10; // connectionDefinitions returns a connectionType and its associated edgeType, given a node type. -let resolve: GraphQLFieldResolver = (source, args, context, info) => { +const resolve: GraphQLFieldResolver = (source, args, context, info) => { info.fieldName = "f"; }; const fields: GraphQLFieldConfigMap = {}; let t: GraphQLObjectType; let e: GraphQLObjectType; -let def = connectionDefinitions({ +const def = connectionDefinitions({ connectionFields: fields, edgeFields: fields, name: "N", @@ -62,7 +62,8 @@ let def = connectionDefinitions({ }); t = def.connectionType; e = def.edgeType; -// connectionFromArray is a helper method that takes an array and the arguments from connectionArgs, does pagination and filtering, and returns an object in the shape expected by a connectionType's resolve function. +// connectionFromArray is a helper method that takes an array and the arguments from connectionArgs, +// does pagination and filtering, and returns an object in the shape expected by a connectionType's resolve function. const conn = connectionFromArray([1, 2, 3], { after: "a", before: "b", @@ -89,7 +90,7 @@ conn2.then((res) => { // cursorForObjectInConnection is a helper method that takes an array and a member object, and returns a cursor for use in the mutation payload. cursorForObjectInConnection(["a"], "b").toLowerCase(); // An example usage of these methods from the test schema: -let shipType: GraphQLObjectType = new GraphQLObjectType({ +const shipType: GraphQLObjectType = new GraphQLObjectType({ name: "ShipType", fields: {}, }); @@ -109,7 +110,8 @@ const factionType = new GraphQLObjectType({ }), }); // Object Identification -// nodeDefinitions returns the Node interface that objects can implement, and returns the node root field to include on the query type. To implement this, it takes a function to resolve an ID to an object, and to determine the type of a given object. +// nodeDefinitions returns the Node interface that objects can implement, and returns the node root field to include on the query type. +// To implement this, it takes a function to resolve an ID to an object, and to determine the type of a given object. const resolver: GraphQLTypeResolver = () => { return new GraphQLObjectType({ name: "T", @@ -170,7 +172,8 @@ const queryType = new GraphQLObjectType({ }) }); // Mutations -// mutationWithClientMutationId takes a name, input fields, output fields, and a mutation method to map from the input fields to the output fields, performing the mutation along the way. It then creates and returns a field configuration that can be used as a top-level field on the mutation type. +// mutationWithClientMutationId takes a name, input fields, output fields, and a mutation method to map from the input fields to the output fields, performing the mutation along the way. +// It then creates and returns a field configuration that can be used as a top-level field on the mutation type. const gifcm: GraphQLInputFieldConfigMap = {}; const gfcm: GraphQLFieldConfigMap = {}; mutationWithClientMutationId({ diff --git a/halogen/test/clip-loader.tsx b/halogen/test/clip-loader.tsx index 884e1caec6..02f0dd232c 100644 --- a/halogen/test/clip-loader.tsx +++ b/halogen/test/clip-loader.tsx @@ -1,18 +1,18 @@ import * as React from "react"; import * as Halogen from "halogen"; -class HalogenTests_ClipLoader_withNoProps extends React.Component, {}>{ +class HalogenTests_ClipLoader_withNoProps extends React.Component, {}> { render() { return ( - ) + ); } } -class HalogenTests_ClipLoader_withAllProps extends React.Component, {}>{ +class HalogenTests_ClipLoader_withAllProps extends React.Component, {}> { render() { return ( - ) + ); } } diff --git a/halogen/test/fade-loader.tsx b/halogen/test/fade-loader.tsx index 63781098eb..deeae1ce95 100644 --- a/halogen/test/fade-loader.tsx +++ b/halogen/test/fade-loader.tsx @@ -1,19 +1,19 @@ import * as React from "react"; import * as Halogen from "halogen"; -class HalogenTests_FadeLoader_withNoProps extends React.Component, {}>{ +class HalogenTests_FadeLoader_withNoProps extends React.Component, {}> { render() { return ( - ) + ); } } -class HalogenTests_FadeLoader_withAllProps extends React.Component, {}>{ +class HalogenTests_FadeLoader_withAllProps extends React.Component, {}> { render() { return ( - ) + ); } } diff --git a/halogen/test/pacman-loader.tsx b/halogen/test/pacman-loader.tsx index 7ccd294918..7852026580 100644 --- a/halogen/test/pacman-loader.tsx +++ b/halogen/test/pacman-loader.tsx @@ -1,18 +1,18 @@ import * as React from "react"; import * as Halogen from "halogen"; -class HalogenTests_PacmanLoader_withNoProps extends React.Component, {}>{ +class HalogenTests_PacmanLoader_withNoProps extends React.Component, {}> { render() { return ( - ) + ); } } -class HalogenTests_PacmanLoader_withAllProps extends React.Component, {}>{ +class HalogenTests_PacmanLoader_withAllProps extends React.Component, {}> { render() { return ( - ) + ); } } diff --git a/halogen/test/rotate-loader.tsx b/halogen/test/rotate-loader.tsx index 82b4b2b380..a5325a4962 100644 --- a/halogen/test/rotate-loader.tsx +++ b/halogen/test/rotate-loader.tsx @@ -1,18 +1,18 @@ import * as React from "react"; import * as Halogen from "halogen"; -class HalogenTests_RotateLoader_withNoProps extends React.Component, {}>{ +class HalogenTests_RotateLoader_withNoProps extends React.Component, {}> { render() { return ( - ) + ); } } -class HalogenTests_RotateLoader_withAllProps extends React.Component, {}>{ +class HalogenTests_RotateLoader_withAllProps extends React.Component, {}> { render() { return ( - ) + ); } } diff --git a/halogen/tslint.json b/halogen/tslint.json index fdc7cdc370..377cc837d4 100644 --- a/halogen/tslint.json +++ b/halogen/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/hapi-auth-jwt2/hapi-auth-jwt2-tests.ts b/hapi-auth-jwt2/hapi-auth-jwt2-tests.ts index 65bc862e64..e6eeb6a055 100644 --- a/hapi-auth-jwt2/hapi-auth-jwt2-tests.ts +++ b/hapi-auth-jwt2/hapi-auth-jwt2-tests.ts @@ -10,17 +10,17 @@ interface User { } interface Users { - [id: number]: User + [id: number]: User; } -var users:Users = { +var users: Users = { 1: { id: 1, name: 'Test User' } }; -var validate = function(decoded: User, request: Hapi.Request, callback: hapiAuthJwt2.ValidateCallback) { +function validate(decoded: User, request: Hapi.Request, callback: hapiAuthJwt2.ValidateCallback) { if (!users[decoded.id]) { return callback(null, false); } @@ -28,8 +28,8 @@ var validate = function(decoded: User, request: Hapi.Request, callback: hapiAuth return callback(null, true); } -server.register(hapiAuthJwt2, function(err) { - server.auth.strategy('jwt', 'jwt', { +server.register(hapiAuthJwt2, err => { + server.auth.strategy('jwt', 'jwt', { key: 'NeverShareYourSecret', validateFunc: validate, verifyOptions: { diff --git a/hapi-auth-jwt2/tsconfig.json b/hapi-auth-jwt2/tsconfig.json index 764570cbac..3bbd249dc8 100644 --- a/hapi-auth-jwt2/tsconfig.json +++ b/hapi-auth-jwt2/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "hapi-auth-jwt2-tests.ts" ] -} +} \ No newline at end of file diff --git a/history/v3/index.d.ts b/history/v3/index.d.ts new file mode 100644 index 0000000000..7a6c8116bd --- /dev/null +++ b/history/v3/index.d.ts @@ -0,0 +1,79 @@ +// Type definitions for history 3.2 +// Project: https://github.com/mjackson/history +// Definitions by: Sergey Buturlakin , Nathan Brown , Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace History; + +export type Action = "POP" | "PUSH" | "REPLACE"; +export type BeforeUnloadHook = () => string | boolean; +export type CreateHistory = (options?: HistoryOptions & O) => History & H; +export type CreateHistoryEnhancer = (createHistory: CreateHistory) => CreateHistory; + +export interface History { + listenBefore(hook: TransitionHook): () => void; + listen(listener: LocationListener): () => void; + transitionTo(location: Location): void; + push(path: LocationDescriptor): void; + replace(path: LocationDescriptor): void; + go(n: number): void; + goBack(): void; + goForward(): void; + createKey(): LocationKey; + createPath(path: LocationDescriptor): Path; + createHref(path: LocationDescriptor): Href; + createLocation(path?: LocationDescriptor, action?: Action, key?: LocationKey): Location; + getCurrentLocation(): Location; +} + +export interface HistoryOptions { + getUserConfirmation?: (message: string, callback: (result: boolean) => void) => void; + keyLength?: number; +} + +export type Hash = string; +export type Href = string; + +export interface Location { + pathname: Pathname; + search: Search; + query: Query; + state: LocationState; + action: Action; + key: LocationKey; +} + +export interface LocationDescriptorObject { + pathname?: Pathname; + search?: Search; + query?: Query; + state?: LocationState; +} + +export type LocationDescriptor = LocationDescriptorObject | Path; + +export type LocationKey = string; + +export type LocationListener = (location: Location) => void; + +export type LocationState = any; + +export type Path = string; // Pathname + Search; +export type Pathname = string; +export type Query = any; +export type Search = string; + +export type TransitionHook = (location: Location, callback: (result: any) => void) => any; + +export { default as createHistory } from "history/lib/createBrowserHistory"; +export { default as createHashHistory } from "history/lib/createHashHistory"; +export { default as createMemoryHistory, MemoryHistory, MemoryHistoryOptions } from "history/lib/createMemoryHistory"; + +export { default as useBasename, Basename, HistoryBasename, HistoryBasenameOptions } from "history/lib/useBasename"; +export { default as useBeforeUnload, HistoryBeforeUnload } from "history/lib/useBeforeUnload"; +export { default as useQueries, HistoryQueries } from "history/lib/useQueries"; + +import * as Actions from "history/lib/actions"; +export { Actions }; + +export { locationsAreEqual } from "history/lib/LocationUtils"; diff --git a/history/v3/lib/LocationUtils.d.ts b/history/v3/lib/LocationUtils.d.ts new file mode 100644 index 0000000000..1202cde9fe --- /dev/null +++ b/history/v3/lib/LocationUtils.d.ts @@ -0,0 +1,3 @@ +import { Location } from "history"; + +export function locationsAreEqual(a: Location, b: Location): boolean; diff --git a/history/v3/lib/actions.d.ts b/history/v3/lib/actions.d.ts new file mode 100644 index 0000000000..22fd29f61e --- /dev/null +++ b/history/v3/lib/actions.d.ts @@ -0,0 +1,9 @@ +export const PUSH: string; +export const REPLACE: string; +export const POP: string; + +export default { + PUSH, + REPLACE, + POP +}; diff --git a/history/v3/lib/createBrowserHistory.d.ts b/history/v3/lib/createBrowserHistory.d.ts new file mode 100644 index 0000000000..64f6bede8b --- /dev/null +++ b/history/v3/lib/createBrowserHistory.d.ts @@ -0,0 +1,5 @@ +import { CreateHistory } from "history"; + +declare const createBrowserHistory: CreateHistory; + +export default createBrowserHistory; diff --git a/history/v3/lib/createHashHistory.d.ts b/history/v3/lib/createHashHistory.d.ts new file mode 100644 index 0000000000..5150656393 --- /dev/null +++ b/history/v3/lib/createHashHistory.d.ts @@ -0,0 +1,5 @@ +import { CreateHistory } from "history"; + +declare const createHashHistory: CreateHistory; + +export default createHashHistory; diff --git a/history/v3/lib/createLocation.d.ts b/history/v3/lib/createLocation.d.ts new file mode 100644 index 0000000000..4007d98f05 --- /dev/null +++ b/history/v3/lib/createLocation.d.ts @@ -0,0 +1,2 @@ +import { Path, LocationState, Action, LocationKey, Location } from "history"; +export default function createLocation(path?: Path, state?: LocationState, action?: Action, key?: LocationKey): Location; diff --git a/history/v3/lib/createMemoryHistory.d.ts b/history/v3/lib/createMemoryHistory.d.ts new file mode 100644 index 0000000000..9ce282f164 --- /dev/null +++ b/history/v3/lib/createMemoryHistory.d.ts @@ -0,0 +1,14 @@ +import { CreateHistory, History } from "history"; + +export interface MemoryHistoryOptions { + entries?: string | [string]; + current?: string; +} + +export interface MemoryHistory { + canGo(n: number): boolean; +} + +declare const createMemoryHistory: CreateHistory; + +export default createMemoryHistory; diff --git a/history/v3/lib/useBasename.d.ts b/history/v3/lib/useBasename.d.ts new file mode 100644 index 0000000000..7b50904a56 --- /dev/null +++ b/history/v3/lib/useBasename.d.ts @@ -0,0 +1,13 @@ +import { CreateHistory, HistoryOptions } from "history"; + +export type Basename = string; + +export interface HistoryBasenameOptions { + basename?: Basename; +} + +export interface HistoryBasename { + basename?: Basename; +} + +export default function useBasename(createHistory: CreateHistory): CreateHistory; diff --git a/history/v3/lib/useBeforeUnload.d.ts b/history/v3/lib/useBeforeUnload.d.ts new file mode 100644 index 0000000000..950a7e6a17 --- /dev/null +++ b/history/v3/lib/useBeforeUnload.d.ts @@ -0,0 +1,7 @@ +import { BeforeUnloadHook, CreateHistory } from "history"; + +export interface HistoryBeforeUnload { + listenBeforeUnload(hook: BeforeUnloadHook): () => void; +} + +export default function useBeforeUnload(createHistory: CreateHistory): CreateHistory; diff --git a/history/v3/lib/useQueries.d.ts b/history/v3/lib/useQueries.d.ts new file mode 100644 index 0000000000..685c0221a6 --- /dev/null +++ b/history/v3/lib/useQueries.d.ts @@ -0,0 +1,10 @@ +import { CreateHistory, Href, LocationState, Path, Pathname, Query } from "history"; + +export interface HistoryQueries { + pushState(state: LocationState, pathname: Pathname, query?: Query): void; + replaceState(state: LocationState, pathname: Pathname, query?: Query): void; + createPath(path: Path, query?: Query): Path; + createHref(path: Path, query?: Query): Href; +} + +export default function useQueries(createHistory: CreateHistory): CreateHistory; diff --git a/history/v3/tsconfig.json b/history/v3/tsconfig.json new file mode 100644 index 0000000000..7523fbbbe9 --- /dev/null +++ b/history/v3/tsconfig.json @@ -0,0 +1,35 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "history": ["history/v3"], + "history/*": ["history/v3/*"] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "lib/actions.d.ts", + "lib/createBrowserHistory.d.ts", + "lib/createHashHistory.d.ts", + "lib/createLocation.d.ts", + "lib/createMemoryHistory.d.ts", + "lib/LocationUtils.d.ts", + "lib/useBasename.d.ts", + "lib/useBeforeUnload.d.ts", + "lib/useQueries.d.ts" + ] +} diff --git a/hoek/hoek-tests.ts b/hoek/hoek-tests.ts index 09f82a7e2a..bb2ac87389 100644 --- a/hoek/hoek-tests.ts +++ b/hoek/hoek-tests.ts @@ -50,16 +50,16 @@ console.log(copy.x.b); // results in 100 // merge(target, source, isNullOverride, isMergeArrays) -let target = { a: 1, b: 2 }; -let source = { a: 0, c: 5 }; -let source2 = { a: null, c: 5 }; +const target = { a: 1, b: 2 }; +const source = { a: 0, c: 5 }; +const source2 = { a: null, c: 5 }; Hoek.merge(target, source); // results in {a: 0, b: 2, c: 5} Hoek.merge(target, source2); // results in {a: null, b: 2, c: 5} Hoek.merge(target, source2, false); // results in {a: 1, b: 2, c: 5} -let targetArray = [1, 2, 3]; -let sourceArray = [4, 5]; +const targetArray = [1, 2, 3]; +const sourceArray = [4, 5]; Hoek.merge(targetArray, sourceArray); // results in [1, 2, 3, 4, 5] Hoek.merge(targetArray, sourceArray, true, false); // results in [4, 5] @@ -67,18 +67,18 @@ Hoek.merge(targetArray, sourceArray, true, false); // results in [4, 5] // applyToDefaults(defaults, options, isNullOverride) let defaults = { host: "localhost", port: 8000 }; -let options = { port: 8080 }; +const options = { port: 8080 }; let config = Hoek.applyToDefaults(defaults, options); // results in { host: "localhost", port: 8080 } defaults = { host: "localhost", port: 8000 }; -let options1 = { host: null, port: 8080 }; +const options1 = { host: null, port: 8080 }; config = Hoek.applyToDefaults(defaults, options1, true); // results in { host: null, port: 8080 } // applyToDefaultsWithShallow(defaults, options, keys) -let defaults1 = { +const defaults1 = { server: { host: "localhost", port: 8000 @@ -86,25 +86,25 @@ let defaults1 = { name: 'example' }; -let options2 = { server: { port: 8080 } }; +const options2 = { server: { port: 8080 } }; -let config1 = Hoek.applyToDefaultsWithShallow(defaults1, options2, ['server']); // results in { server: { port: 8080 }, name: 'example' } +const config1 = Hoek.applyToDefaultsWithShallow(defaults1, options2, ['server']); // results in { server: { port: 8080 }, name: 'example' } // deepEqual(b, a, [options]) -Hoek.deepEqual({ a: [1, 2], b: 'string', c: { d: true } }, { a: [1, 2], b: 'string', c: { d: true } }); //results in true -Hoek.deepEqual(Object.create(null), {}, { prototype: false }); //results in true -Hoek.deepEqual(Object.create(null), {}); //results in false +Hoek.deepEqual({ a: [1, 2], b: 'string', c: { d: true } }, { a: [1, 2], b: 'string', c: { d: true } }); // results in true +Hoek.deepEqual(Object.create(null), {}, { prototype: false }); // results in true +Hoek.deepEqual(Object.create(null), {}); // results in false // unique(array, key) let array = [1, 2, 2, 3, 3, 4, 5, 6]; -let newArray = Hoek.unique(array); // results in [1,2,3,4,5,6] +const newArray = Hoek.unique(array); // results in [1,2,3,4,5,6] let array1 = [{ id: 1 }, { id: 1 }, { id: 2 }]; -let newArray1 = Hoek.unique(array1, "id"); // results in [{id: 1}, {id: 2}] +const newArray1 = Hoek.unique(array1, "id"); // results in [{id: 1}, {id: 2}] // mapToObject(array, key) @@ -117,9 +117,9 @@ newObject = Hoek.mapToObject(array1, "id"); // results in {"1": true, "2": true} // intersect(array1, array2) array = [1, 2, 3]; -let array2 = [1, 4, 5]; +const array2 = [1, 4, 5]; -let newArray2 = Hoek.intersect(array, array2); // results in [1] +const newArray2 = Hoek.intersect(array, array2); // results in [1] // contain(ref, values, [options]) @@ -135,7 +135,7 @@ let array3 = [1, [2, 3]]; let flattenedArray = Hoek.flatten(array); // results in [1, 2, 3] array3 = [1, [2, 3]]; -let target1 = [4, [5]]; +const target1 = [4, [5]]; flattenedArray = Hoek.flatten(array3, target1); // results in [4, [5], 1, 2, 3] @@ -147,7 +147,7 @@ let obj = { a: { b: { c: 1 } } }; Hoek.reach(obj, chain); // returns 1 chain = 'a.b.-1'; -let obj1 = { a: { b: [2, 3, 6] } }; +const obj1 = { a: { b: [2, 3, 6] } }; Hoek.reach(obj1, chain); // returns 6 @@ -160,7 +160,7 @@ Hoek.reachTemplate(obj, '1+{a.b.c}=2'); // returns '1+1=2' // transform(obj, transform, [options]) -let source1 = { +const source1 = { address: { one: '123 main street', two: 'PO Box 1234' @@ -189,7 +189,7 @@ let result = Hoek.transform(source1, { // shallow(obj) -let shallow = Hoek.shallow({ a: { b: 1 } }); +const shallow = Hoek.shallow({ a: { b: 1 } }); // stringify(obj) @@ -199,13 +199,13 @@ Hoek.stringify(a); // Returns '[Cannot display object: Converting circular // Timer -let timerObj = new Hoek.Timer(); +const timerObj = new Hoek.Timer(); console.log("Time is now: " + timerObj.ts); console.log("Elapsed time from initialization: " + timerObj.elapsed() + 'milliseconds'); // Bench -let benchObj = new Hoek.Bench(); +const benchObj = new Hoek.Bench(); console.log("Elapsed time from initialization: " + benchObj.elapsed() + 'milliseconds'); // base64urlEncode(value) @@ -218,12 +218,12 @@ Hoek.base64urlDecode("aG9law=="); // escapeHtml(string) -let string = ' hey '; -let escapedString = Hoek.escapeHtml(string); // returns <html> hey </html> +const string = ' hey '; +const escapedString = Hoek.escapeHtml(string); // returns <html> hey </html> // escapeHeaderAttribute(attribute) -a = Hoek.escapeHeaderAttribute('I said "go w\\o me"'); //returns I said \"go w\\o me\" +a = Hoek.escapeHeaderAttribute('I said "go w\\o me"'); // returns I said \"go w\\o me\" // escapeRegex(string) @@ -231,7 +231,7 @@ a = Hoek.escapeRegex('4^f$s.4*5+-_?%=#!:@|~\\/`"(>)[<]d{}s,'); // returns 4\^f\ // assert(condition, message) -let x = 1, y = 2; +const x = 1, y = 2 as number; Hoek.assert(x === y, 'x should equal y'); // Throws 'x should equal y' @@ -243,21 +243,21 @@ Hoek.abort("Error message"); // displayStack(slice) -let stack = Hoek.displayStack(); +const stack = Hoek.displayStack(); console.log(stack); // callStack(slice) -let stack2 = Hoek.callStack(); +const stack2 = Hoek.callStack(); console.log(stack2); // nextTick(fn) -let myFn = function () { +let myFn = () => { console.log('Do this later'); }; -let nextFn = Hoek.nextTick(myFn); +const nextFn = Hoek.nextTick(myFn); nextFn(); console.log('Do this first'); @@ -269,11 +269,11 @@ console.log('Do this first'); // once(fn) -myFn = function () { +myFn = () => { console.log('Ran myFn'); }; -let onceFn = Hoek.once(myFn); +const onceFn = Hoek.once(myFn); onceFn(); // results in "Ran myFn" onceFn(); // results in undefined @@ -283,7 +283,7 @@ Hoek.ignore(); // uniqueFilename(path, extension) -let result1 = Hoek.uniqueFilename('./test/modules', 'txt'); // results in "full/path/test/modules/{random}.txt" +const result1 = Hoek.uniqueFilename('./test/modules', 'txt'); // results in "full/path/test/modules/{random}.txt" // isInteger(value) diff --git a/hoek/index.d.ts b/hoek/index.d.ts index 98e2188fec..e1ea52677b 100644 --- a/hoek/index.d.ts +++ b/hoek/index.d.ts @@ -27,8 +27,8 @@ interface ReachOptions { // Object -/** - * Clone an object or an array. +/** + * Clone an object or an array. */ export function clone(obj: T): T; diff --git a/hoek/tslint.json b/hoek/tslint.json index 192203ab54..377cc837d4 100644 --- a/hoek/tslint.json +++ b/hoek/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/http-assert/http-assert-tests.ts b/http-assert/http-assert-tests.ts index b95561b635..bfb12e650a 100644 --- a/http-assert/http-assert-tests.ts +++ b/http-assert/http-assert-tests.ts @@ -4,8 +4,8 @@ import { HttpError } from 'http-errors'; try { httpAssert.equal('hello', 'hello'); httpAssert(false, 401, 'authentication failed'); -} catch(err) { - console.log((err).status); - console.log((err).message); - console.log((err).expose); +} catch (err) { + console.log(( err).status); + console.log(( err).message); + console.log(( err).expose); } diff --git a/hyco-ws/tslint.json b/hyco-ws/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/hyco-ws/tslint.json +++ b/hyco-ws/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/indent-string/indent-string-tests.ts b/indent-string/indent-string-tests.ts index ea473a2814..6e5e764cb4 100644 --- a/indent-string/indent-string-tests.ts +++ b/indent-string/indent-string-tests.ts @@ -1,9 +1,9 @@ import indentString = require('indent-string'); indentString('Unicorns\nRainbows', 4); -//=> ' Unicorns' -//=> ' Rainbows' +// => ' Unicorns' +// => ' Rainbows' indentString('Unicorns\nRainbows', 4, '♥'); -//=> '♥♥♥♥Unicorns' -//=> '♥♥♥♥Rainbows' \ No newline at end of file +// => '♥♥♥♥Unicorns' +// => '♥♥♥♥Rainbows' \ No newline at end of file diff --git a/inert/tslint.json b/inert/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/inert/tslint.json +++ b/inert/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/is-absolute-url/is-absolute-url-tests.ts b/is-absolute-url/is-absolute-url-tests.ts index 8ddf3e2514..47c5f007ed 100644 --- a/is-absolute-url/is-absolute-url-tests.ts +++ b/is-absolute-url/is-absolute-url-tests.ts @@ -1,10 +1,10 @@ import isAbsoluteUrl = require('is-absolute-url'); isAbsoluteUrl('http://sindresorhus.com/foo/bar'); -//=> true +// => true isAbsoluteUrl('//sindresorhus.com'); -//=> false +// => false isAbsoluteUrl('foo/bar'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/is-archive/is-archive-tests.ts b/is-archive/is-archive-tests.ts index 30be8dc06e..332deae7ec 100644 --- a/is-archive/is-archive-tests.ts +++ b/is-archive/is-archive-tests.ts @@ -1,7 +1,7 @@ import isArchive = require('is-archive'); isArchive('src/unicorn.zip'); -//=> true +// => true isArchive('src/unicorn.txt'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/is-array/index.d.ts b/is-array/index.d.ts new file mode 100644 index 0000000000..f57afcbd50 --- /dev/null +++ b/is-array/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for is-array 1.0 +// Project: https://github.com/retrofox/is-array +// Definitions by: Pine Mizune +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isArray; +declare function isArray(val?: any): val is any[]; diff --git a/is-array/is-array-tests.ts b/is-array/is-array-tests.ts new file mode 100644 index 0000000000..9a8e252e05 --- /dev/null +++ b/is-array/is-array-tests.ts @@ -0,0 +1,13 @@ +import isArray = require('is-array'); + +isArray(); +isArray(null); +isArray(1); +isArray(true); +isArray([]); +isArray({}); + +var x = {} +if (isArray(x)) { + x.push(0); +} diff --git a/is-array/tsconfig.json b/is-array/tsconfig.json new file mode 100644 index 0000000000..2d027ece6d --- /dev/null +++ b/is-array/tsconfig.json @@ -0,0 +1,23 @@ + +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "is-array-tests.ts" + ] +} diff --git a/is-array/tslint.json b/is-array/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/is-array/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/is-binary-path/is-binary-path-tests.ts b/is-binary-path/is-binary-path-tests.ts index 967346a35a..43505a5b32 100644 --- a/is-binary-path/is-binary-path-tests.ts +++ b/is-binary-path/is-binary-path-tests.ts @@ -1,5 +1,5 @@ import isBinaryPath = require("is-binary-path"); -let a: boolean = isBinaryPath("src/unicorn.png"); +const a: boolean = isBinaryPath("src/unicorn.png"); -let b: boolean = isBinaryPath("src/unicorn.txt"); \ No newline at end of file +const b: boolean = isBinaryPath("src/unicorn.txt"); \ No newline at end of file diff --git a/is-compressed/is-compressed-tests.ts b/is-compressed/is-compressed-tests.ts index 11a2e67294..7720b334a4 100644 --- a/is-compressed/is-compressed-tests.ts +++ b/is-compressed/is-compressed-tests.ts @@ -1,7 +1,7 @@ import isCompressed = require('is-compressed'); isCompressed('src/unicorn.zip'); -//=> true +// => true isCompressed('src/unicorn.txt'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/is-relative-url/is-relative-url-tests.ts b/is-relative-url/is-relative-url-tests.ts index 293c621872..8835694624 100644 --- a/is-relative-url/is-relative-url-tests.ts +++ b/is-relative-url/is-relative-url-tests.ts @@ -1,10 +1,10 @@ import isRelativeUrl = require('is-relative-url'); isRelativeUrl('foo/bar'); -//=> true +// => true isRelativeUrl('http://sindresorhus.com/foo/bar'); -//=> false +// => false isRelativeUrl('//sindresorhus.com'); -//=> true \ No newline at end of file +// => true \ No newline at end of file diff --git a/is-root-path/is-root-path-tests.ts b/is-root-path/is-root-path-tests.ts index 0a577aee5a..3e050cd162 100644 --- a/is-root-path/is-root-path-tests.ts +++ b/is-root-path/is-root-path-tests.ts @@ -1,7 +1,7 @@ import isRootPath = require('is-root-path'); isRootPath('/'); -//=> true +// => true isRootPath('/Users'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/is-root/is-root-tests.ts b/is-root/is-root-tests.ts index 42fc3ee4f3..b53d07a0ac 100644 --- a/is-root/is-root-tests.ts +++ b/is-root/is-root-tests.ts @@ -2,4 +2,4 @@ import isRoot = require('is-root'); isRoot(); -//=> true \ No newline at end of file +// => true \ No newline at end of file diff --git a/is-text-path/is-text-path-tests.ts b/is-text-path/is-text-path-tests.ts index cd71933ec2..f7c417fe51 100644 --- a/is-text-path/is-text-path-tests.ts +++ b/is-text-path/is-text-path-tests.ts @@ -1,7 +1,7 @@ import isTextPath = require('is-text-path'); isTextPath('src/unicorn.txt'); -//=> true +// => true isTextPath('src/unicorn.png'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/isbn-utils/index.d.ts b/isbn-utils/index.d.ts new file mode 100644 index 0000000000..fe2ac4dae9 --- /dev/null +++ b/isbn-utils/index.d.ts @@ -0,0 +1,35 @@ +// Type definitions for isbn-utils 1.1 +// Project: https://github.com/GitbookIO/isbn-utils +// Definitions by: Jørgen Elgaard Larsen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +type IGroups = any; + +export class ISBNcodes { + readonly source: string; + readonly prefix: string; + readonly group: string; + readonly publisher: string; + readonly article: string; + readonly check: string; + readonly check10: string; + readonly check13: string; + readonly groupname: string; +} + +export class ISBN { + constructor(val: string, groups: IGroups); + asIsbn10(hyphenate?: boolean): string; + asIsbn13(hyphenate?: boolean): string; + codes: ISBNcodes; + isIsbn10(): boolean; + isIsbn13(): boolean; + isValid(): boolean; +} + +export function asIsbn10(isbn: string, hyphenate?: boolean): string; +export function asIsbn13(isbn: string, hyphenate?: boolean): string; +export function parse(isbn: string, groups?: IGroups): ISBN|null; +export function hyphenate(isbn: string): string; +export function isValid(isbn: string, groups?: IGroups): boolean; diff --git a/isbn-utils/isbn-utils-tests.ts b/isbn-utils/isbn-utils-tests.ts new file mode 100644 index 0000000000..91f72a0359 --- /dev/null +++ b/isbn-utils/isbn-utils-tests.ts @@ -0,0 +1,36 @@ +import * as isbn from 'isbn-utils'; + + +const isbn10a: isbn.ISBN|null = isbn.parse('4873113369'); +let b: boolean; +let s: string; + +if (isbn10a !== null) { + b = isbn10a.isIsbn10(); + b = isbn10a.isIsbn13(); + s = isbn10a.asIsbn10(); + s = isbn10a.asIsbn10(true); + s = isbn10a.asIsbn13(); + s = isbn10a.asIsbn13(true); + s = isbn10a.codes.source; + s = isbn10a.codes.prefix; + s = isbn10a.codes.group; + s = isbn10a.codes.publisher; + s = isbn10a.codes.article; + s = isbn10a.codes.check; + s = isbn10a.codes.check10; + s = isbn10a.codes.check13; + s = isbn10a.codes.groupname; +} + +const bad: isbn.ISBN|null = isbn.parse('invalid format'); +if (bad === null) { + s = 'Bummer.'; +} + +s = isbn.asIsbn13('4-87311-336-9'); +s = isbn.asIsbn13('4-87311-336-9', true); +s = isbn.asIsbn10('978-4-87311-336-4'); +s = isbn.asIsbn10('978-4-87311-336-4', true); + +s = isbn.hyphenate('9784873113364'); diff --git a/isbn-utils/tsconfig.json b/isbn-utils/tsconfig.json new file mode 100644 index 0000000000..b061bf6192 --- /dev/null +++ b/isbn-utils/tsconfig.json @@ -0,0 +1,23 @@ +{ + "files": [ + "index.d.ts", + "isbn-utils-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/isbn-utils/tslint.json b/isbn-utils/tslint.json new file mode 100644 index 0000000000..f9e30021f4 --- /dev/null +++ b/isbn-utils/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} diff --git a/isomorphic-fetch/index.d.ts b/isomorphic-fetch/index.d.ts index 452e95e871..00b40fe911 100644 --- a/isomorphic-fetch/index.d.ts +++ b/isomorphic-fetch/index.d.ts @@ -3,182 +3,115 @@ // Definitions by: Todd Lucas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | - "track" | "video"; -type RequestDestination = "" | "document" | "embed" | "font" | "image" | - "manifest" | "media" | "object" | "report" | "script" | "serviceworker" | - "sharedworker" | "style" | "worker" | "xslt"; -type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; -type RequestCredentials = "omit" | "same-origin" | "include"; -type RequestCache = - "default" | "no-store" | "reload" | "no-cache" | "force-cache" | - "only-if-cached"; -type RequestRedirect = "follow" | "error" | "manual"; +interface ForEachCallback { + (keyId: any, status: string): void; +} -type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | - "opaqueredirect"; - -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 HeadersInterface { +interface Headers { append(name: string, value: string): void; delete(name: string): void; + forEach(callback: ForEachCallback): void; get(name: string): string | null; - getAll(name: string): string[]; has(name: string): boolean; set(name: string, value: string): void; - - // TODO: iterable; - forEach(callback: (value: string, index: number, headers: HeadersInterface) => void, thisArg?: any): void; - // NOTE: The following are supported by whatwg-fetch but not node-fetch. - // entries(): IterableIterator<[string, string]>; - // keys(): IterableIterator; - // values(): IterableIterator; } -type HeadersInit = Headers | string[] | { [index: string]: string }; - -declare class Headers implements HeadersInterface { - constructor(init?: HeadersInit); - append(name: string, value: string): void; - delete(name: string): void; - get(name: string): string | null; - getAll(name: string): string[]; - has(name: string): boolean; - set(name: string, value: string): void; - - forEach(callback: (value: string, index: number, headers: HeadersInterface) => void, thisArg?: any): void; +declare var Headers: { + prototype: Headers; + new(init?: any): Headers; } -interface BodyInterface { - bodyUsed: boolean; +interface Blob { + readonly size: number; + readonly type: string; + msClose(): void; + msDetachStream(): any; + slice(start?: number, end?: number, contentType?: string): Blob; +} + +interface Body { + readonly bodyUsed: boolean; arrayBuffer(): Promise; blob(): Promise; - formData(): Promise; json(): Promise; - json(): Promise; text(): Promise; } -declare class Body implements BodyInterface { - bodyUsed: boolean; - arrayBuffer(): Promise; - blob(): Promise; - formData(): Promise; - json(): Promise; - json(): Promise; - text(): Promise; -} - -interface RequestInterface extends BodyInterface { - method: string; - url: string; - headers: HeadersInterface; - - type: RequestType; - destination: RequestDestination; - referrer?: string; - referrerPolicy?: ReferrerPolicy; - mode: RequestMode; - credentials: RequestCredentials; - cache: RequestCache; - redirect?: RequestRedirect; - integrity?: string; - - clone(): RequestInterface; -} - -type BodyInit = Blob | ArrayBufferView | ArrayBuffer | FormData /* | URLSearchParams */ | string; - interface RequestInit { method?: string; - headers?: HeadersInit; - body?: BodyInit; + headers?: any; + body?: any; referrer?: string; - referrerPolicy?: ReferrerPolicy; - mode?: RequestMode; - credentials?: RequestCredentials; - cache?: RequestCache; - redirect?: RequestRedirect; + referrerPolicy?: string; + mode?: string; + credentials?: string; + cache?: string; + redirect?: string; integrity?: string; - window?: any; // can only be set to null + keepalive?: boolean; + window?: any; } -type RequestInfo = RequestInterface | string; - -declare class Request extends Body implements RequestInterface { - constructor(input: RequestInfo, init?: RequestInit); - - method: string; - url: string; - headers: HeadersInterface; - - type: RequestType; - destination: RequestDestination; - referrer: string; - referrerPolicy: ReferrerPolicy; - mode: RequestMode; - credentials: RequestCredentials; - cache: RequestCache; - redirect: RequestRedirect; - integrity: string; - - clone(): RequestInterface; +interface Request extends Object, Body { + readonly cache: string; + readonly credentials: string; + readonly destination: string; + readonly headers: Headers; + readonly integrity: string; + readonly keepalive: boolean; + readonly method: string; + readonly mode: string; + readonly redirect: string; + readonly referrer: string; + readonly referrerPolicy: string; + readonly type: string; + readonly url: string; + clone(): Request; } -interface ResponseInterface extends BodyInterface { - type: ResponseType; - - url: string; - redirected: boolean; - status: number; - statusText: string; - ok: boolean; - headers: HeadersInterface; - // size: number; - // timeout: number; - body: any; - trailer: Promise; - - clone(): ResponseInterface; +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; } -type ResponseBodyInit = BodyInit; +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; +} interface ResponseInit { status?: number; statusText?: string; - headers?: HeadersInit; + headers?: any; } -declare class Response extends Body implements ResponseInterface { - constructor(body?: ResponseBodyInit, init?: ResponseInit); - - static redirect(url: string, status?: number): ResponseInterface; - static error(): ResponseInterface; - - type: ResponseType; - - url: string; - redirected: boolean; - status: number; - statusText: string; - ok: boolean; - headers: HeadersInterface; - body: any; - trailer: Promise; - - clone(): ResponseInterface; +interface Response extends Object, Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly status: number; + readonly statusText: string; + readonly type: string; + readonly url: string; + clone(): Response; } -interface Window { - fetch(url: RequestInfo, init?: RequestInit): Promise; +declare var Response: { + prototype: Response; + new(body?: any, init?: ResponseInit): Response; } -declare var fetch: typeof window.fetch; +interface GlobalFetch { + fetch(input: Request | string, init?: RequestInit): Promise; +} + +interface Window extends GlobalFetch { +} + +declare function fetch(input: Request | string, init?: RequestInit): Promise; declare module "isomorphic-fetch" { - export = fetch; + namespace _fetch { } + const _fetch: typeof fetch; + export = _fetch; } diff --git a/isomorphic-fetch/isomorphic-fetch-tests.ts b/isomorphic-fetch/isomorphic-fetch-tests.ts index 78f0da930a..ac1a008350 100644 --- a/isomorphic-fetch/isomorphic-fetch-tests.ts +++ b/isomorphic-fetch/isomorphic-fetch-tests.ts @@ -6,7 +6,7 @@ function test_isomorphicFetchTestCases_ambient() { expectSuccess(fetch('http://localhost:3000/good'), 'Good response'); fetch('http://localhost:3000/bad') - .then((response: ResponseInterface) => { + .then((response: Response) => { return response.text(); }) .catch((err) => { @@ -17,7 +17,7 @@ function test_isomorphicFetchTestCases_commonjs() { expectSuccess(fetchImportedViaCommonJS('http://localhost:3000/good'), 'Good response'); fetchImportedViaCommonJS('http://localhost:3000/bad') - .then((response: ResponseInterface) => { + .then((response: Response) => { return response.text(); }) .catch((err) => { @@ -28,7 +28,7 @@ function test_isomorphicFetchTestCases_es6() { expectSuccess(fetchImportedViaES6Module('http://localhost:3000/good'), 'Good response'); fetchImportedViaES6Module('http://localhost:3000/bad') - .then((response: ResponseInterface) => { + .then((response: Response) => { return response.text(); }) .catch((err) => { @@ -135,8 +135,8 @@ function test_whatwgTestCases_es6() { expectSuccess(fetchImportedViaES6Module(request), 'Post response:'); } -function expectSuccess(promise: Promise, responseText: string) { - promise.then((response: ResponseInterface) => { +function expectSuccess(promise: Promise, responseText: string) { + promise.then((response: Response) => { return response.text(); }) .then((text: string) => { diff --git a/jalaali-js/tslint.json b/jalaali-js/tslint.json index fdc7cdc370..377cc837d4 100644 --- a/jalaali-js/tslint.json +++ b/jalaali-js/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/japanese-holidays/index.d.ts b/japanese-holidays/index.d.ts new file mode 100644 index 0000000000..e8102de87d --- /dev/null +++ b/japanese-holidays/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for japanese-holidays 1.0 +// Project: https://github.com/osamutake/japanese-holidays-js +// Definitions by: syamatoo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function isHoliday(date: Date, furikae?: boolean): string | undefined; +export function isHolidayAt(date: Date, furikae?: boolean): string | undefined; +export function getHolidaysOf(year: number, furikae?: boolean): Holiday[]; + +export interface Holiday { + month: number; + date: number; + name: string; +} diff --git a/japanese-holidays/japanese-holidays-tests.ts b/japanese-holidays/japanese-holidays-tests.ts new file mode 100644 index 0000000000..32f760360e --- /dev/null +++ b/japanese-holidays/japanese-holidays-tests.ts @@ -0,0 +1,22 @@ +import {isHoliday, isHolidayAt, getHolidaysOf} from 'japanese-holidays'; + +const date = new Date(2017, 0, 9); +const h: string | undefined = isHoliday(date); +if (h !== undefined) { + h.charAt(0); +} + +const noFurikae: string | undefined = isHoliday(date, false); + +const hAt = isHolidayAt(date); +if (hAt !== undefined) { + hAt.charAt(0); +} + +isHolidayAt(date, false); + +const holidays = getHolidaysOf(2017); +const first = holidays[0]; +const n: string = first.name; +const m: number = first.month; +const d: number = first.date; diff --git a/japanese-holidays/tsconfig.json b/japanese-holidays/tsconfig.json new file mode 100644 index 0000000000..11826ce711 --- /dev/null +++ b/japanese-holidays/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "japanese-holidays-tests.ts" + ] +} \ No newline at end of file diff --git a/japanese-holidays/tslint.json b/japanese-holidays/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/japanese-holidays/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/jasmine-ajax/index.d.ts b/jasmine-ajax/index.d.ts index 72a3348afc..6ec4020d00 100644 --- a/jasmine-ajax/index.d.ts +++ b/jasmine-ajax/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for jasmine-ajax 3.1.1 +// Type definitions for jasmine-ajax 3.1 // Project: https://github.com/jasmine/jasmine-ajax // Definitions by: Louis Grignon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 interface JasmineAjaxResponse { status?: number; @@ -74,7 +75,7 @@ declare class MockAjax { stubRequest(url: RegExp, data?: string, method?: string): JasmineAjaxRequestStub; stubRequest(url: string, data?: string, method?: string): JasmineAjaxRequestStub; - + stubRequest(url: RegExp, data?: RegExp, method?: string): JasmineAjaxRequestStub; stubRequest(url: string, data?: RegExp, method?: string): JasmineAjaxRequestStub; diff --git a/jasmine-ajax/jasmine-ajax-tests.ts b/jasmine-ajax/jasmine-ajax-tests.ts index 890a724420..d94b205d13 100644 --- a/jasmine-ajax/jasmine-ajax-tests.ts +++ b/jasmine-ajax/jasmine-ajax-tests.ts @@ -8,31 +8,31 @@ declare function getJasmineRequireObj(); -describe('StubTracker', function() { - beforeEach(function() { +describe('StubTracker', () => { + beforeEach(() => { var Constructor = getJasmineRequireObj().AjaxStubTracker(); this.tracker = new Constructor(); }); - it('finds nothing if no stubs are added', function() { + it('finds nothing if no stubs are added', () => { expect(this.tracker.findStub()).toBeUndefined(); }); - it('finds an added stub', function() { - var stub = { matches: function() { return true; } }; + it('finds an added stub', () => { + var stub = { matches: () => true }; this.tracker.addStub(stub); expect(this.tracker.findStub()).toBe(stub); }); - it('skips an added stub that does not match', function() { - var stub = { matches: function() { return false; } }; + it('skips an added stub that does not match', () => { + var stub = { matches: () => false }; this.tracker.addStub(stub); expect(this.tracker.findStub()).toBeUndefined(); }); - it('passes url, data, and method to the stub', function() { + it('passes url, data, and method to the stub', () => { var stub = { matches: jasmine.createSpy('matches') }; this.tracker.addStub(stub); @@ -41,7 +41,7 @@ describe('StubTracker', function() { expect(stub.matches).toHaveBeenCalledWith('url', 'data', 'method'); }); - it('can clear out all stubs', function() { + it('can clear out all stubs', () => { var stub = { matches: jasmine.createSpy('matches') }; this.tracker.addStub(stub); @@ -57,10 +57,10 @@ describe('StubTracker', function() { expect(stub.matches).not.toHaveBeenCalled(); }); - it('uses the most recently added stub that matches', function() { - var stub1 = { matches: function() { return true; } }; - var stub2 = { matches: function() { return true; } }; - var stub3 = { matches: function() { return false; } }; + it('uses the most recently added stub that matches', () => { + var stub1 = { matches: () => true }; + var stub2 = { matches: () => false }; + var stub3 = { matches: () => false }; this.tracker.addStub(stub1); this.tracker.addStub(stub2); @@ -70,22 +70,22 @@ describe('StubTracker', function() { }); }); -describe('FakeRequest', function() { - beforeEach(function() { +describe('FakeRequest', () => { + beforeEach(() => { this.requestTracker = { track: jasmine.createSpy('trackRequest') }; - this.stubTracker = { findStub: function() { } }; + this.stubTracker = { findStub() { } }; var parserInstance = this.parserInstance = jasmine.createSpy('parse'); - this.paramParser = { findParser: function() { return { parse: parserInstance }; } }; + this.paramParser = { findParser: () => ({ parse: parserInstance }) }; var eventBus = this.fakeEventBus = { addEventListener: jasmine.createSpy('addEventListener'), trigger: jasmine.createSpy('trigger'), removeEventListener: jasmine.createSpy('removeEventListener') }; - this.eventBusFactory = function() { + this.eventBusFactory = () => { return eventBus; }; this.fakeGlobal = { - XMLHttpRequest: function() { + XMLHttpRequest: () => { this.extraAttribute = 'my cool attribute'; }, DOMParser: window['DOMParser'], @@ -94,13 +94,13 @@ describe('FakeRequest', function() { this.FakeRequest = getJasmineRequireObj().AjaxFakeRequest(this.eventBusFactory)(this.fakeGlobal, this.requestTracker, this.stubTracker, this.paramParser); }); - it('extends from the global XMLHttpRequest', function() { + it('extends from the global XMLHttpRequest', () => { var request = new this.FakeRequest(); expect(request.extraAttribute).toEqual('my cool attribute'); }); - it('skips XMLHttpRequest attributes that IE does not want copied', function() { + it('skips XMLHttpRequest attributes that IE does not want copied', () => { // use real window here so it will correctly go red on IE if it breaks var FakeRequest = getJasmineRequireObj().AjaxFakeRequest(this.eventBusFactory)(window, this.requestTracker, this.stubTracker, this.paramParser); var request = new FakeRequest(); @@ -110,20 +110,20 @@ describe('FakeRequest', function() { expect(request.statusText).toBeUndefined(); }); - it('tracks the request', function() { + it('tracks the request', () => { var request = new this.FakeRequest(); expect(this.requestTracker.track).toHaveBeenCalledWith(request); }); - it('has default request headers and override mime type', function() { + it('has default request headers and override mime type', () => { var request = new this.FakeRequest(); expect(request.requestHeaders).toEqual({}); expect(request.overriddenMimeType).toBeNull(); }); - it('saves request information when opened', function() { + it('saves request information when opened', () => { var request = new this.FakeRequest(); request.open('METHOD', 'URL', 'ignore_async', 'USERNAME', 'PASSWORD'); @@ -133,7 +133,7 @@ describe('FakeRequest', function() { expect(request.password).toEqual('PASSWORD'); }); - it('saves an override mime type', function() { + it('saves an override mime type', () => { var request = new this.FakeRequest(); request.overrideMimeType('application/text; charset: utf-8'); @@ -141,7 +141,7 @@ describe('FakeRequest', function() { expect(request.overriddenMimeType).toBe('application/text; charset: utf-8'); }); - it('saves request headers', function() { + it('saves request headers', () => { var request = new this.FakeRequest(); request.setRequestHeader('X-Header-1', 'value1'); @@ -153,7 +153,7 @@ describe('FakeRequest', function() { }); }); - it('combines request headers with the same header name', function() { + it('combines request headers with the same header name', () => { var request = new this.FakeRequest(); request.setRequestHeader('X-Header', 'value1'); @@ -162,7 +162,7 @@ describe('FakeRequest', function() { expect(request.requestHeaders['X-Header']).toEqual('value1, value2'); }); - it('finds the content-type request header', function() { + it('finds the content-type request header', () => { var request = new this.FakeRequest(); request.setRequestHeader('ContEnt-tYPe', 'application/text+xml'); @@ -170,24 +170,24 @@ describe('FakeRequest', function() { expect(request.contentType()).toEqual('application/text+xml'); }); - describe('managing readyState', function() { - beforeEach(function() { + describe('managing readyState', () => { + beforeEach(() => { this.request = new this.FakeRequest(); }); - it('has an initial ready state of 0 (uninitialized)', function() { + it('has an initial ready state of 0 (uninitialized)', () => { expect(this.request.readyState).toBe(0); expect(this.fakeEventBus.trigger).not.toHaveBeenCalled(); }); - it('has a ready state of 1 (open) when opened', function() { + it('has a ready state of 1 (open) when opened', () => { this.request.open(); expect(this.request.readyState).toBe(1); expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange'); }); - it('has a ready state of 0 (uninitialized) when aborted', function() { + it('has a ready state of 0 (uninitialized) when aborted', () => { this.request.open(); this.fakeEventBus.trigger.calls.reset(); @@ -197,7 +197,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange'); }); - it('has a ready state of 1 (sent) when sent', function() { + it('has a ready state of 1 (sent) when sent', () => { this.request.open(); this.fakeEventBus.trigger.calls.reset(); @@ -208,7 +208,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).not.toHaveBeenCalledWith('readystatechange'); }); - it('has a ready state of 4 (loaded) when timed out', function() { + it('has a ready state of 4 (loaded) when timed out', () => { this.request.open(); this.request.send(); this.fakeEventBus.trigger.calls.reset(); @@ -221,7 +221,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange', 'timeout'); }); - it('has a ready state of 4 (loaded) when network erroring', function() { + it('has a ready state of 4 (loaded) when network erroring', () => { this.request.open(); this.request.send(); this.fakeEventBus.trigger.calls.reset(); @@ -232,7 +232,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange'); }); - it('has a ready state of 4 (loaded) when responding', function() { + it('has a ready state of 4 (loaded) when responding', () => { this.request.open(); this.request.send(); this.fakeEventBus.trigger.calls.reset(); @@ -243,7 +243,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange'); }); - it('has a ready state of 2, then 4 (loaded) when responding', function() { + it('has a ready state of 2, then 4 (loaded) when responding', () => { this.request.open(); this.request.send(); this.fakeEventBus.trigger.calls.reset(); @@ -254,7 +254,7 @@ describe('FakeRequest', function() { { name: 'X-Header', value: 'foo' } ]; - this.fakeEventBus.trigger.and.callFake(function(event) { + this.fakeEventBus.trigger.and.callFake(event => { if (event === 'readystatechange') { events.push({ readyState: request.readyState, @@ -280,41 +280,41 @@ describe('FakeRequest', function() { ]); }); - it('throws an error when timing out a request that has completed', function() { + it('throws an error when timing out a request that has completed', () => { this.request.open(); this.request.send(); this.request.respondWith({}); var request = this.request; - expect(function() { + expect(() => { request.responseTimeout(); }).toThrowError('FakeXMLHttpRequest already completed'); }); - it('throws an error when responding to a request that has completed', function() { + it('throws an error when responding to a request that has completed', () => { this.request.open(); this.request.send(); this.request.respondWith({}); var request = this.request; - expect(function() { + expect(() => { request.respondWith({}); }).toThrowError('FakeXMLHttpRequest already completed'); }); - it('throws an error when erroring a request that has completed', function() { + it('throws an error when erroring a request that has completed', () => { this.request.open(); this.request.send(); this.request.respondWith({}); var request = this.request; - expect(function() { + expect(() => { request.responseError({}); }).toThrowError('FakeXMLHttpRequest already completed'); }); }); - it('registers on-style callback with the event bus', function() { + it('registers on-style callback with the event bus', () => { this.request = new this.FakeRequest(); expect(this.fakeEventBus.addEventListener).toHaveBeenCalledWith('readystatechange', jasmine.any(Function)); @@ -336,16 +336,13 @@ describe('FakeRequest', function() { this.request.onloadend = jasmine.createSpy('loadend'); var args = this.fakeEventBus.addEventListener.calls.allArgs(); - for (var i = 0; i < args.length; i++) { - var eventName = args[i][0], - busCallback = args[i][1]; - + for (const [eventName, busCallback] of args) { busCallback(); expect(this.request['on' + eventName]).toHaveBeenCalled(); } }); - it('delegates addEventListener to the eventBus', function() { + it('delegates addEventListener to the eventBus', () => { this.request = new this.FakeRequest(); this.request.addEventListener('foo', 'bar'); @@ -353,7 +350,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.addEventListener).toHaveBeenCalledWith('foo', 'bar'); }); - it('delegates removeEventListener to the eventBus', function() { + it('delegates removeEventListener to the eventBus', () => { this.request = new this.FakeRequest(); this.request.removeEventListener('foo', 'bar'); @@ -361,18 +358,18 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.removeEventListener).toHaveBeenCalledWith('foo', 'bar'); }); - describe('triggering progress events', function() { - beforeEach(function() { + describe('triggering progress events', () => { + beforeEach(() => { this.request = new this.FakeRequest(); }); - it('should not trigger any events to start', function() { + it('should not trigger any events to start', () => { this.request.open(); expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange'); }); - it('should trigger loadstart when sent', function() { + it('should trigger loadstart when sent', () => { this.request.open(); this.fakeEventBus.trigger.calls.reset(); @@ -389,7 +386,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).not.toHaveBeenCalledWith('loadend'); }); - it('should trigger abort, progress, loadend when aborted', function() { + it('should trigger abort, progress, loadend when aborted', () => { this.request.open(); this.request.send(); @@ -407,7 +404,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('loadend'); }); - it('should trigger error, progress, loadend when network error', function() { + it('should trigger error, progress, loadend when network error', () => { this.request.open(); this.request.send(); @@ -425,7 +422,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('loadend'); }); - it('should trigger timeout, progress, loadend when timing out', function() { + it('should trigger timeout, progress, loadend when timing out', () => { this.request.open(); this.request.send(); @@ -445,7 +442,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('loadend'); }); - it('should trigger load, progress, loadend when responding', function() { + it('should trigger load, progress, loadend when responding', () => { this.request.open(); this.request.send(); @@ -464,7 +461,7 @@ describe('FakeRequest', function() { }); }); - it('ticks the jasmine clock on timeout', function() { + it('ticks the jasmine clock on timeout', () => { var clock = { tick: jasmine.createSpy('tick') }; spyOn(jasmine, 'clock').and.returnValue(clock); @@ -477,13 +474,13 @@ describe('FakeRequest', function() { expect(clock.tick).toHaveBeenCalledWith(30000); }); - it('has an initial status of null', function() { + it('has an initial status of null', () => { var request = new this.FakeRequest(); expect(request.status).toBeNull(); }); - it('has an aborted status', function() { + it('has an aborted status', () => { var request = new this.FakeRequest(); request.abort(); @@ -492,7 +489,7 @@ describe('FakeRequest', function() { expect(request.statusText).toBe('abort'); }); - it('has a status from the response', function() { + it('has a status from the response', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -503,7 +500,7 @@ describe('FakeRequest', function() { expect(request.statusText).toBe(''); }); - it('has a statusText from the response', function() { + it('has a statusText from the response', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -514,7 +511,7 @@ describe('FakeRequest', function() { expect(request.statusText).toBe('OK'); }); - it('saves off any data sent to the server', function() { + it('saves off any data sent to the server', () => { var request = new this.FakeRequest(); request.open(); request.send('foo=bar&baz=quux'); @@ -522,7 +519,7 @@ describe('FakeRequest', function() { expect(request.params).toBe('foo=bar&baz=quux'); }); - it('parses data sent to the server', function() { + it('parses data sent to the server', () => { var request = new this.FakeRequest(); request.open(); request.send('foo=bar&baz=quux'); @@ -532,7 +529,7 @@ describe('FakeRequest', function() { expect(request.data()).toBe('parsed'); }); - it('skips parsing if no data was sent', function() { + it('skips parsing if no data was sent', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -541,7 +538,7 @@ describe('FakeRequest', function() { expect(this.parserInstance).not.toHaveBeenCalled(); }); - it('saves responseText', function() { + it('saves responseText', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -551,7 +548,7 @@ describe('FakeRequest', function() { expect(request.responseText).toBe('foobar'); }); - it('defaults responseText if none is given', function() { + it('defaults responseText if none is given', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -561,7 +558,7 @@ describe('FakeRequest', function() { expect(request.responseText).toBe(''); }); - it('retrieves individual response headers', function() { + it('retrieves individual response headers', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -576,7 +573,7 @@ describe('FakeRequest', function() { expect(request.getResponseHeader('X-Header')).toBe('foo'); }); - it('retrieves individual response headers case-insensitively', function() { + it('retrieves individual response headers case-insensitively', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -591,7 +588,7 @@ describe('FakeRequest', function() { expect(request.getResponseHeader('x-header')).toBe('foo'); }); - it('retrieves a combined response header', function() { + it('retrieves a combined response header', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -607,7 +604,7 @@ describe('FakeRequest', function() { expect(request.getResponseHeader('x-header')).toBe('foo, bar'); }); - it("doesn't pollute the response headers of other XHRs", function() { + it("doesn't pollute the response headers of other XHRs", () => { var request1 = new this.FakeRequest(); request1.open(); request1.send(); @@ -623,7 +620,7 @@ describe('FakeRequest', function() { expect(request2.getAllResponseHeaders()).toBe("X-Baz: quux\r\n"); }); - it('retrieves all response headers', function() { + it('retrieves all response headers', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -640,7 +637,7 @@ describe('FakeRequest', function() { expect(request.getAllResponseHeaders()).toBe("X-Header-1: foo\r\nX-Header-2: bar\r\nX-Header-1: baz\r\n"); }); - it('sets the content-type header to the specified contentType when no other headers are supplied', function() { + it('sets the content-type header to the specified contentType when no other headers are supplied', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -651,7 +648,7 @@ describe('FakeRequest', function() { expect(request.getAllResponseHeaders()).toBe("Content-Type: text/plain\r\n"); }); - it('sets a default content-type header if no contentType and headers are supplied', function() { + it('sets a default content-type header if no contentType and headers are supplied', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -662,7 +659,7 @@ describe('FakeRequest', function() { expect(request.getAllResponseHeaders()).toBe("Content-Type: application/json\r\n"); }); - it('has no responseXML by default', function() { + it('has no responseXML by default', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -672,7 +669,7 @@ describe('FakeRequest', function() { expect(request.responseXML).toBeNull(); }); - it('parses a text/xml document into responseXML', function() { + it('parses a text/xml document into responseXML', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -689,7 +686,7 @@ describe('FakeRequest', function() { } }); - it('parses an application/xml document into responseXML', function() { + it('parses an application/xml document into responseXML', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -706,7 +703,7 @@ describe('FakeRequest', function() { } }); - it('parses a custom blah+xml document into responseXML', function() { + it('parses a custom blah+xml document into responseXML', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -723,7 +720,7 @@ describe('FakeRequest', function() { } }); - it('defaults the response attribute to the responseText', function() { + it('defaults the response attribute to the responseText', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -733,7 +730,7 @@ describe('FakeRequest', function() { expect(request.response).toEqual('foo'); }); - it('has a text response when the responseType is blank', function() { + it('has a text response when the responseType is blank', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -743,7 +740,7 @@ describe('FakeRequest', function() { expect(request.response).toEqual('foo'); }); - it('has a text response when the responseType is text', function() { + it('has a text response when the responseType is text', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -755,14 +752,14 @@ describe('FakeRequest', function() { }); -describe("Jasmine Mock Ajax (for toplevel)", function() { +describe("Jasmine Mock Ajax (for toplevel)", () => { var request, anotherRequest, response; var success, error, complete; var client, onreadystatechange; var sharedContext: any = {}; var fakeGlobal, mockAjax; - beforeEach(function() { + beforeEach(() => { var fakeXMLHttpRequest = jasmine.createSpy('realFakeXMLHttpRequest'); fakeGlobal = { XMLHttpRequest: fakeXMLHttpRequest, @@ -776,7 +773,7 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { error = jasmine.createSpy("onFailure"); complete = jasmine.createSpy("onComplete"); - onreadystatechange = function() { + onreadystatechange = () => { if (this.readyState === (this.DONE || 4)) { // IE 8 doesn't support DONE if (this.status === 200) { success(this.responseText, this.textStatus, this); @@ -789,8 +786,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { }; }); - describe("when making a request", function() { - beforeEach(function() { + describe("when making a request", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -798,24 +795,24 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { request = mockAjax.requests.mostRecent(); }); - it("should store URL and transport", function() { + it("should store URL and transport", () => { expect(request.url).toEqual("example.com/someApi"); }); - it("should queue the request", function() { + it("should queue the request", () => { expect(mockAjax.requests.count()).toEqual(1); }); - it("should allow access to the queued request", function() { + it("should allow access to the queued request", () => { expect(mockAjax.requests.first()).toEqual(request); }); - it("should allow access to the queued request via index", function() { + it("should allow access to the queued request via index", () => { expect(mockAjax.requests.at(0)).toEqual(request); }); - describe("and then another request", function() { - beforeEach(function() { + describe("and then another request", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -824,26 +821,26 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { anotherRequest = mockAjax.requests.mostRecent(); }); - it("should queue the next request", function() { + it("should queue the next request", () => { expect(mockAjax.requests.count()).toEqual(2); }); - it("should allow access to the other queued request", function() { + it("should allow access to the other queued request", () => { expect(mockAjax.requests.first()).toEqual(request); expect(mockAjax.requests.mostRecent()).toEqual(anotherRequest); }); }); - describe("mockAjax.requests.mostRecent()", function() { + describe("mockAjax.requests.mostRecent()", () => { - describe("when there is one request queued", function() { - it("should return the request", function() { + describe("when there is one request queued", () => { + it("should return the request", () => { expect(mockAjax.requests.mostRecent()).toEqual(request); }); }); - describe("when there is more than one request", function() { - beforeEach(function() { + describe("when there is more than one request", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -851,37 +848,37 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { anotherRequest = mockAjax.requests.mostRecent(); }); - it("should return the most recent request", function() { + it("should return the most recent request", () => { expect(mockAjax.requests.mostRecent()).toEqual(anotherRequest); }); }); - describe("when there are no requests", function() { - beforeEach(function() { + describe("when there are no requests", () => { + beforeEach(() => { mockAjax.requests.reset(); }); - it("should return null", function() { + it("should return null", () => { expect(mockAjax.requests.mostRecent()).toBeUndefined(); }); }); }); - describe("clearAjaxRequests()", function() { - beforeEach(function() { + describe("clearAjaxRequests()", () => { + beforeEach(() => { mockAjax.requests.reset(); }); - it("should remove all requests", function() { + it("should remove all requests", () => { expect(mockAjax.requests.count()).toEqual(0); expect(mockAjax.requests.mostRecent()).toBeUndefined(); }); }); }); - describe("when simulating a response with request.response", function() { - describe("and the response is Success", function() { - beforeEach(function() { + describe("when simulating a response with request.response", () => { + describe("and the response is Success", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -900,23 +897,23 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedContext.responseType = response.responseType; }); - it("should call the success handler", function() { + it("should call the success handler", () => { expect(success).toHaveBeenCalled(); }); - it("should not call the failure handler", function() { + it("should not call the failure handler", () => { expect(error).not.toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); sharedAjaxResponseBehaviorForZepto_Success(sharedContext); }); - describe("and the response is Success, but with JSON", function() { - beforeEach(function() { + describe("and the response is Success, but with JSON", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -938,19 +935,19 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { response = success.calls.mostRecent().args[2]; }); - it("should call the success handler", function() { + it("should call the success handler", () => { expect(success).toHaveBeenCalled(); }); - it("should not call the failure handler", function() { + it("should not call the failure handler", () => { expect(error).not.toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); - it("should return a JavaScript object for XHR2 response", function() { + it("should return a JavaScript object for XHR2 response", () => { var responseText = sharedContext.responseText; expect(success.calls.mostRecent().args[0]).toEqual(responseText); @@ -961,8 +958,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedAjaxResponseBehaviorForZepto_Success(sharedContext); }); - describe("and the response is Success, and response is overriden", function() { - beforeEach(function() { + describe("and the response is Success, and response is overriden", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -984,7 +981,7 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { response = success.calls.mostRecent().args[2]; }); - it("should return the provided override for the XHR2 response", function() { + it("should return the provided override for the XHR2 response", () => { var responseText = sharedContext.responseText; expect(response.responseText).toEqual(responseText); @@ -994,8 +991,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedAjaxResponseBehaviorForZepto_Success(sharedContext); }); - describe("response with unique header names using an object", function() { - beforeEach(function() { + describe("response with unique header names using an object", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com"); @@ -1013,13 +1010,13 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { response = success.calls.mostRecent().args[2]; }); - it("getResponseHeader should return the each value", function() { + it("getResponseHeader should return the each value", () => { expect(response.getResponseHeader('X-Header1')).toBe('header 1 value'); expect(response.getResponseHeader('X-Header2')).toBe('header 2 value'); expect(response.getResponseHeader('X-Header3')).toBe('header 3 value'); }); - it("getAllResponseHeaders should return all values", function() { + it("getAllResponseHeaders should return all values", () => { expect(response.getAllResponseHeaders()).toBe([ "X-Header1: header 1 value", "X-Header2: header 2 value", @@ -1028,8 +1025,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { }); }); - describe("response with multiple headers of the same name using an array of objects", function() { - beforeEach(function() { + describe("response with multiple headers of the same name using an array of objects", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com"); @@ -1046,11 +1043,11 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { response = success.calls.mostRecent().args[2]; }); - it("getResponseHeader should return all values comma separated", function() { + it("getResponseHeader should return all values comma separated", () => { expect(response.getResponseHeader('X-Header')).toBe('header value 1, header value 2'); }); - it("getAllResponseHeaders should return all values", function() { + it("getAllResponseHeaders should return all values", () => { expect(response.getAllResponseHeaders()).toBe([ "X-Header: header value 1", "X-Header: header value 2" @@ -1058,8 +1055,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { }); }); - describe("the content type defaults to application/json", function() { - beforeEach(function() { + describe("the content type defaults to application/json", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -1078,23 +1075,23 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedContext.responseText = response.responseText; }); - it("should call the success handler", function() { + it("should call the success handler", () => { expect(success).toHaveBeenCalled(); }); - it("should not call the failure handler", function() { + it("should not call the failure handler", () => { expect(error).not.toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); sharedAjaxResponseBehaviorForZepto_Success(sharedContext); }); - describe("and the status/response code is 0", function() { - beforeEach(function() { + describe("and the status/response code is 0", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -1113,15 +1110,15 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedContext.responseType = response.responseType; }); - it("should call the success handler", function() { + it("should call the success handler", () => { expect(success).not.toHaveBeenCalled(); }); - it("should not call the failure handler", function() { + it("should not call the failure handler", () => { expect(error).toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); @@ -1129,8 +1126,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { }); }); - describe("and the response is error", function() { - beforeEach(function() { + describe("and the response is error", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -1138,7 +1135,7 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { client.send(); request = mockAjax.requests.mostRecent(); - response = { status: 500, statusText: "SERVER ERROR", contentType: "text/html", responseText: "(._){",responseType: "json"}; + response = { status: 500, statusText: "SERVER ERROR", contentType: "text/html", responseText: "(._){", responseType: "json"}; request.respondWith(response); sharedContext.responseCallback = error; @@ -1149,23 +1146,23 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedContext.responseType = response.responseType; }); - it("should not call the success handler", function() { + it("should not call the success handler", () => { expect(success).not.toHaveBeenCalled(); }); - it("should call the failure handler", function() { + it("should call the failure handler", () => { expect(error).toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); sharedAjaxResponseBehaviorForZepto_Failure(sharedContext); }); - describe('when simulating a response with request.responseTimeout', function() { - beforeEach(function() { + describe('when simulating a response with request.responseTimeout', () => { + beforeEach(() => { jasmine.clock().install(); client = new fakeGlobal.XMLHttpRequest(); @@ -1186,19 +1183,19 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedContext.responseType = response.responseType; }); - afterEach(function() { + afterEach(() => { jasmine.clock().uninstall(); }); - it("should not call the success handler", function() { + it("should not call the success handler", () => { expect(success).not.toHaveBeenCalled(); }); - it("should call the failure handler", function() { + it("should call the failure handler", () => { expect(error).toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); }); @@ -1206,74 +1203,74 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { function sharedAjaxResponseBehaviorForZepto_Success(context) { - describe("the success response", function() { + describe("the success response", () => { var xhr; - beforeEach(function() { + beforeEach(() => { xhr = context.responseCallback.calls.mostRecent().args[2]; }); - it("should have the expected status code", function() { + it("should have the expected status code", () => { expect(xhr.status).toEqual(context.status); }); - it("should have the expected content type", function() { + it("should have the expected content type", () => { expect(xhr.getResponseHeader('Content-Type')).toEqual(context.contentType); }); - it("should have the expected xhr2 response", function() { + it("should have the expected xhr2 response", () => { var expected = context.response || context.responseType === 'json' ? JSON.parse(context.responseText) : context.responseText; expect(xhr.response).toEqual(expected); }); - it("should have the expected response text", function() { + it("should have the expected response text", () => { expect(xhr.responseText).toEqual(context.responseText); }); - it("should have the expected status text", function() { + it("should have the expected status text", () => { expect(xhr.statusText).toEqual(context.statusText); }); }); } function sharedAjaxResponseBehaviorForZepto_Failure(context) { - describe("the failure response", function() { + describe("the failure response", () => { var xhr; - beforeEach(function() { + beforeEach(() => { xhr = context.responseCallback.calls.mostRecent().args[0]; }); - it("should have the expected status code", function() { + it("should have the expected status code", () => { expect(xhr.status).toEqual(context.status); }); - it("should have the expected content type", function() { + it("should have the expected content type", () => { expect(xhr.getResponseHeader('Content-Type')).toEqual(context.contentType); }); - it("should have the expected xhr2 response", function() { + it("should have the expected xhr2 response", () => { var expected = context.response || xhr.responseType === 'json' ? JSON.parse(xhr.responseText) : xhr.responseText; expect(xhr.response).toEqual(expected); }); - it("should have the expected response text", function() { + it("should have the expected response text", () => { expect(xhr.responseText).toEqual(context.responseText); }); - it("should have the expected status text", function() { + it("should have the expected status text", () => { expect(xhr.statusText).toEqual(context.statusText); }); }); } -describe('ParamParser', function() { - beforeEach(function() { +describe('ParamParser', () => { + beforeEach(() => { var Constructor = getJasmineRequireObj().AjaxParamParser(); expect(Constructor).toEqual(jasmine.any(Function)); this.parser = new Constructor(); }); - it('has a default parser', function() { - var parser = this.parser.findParser({ contentType: function() { } }), + it('has a default parser', () => { + var parser = this.parser.findParser({ contentType: () => { } }), parsed = parser.parse('3+stooges=shemp&3+stooges=larry%20%26%20moe%20%26%20curly&some%3Dthing=else+entirely'); expect(parsed).toEqual({ @@ -1282,7 +1279,7 @@ describe('ParamParser', function() { }); }); - it('should detect and parse json', function() { + it('should detect and parse json', () => { var data = { foo: 'bar', baz: ['q', 'u', 'u', 'x'], @@ -1292,13 +1289,13 @@ describe('ParamParser', function() { } } }, - parser = this.parser.findParser({ contentType: function() { return 'application/json'; } }), + parser = this.parser.findParser({ contentType: () => 'application/json' }), parsed = parser.parse(JSON.stringify(data)); expect(parsed).toEqual(data); }); - it('should parse json with further qualifiers on content-type', function() { + it('should parse json with further qualifiers on content-type', () => { var data = { foo: 'bar', baz: ['q', 'u', 'u', 'x'], @@ -1308,13 +1305,13 @@ describe('ParamParser', function() { } } }, - parser = this.parser.findParser({ contentType: function() { return 'application/json; charset=utf-8'; } }), + parser = this.parser.findParser({ contentType: () => 'application/json; charset=utf-8' }), parsed = parser.parse(JSON.stringify(data)); expect(parsed).toEqual(data); }); - it('should have custom parsers take precedence', function() { + it('should have custom parsers take precedence', () => { var custom = { test: jasmine.createSpy('test').and.returnValue(true), parse: jasmine.createSpy('parse').and.returnValue('parsedFormat') @@ -1322,7 +1319,7 @@ describe('ParamParser', function() { this.parser.add(custom); - var parser = this.parser.findParser({ contentType: function() { } }), + var parser = this.parser.findParser({ contentType: () => { } }), parsed = parser.parse('custom_format'); expect(parsed).toEqual('parsedFormat'); @@ -1330,7 +1327,7 @@ describe('ParamParser', function() { expect(custom.parse).toHaveBeenCalledWith('custom_format'); }); - it('should skip custom parsers that do not match', function() { + it('should skip custom parsers that do not match', () => { var custom = { test: jasmine.createSpy('test').and.returnValue(false), parse: jasmine.createSpy('parse').and.returnValue('parsedFormat') @@ -1338,7 +1335,7 @@ describe('ParamParser', function() { this.parser.add(custom); - var parser = this.parser.findParser({ contentType: function() { } }), + var parser = this.parser.findParser({ contentType: () => { } }), parsed = parser.parse('custom_format'); expect(parsed).toEqual({ custom_format: ['undefined'] }); @@ -1346,7 +1343,7 @@ describe('ParamParser', function() { expect(custom.parse).not.toHaveBeenCalled(); }); - it('removes custom parsers when reset', function() { + it('removes custom parsers when reset', () => { var custom = { test: jasmine.createSpy('test').and.returnValue(true), parse: jasmine.createSpy('parse').and.returnValue('parsedFormat') @@ -1354,7 +1351,7 @@ describe('ParamParser', function() { this.parser.add(custom); - var parser = this.parser.findParser({ contentType: function() { } }), + var parser = this.parser.findParser({ contentType: () => { } }), parsed = parser.parse('custom_format'); expect(parsed).toEqual('parsedFormat'); @@ -1364,7 +1361,7 @@ describe('ParamParser', function() { this.parser.reset(); - parser = this.parser.findParser({ contentType: function() { } }); + parser = this.parser.findParser({ contentType: () => { } }); parsed = parser.parse('custom_format'); expect(parsed).toEqual({ custom_format: ['undefined'] }); @@ -1373,14 +1370,14 @@ describe('ParamParser', function() { }); }); -describe('RequestStub', function() { - beforeEach(function() { +describe('RequestStub', () => { + beforeEach(() => { this.RequestStub = getJasmineRequireObj().AjaxRequestStub(); jasmine.addMatchers({ - toMatchRequest: function(a, b) { + toMatchRequest(a, b) { return { - compare: function(actual): jasmine.CustomMatcherResult { + compare(actual): jasmine.CustomMatcherResult { return { message: '', pass: actual.matches.apply(actual, Array.prototype.slice.call(arguments, 1)) @@ -1391,31 +1388,31 @@ describe('RequestStub', function() { }); }); - it('matches just by exact url', function() { + it('matches just by exact url', () => { var stub = new this.RequestStub('www.example.com/foo'); expect(stub)['toMatchRequest']('www.example.com/foo'); }); - it('does not match if the url differs', function() { + it('does not match if the url differs', () => { var stub = new this.RequestStub('www.example.com/foo'); expect(stub).not['toMatchRequest']('www.example.com/bar'); }); - it('matches unordered query params', function() { + it('matches unordered query params', () => { var stub = new this.RequestStub('www.example.com?foo=bar&baz=quux'); expect(stub)['toMatchRequest']('www.example.com?baz=quux&foo=bar'); }); - it('requires all specified query params to be there', function() { + it('requires all specified query params to be there', () => { var stub = new this.RequestStub('www.example.com?foo=bar&baz=quux'); expect(stub).not['toMatchRequest']('www.example.com?foo=bar'); }); - it('can match the url with a RegExp', function() { + it('can match the url with a RegExp', () => { var stub = new this.RequestStub(/ba[rz]/); expect(stub)['toMatchRequest']('bar'); @@ -1423,7 +1420,7 @@ describe('RequestStub', function() { expect(stub).not['toMatchRequest']('foo'); }); - it('requires the method to match if supplied', function() { + it('requires the method to match if supplied', () => { var stub = new this.RequestStub('www.example.com/foo', null, 'POST'); expect(stub).not['toMatchRequest']('www.example.com/foo'); @@ -1431,7 +1428,7 @@ describe('RequestStub', function() { expect(stub)['toMatchRequest']('www.example.com/foo', null, 'POST'); }); - it('requires the data submitted to match if supplied', function() { + it('requires the data submitted to match if supplied', () => { var stub = new this.RequestStub('/foo', 'foo=bar&baz=quux'); expect(stub)['toMatchRequest']('/foo', 'baz=quux&foo=bar'); @@ -1439,13 +1436,13 @@ describe('RequestStub', function() { }); }); -describe('RequestTracker', function() { - beforeEach(function() { +describe('RequestTracker', () => { + beforeEach(() => { var Constructor = getJasmineRequireObj().AjaxRequestTracker(); this.tracker = new Constructor(); }); - it('tracks the number of times ajax requests are made', function() { + it('tracks the number of times ajax requests are made', () => { expect(this.tracker.count()).toBe(0); this.tracker.track(); @@ -1453,29 +1450,29 @@ describe('RequestTracker', function() { expect(this.tracker.count()).toBe(1); }); - it('simplifies access to the last (most recent) request', function() { + it('simplifies access to the last (most recent) request', () => { this.tracker.track(); this.tracker.track('request'); expect(this.tracker.mostRecent()).toEqual('request'); }); - it('returns a useful falsy value when there is no last (most recent) request', function() { + it('returns a useful falsy value when there is no last (most recent) request', () => { expect(this.tracker.mostRecent()).toBeFalsy(); }); - it('simplifies access to the first (oldest) request', function() { + it('simplifies access to the first (oldest) request', () => { this.tracker.track('request'); this.tracker.track(); expect(this.tracker.first()).toEqual('request'); }); - it('returns a useful falsy value when there is no first (oldest) request', function() { + it('returns a useful falsy value when there is no first (oldest) request', () => { expect(this.tracker.first()).toBeFalsy(); }); - it('allows the requests list to be reset', function() { + it('allows the requests list to be reset', () => { this.tracker.track(); this.tracker.track(); @@ -1486,7 +1483,7 @@ describe('RequestTracker', function() { expect(this.tracker.count()).toBe(0); }); - it('allows retrieval of an arbitrary request by index', function() { + it('allows retrieval of an arbitrary request by index', () => { this.tracker.track('1'); this.tracker.track('2'); this.tracker.track('3'); @@ -1494,14 +1491,14 @@ describe('RequestTracker', function() { expect(this.tracker.at(1)).toEqual('2'); }); - it('allows retrieval of all requests that are for a given url', function() { + it('allows retrieval of all requests that are for a given url', () => { this.tracker.track({ url: 'foo' }); this.tracker.track({ url: 'bar' }); expect(this.tracker.filter('bar')).toEqual([{ url: 'bar' }]); }); - it('allows retrieval of all requests that match a given RegExp', function() { + it('allows retrieval of all requests that match a given RegExp', () => { this.tracker.track({ url: 'foo' }); this.tracker.track({ url: 'bar' }); this.tracker.track({ url: 'baz' }); @@ -1509,29 +1506,27 @@ describe('RequestTracker', function() { expect(this.tracker.filter(/ba[rz]/)).toEqual([{ url: 'bar' }, { url: 'baz' }]); }); - it('allows retrieval of all requests that match based on a function', function() { + it('allows retrieval of all requests that match based on a function', () => { this.tracker.track({ url: 'foo' }); this.tracker.track({ url: 'bar' }); this.tracker.track({ url: 'baz' }); - var func = function(request) { - return request.url === 'bar'; - }; + var func = request => request.url === 'bar'; expect(this.tracker.filter(func)).toEqual([{ url: 'bar' }]); }); - it('filters to nothing if no requests have been tracked', function() { + it('filters to nothing if no requests have been tracked', () => { expect(this.tracker.filter('foo')).toEqual([]); }); }); -describe('EventBus', function() { - beforeEach(function() { +describe('EventBus', () => { + beforeEach(() => { this.bus = getJasmineRequireObj().AjaxEventBus()(); }); - it('calls an event listener', function() { + it('calls an event listener', () => { var callback = jasmine.createSpy('callback'); this.bus.addEventListener('foo', callback); @@ -1540,7 +1535,7 @@ describe('EventBus', function() { expect(callback).toHaveBeenCalled(); }); - it('calls an event listener with additional arguments', function() { + it('calls an event listener with additional arguments', () => { var callback = jasmine.createSpy('callback'); this.bus.addEventListener('foo', callback); @@ -1549,7 +1544,7 @@ describe('EventBus', function() { expect(callback).toHaveBeenCalledWith('bar'); }); - it('only triggers callbacks for the specified event', function() { + it('only triggers callbacks for the specified event', () => { var fooCallback = jasmine.createSpy('foo'), barCallback = jasmine.createSpy('bar'); @@ -1562,7 +1557,7 @@ describe('EventBus', function() { expect(barCallback).not.toHaveBeenCalled(); }); - it('calls all the callbacks for the specified event', function() { + it('calls all the callbacks for the specified event', () => { var callback1 = jasmine.createSpy('callback'); var callback2 = jasmine.createSpy('otherCallback'); @@ -1575,14 +1570,14 @@ describe('EventBus', function() { expect(callback2).toHaveBeenCalled(); }); - it('works if there are no callbacks for the event', function() { + it('works if there are no callbacks for the event', () => { var bus = this.bus; - expect(function() { + expect(() => { bus.trigger('notActuallyThere'); }).not.toThrow(); }); - it('does not call listeners that have been removed', function() { + it('does not call listeners that have been removed', () => { var callback = jasmine.createSpy('callback'); this.bus.addEventListener('foo', callback); @@ -1592,7 +1587,7 @@ describe('EventBus', function() { expect(callback).not.toHaveBeenCalled(); }); - it('only removes the specified callback', function() { + it('only removes the specified callback', () => { var callback1 = jasmine.createSpy('callback'); var callback2 = jasmine.createSpy('otherCallback'); @@ -1607,14 +1602,14 @@ describe('EventBus', function() { }); }); -describe("Webmock style mocking", function() { +describe("Webmock style mocking", () => { var successSpy, errorSpy, response, fakeGlobal, mockAjax; var sendRequest = function(fakeGlobal, url?, method?) { url = url || "http://example.com/someApi"; method = method || 'GET'; var xhr = new fakeGlobal.XMLHttpRequest(); - xhr.onreadystatechange = function(args) { + xhr.onreadystatechange = args => { if (this.readyState === (this.DONE || 4)) { // IE 8 doesn't support DONE response = this; successSpy(); @@ -1625,7 +1620,7 @@ describe("Webmock style mocking", function() { xhr.send(); }; - beforeEach(function() { + beforeEach(() => { successSpy = jasmine.createSpy('success'); fakeGlobal = { XMLHttpRequest: jasmine.createSpy('realXMLHttpRequest') }; mockAjax = new MockAjax(fakeGlobal); @@ -1634,33 +1629,33 @@ describe("Webmock style mocking", function() { mockAjax.stubRequest("http://example.com/someApi").andReturn({ responseText: "hi!" }); }); - it("allows a url to be setup as a stub", function() { + it("allows a url to be setup as a stub", () => { sendRequest(fakeGlobal); expect(successSpy).toHaveBeenCalled(); }); - it("should allow you to clear all the ajax stubs", function() { + it("should allow you to clear all the ajax stubs", () => { mockAjax.stubs.reset(); sendRequest(fakeGlobal); expect(successSpy).not.toHaveBeenCalled(); }); - it("should set the contentType", function() { + it("should set the contentType", () => { sendRequest(fakeGlobal); expect(response.getResponseHeader('Content-Type')).toEqual('application/json'); }); - it("should set the responseText", function() { + it("should set the responseText", () => { sendRequest(fakeGlobal); expect(response.responseText).toEqual('hi!'); }); - it("should default the status to 200", function() { + it("should default the status to 200", () => { sendRequest(fakeGlobal); expect(response.status).toEqual(200); }); - it("should set the responseHeaders", function() { + it("should set the responseHeaders", () => { mockAjax.stubRequest("http://example.com/someApi").andReturn({ responseText: "hi!", responseHeaders: [{ name: "X-Custom", value: "header value" }] @@ -1669,37 +1664,37 @@ describe("Webmock style mocking", function() { expect(response.getResponseHeader('X-Custom')).toEqual('header value'); }); - describe("with another stub for the same url", function() { - beforeEach(function() { + describe("with another stub for the same url", () => { + beforeEach(() => { mockAjax.stubRequest("http://example.com/someApi").andReturn({ responseText: "no", status: 403 }); sendRequest(fakeGlobal); }); - it("should set the status", function() { + it("should set the status", () => { expect(response.status).toEqual(403); }); - it("should allow the latest stub to win", function() { + it("should allow the latest stub to win", () => { expect(response.responseText).toEqual('no'); }); }); }); -describe("withMock", function() { - var sendRequest = function(fakeGlobal) { +describe("withMock", () => { + var sendRequest = fakeGlobal => { var xhr = new fakeGlobal.XMLHttpRequest(); xhr.open("GET", "http://example.com/someApi"); xhr.send(); }; - it("installs the mock for passed in function, and uninstalls when complete", function() { + it("installs the mock for passed in function, and uninstalls when complete", () => { var xmlHttpRequest = jasmine.createSpyObj('XMLHttpRequest', ['open', 'send']), - xmlHttpRequestCtor = spyOn(window, 'XMLHttpRequest').and.returnValue(xmlHttpRequest), + xmlHttpRequestCtor = spyOn(window as any, 'XMLHttpRequest').and.returnValue(xmlHttpRequest), fakeGlobal = { XMLHttpRequest: xmlHttpRequestCtor }, mockAjax = new MockAjax(fakeGlobal); - mockAjax.withMock(function() { + mockAjax.withMock(() => { sendRequest(fakeGlobal); expect(xmlHttpRequest.open).not.toHaveBeenCalled(); }); @@ -1708,15 +1703,15 @@ describe("withMock", function() { expect(xmlHttpRequest.open).toHaveBeenCalled(); }); - it("properly uninstalls when the passed in function throws", function() { + it("properly uninstalls when the passed in function throws", () => { var xmlHttpRequest = jasmine.createSpyObj('XMLHttpRequest', ['open', 'send']), - xmlHttpRequestCtor = spyOn(window, 'XMLHttpRequest').and.returnValue(xmlHttpRequest), + xmlHttpRequestCtor = spyOn(window as any, 'XMLHttpRequest').and.returnValue(xmlHttpRequest), fakeGlobal = { XMLHttpRequest: xmlHttpRequestCtor }, mockAjax = new MockAjax(fakeGlobal); - expect(function() { - mockAjax.withMock(function() { - throw "error"; + expect(() => { + mockAjax.withMock(() => { + throw "error"; // tslint:disable-line:no-string-throw }); }).toThrow("error"); @@ -1725,8 +1720,8 @@ describe("withMock", function() { }); }); -describe("mockAjax", function() { - it("throws an error if installed multiple times", function() { +describe("mockAjax", () => { + it("throws an error if installed multiple times", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); @@ -1739,7 +1734,7 @@ describe("mockAjax", function() { expect(doubleInstall).toThrow(); }); - it("does not throw an error if uninstalled between installs", function() { + it("does not throw an error if uninstalled between installs", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); @@ -1753,7 +1748,7 @@ describe("mockAjax", function() { expect(sequentialInstalls).not.toThrow(); }); - it("does not replace XMLHttpRequest until it is installed", function() { + it("does not replace XMLHttpRequest until it is installed", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); @@ -1767,7 +1762,7 @@ describe("mockAjax", function() { expect(fakeXmlHttpRequest).not.toHaveBeenCalled(); }); - it("replaces the global XMLHttpRequest on uninstall", function() { + it("replaces the global XMLHttpRequest on uninstall", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); @@ -1779,14 +1774,14 @@ describe("mockAjax", function() { expect(fakeXmlHttpRequest).toHaveBeenCalledWith('foo'); }); - it("clears requests and stubs upon uninstall", function() { + it("clears requests and stubs upon uninstall", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); mockAjax.install(); - mockAjax.requests.track({ url: '/testurl' }); + mockAjax.requests.track( { url: '/testurl' }); mockAjax.stubRequest('/bobcat'); expect(mockAjax.requests.count()).toEqual(1); @@ -1798,25 +1793,25 @@ describe("mockAjax", function() { expect(mockAjax.stubs.findStub('/bobcat')).not.toBeDefined(); }); - it("allows the httpRequest to be retrieved", function() { + it("allows the httpRequest to be retrieved", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); mockAjax.install(); - var request = new (fakeGlobal.XMLHttpRequest)(); + var request = new ( fakeGlobal.XMLHttpRequest)(); expect(mockAjax.requests.count()).toBe(1); expect(mockAjax.requests.mostRecent()).toBe(request); }); - it("allows the httpRequests to be cleared", function() { + it("allows the httpRequests to be cleared", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); mockAjax.install(); - var request = new (fakeGlobal.XMLHttpRequest)(); + var request = new ( fakeGlobal.XMLHttpRequest)(); expect(mockAjax.requests.mostRecent()).toBe(request); mockAjax.requests.reset(); diff --git a/jasmine-ajax/tslint.json b/jasmine-ajax/tslint.json new file mode 100644 index 0000000000..fe03bea79d --- /dev/null +++ b/jasmine-ajax/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false, + "unified-signatures": false + } +} diff --git a/jasmine-data_driven_tests/index.d.ts b/jasmine-data_driven_tests/index.d.ts index 9874f61cb8..827539a3a9 100644 --- a/jasmine-data_driven_tests/index.d.ts +++ b/jasmine-data_driven_tests/index.d.ts @@ -1,7 +1,39 @@ -// Type definitions for Jasmine Data Driven Tests +// Type definitions for Jasmine Data Driven Tests 1.0 // Project: https://github.com/gburghardt/jasmine-data_driven_tests // Definitions by: Anthony MacKinnon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 -declare function all(description: string, dataset: any[], assertion: (...args: any[]) => void): void; -declare function xall(description: string, dataset: any[], assertion: (...args: any[]) => void): void; \ No newline at end of file +declare var all: JasmineDataDrivenTest; +declare var xall: JasmineDataDrivenTest; + +interface JasmineDataDrivenTest { + ( + description: string, + dataset: Array<[T, U, V, W, X, Y, Z]>, + assertion: (arg0: T, arg1: U, arg2: V, arg3: W, arg4: X, arg5: Y, arg6: Z, done: () => void) => void): void; + ( + description: string, + dataset: Array<[T, U, V, W, X, Y]>, + assertion: (arg0: T, arg1: U, arg2: V, arg3: W, arg4: X, arg5: Y, done: () => void) => void): void; + ( + description: string, + dataset: Array<[T, U, V, W, X]>, + assertion: (arg0: T, arg1: U, arg2: V, arg3: W, arg4: X, done: () => void) => void): void; + ( + description: string, + dataset: Array<[T, U, V, W]>, + assertion: (arg0: T, arg1: U, arg2: V, arg3: W, done: () => void) => void): void; + ( + description: string, + dataset: Array<[T, U, V]>, + assertion: (arg0: T, arg1: U, arg2: V, done: () => void) => void): void; + ( + description: string, + dataset: Array<[T, U]>, + assertion: (arg0: T, arg1: U, done: () => void) => void): void; + ( + description: string, + dataset: T[], + assertion: (value: T, done: () => void) => void): void; +} diff --git a/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts b/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts index 27509d7383..727c253ad3 100644 --- a/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts +++ b/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts @@ -1,9 +1,8 @@ - /// all("A data driven test is a suite with multiple specs", ['a', 'b', 'c'], - (value: string) => { + value => { expect(value).not.toBe('d'); } ); @@ -13,7 +12,7 @@ all("A data driven test can have many arguments", [1, 2, 3], [2, 4, 6] ], - (a: number, b: number, c: number) => { + (a, b, c) => { expect(c - (a + b)).toBe(0); } ); @@ -23,7 +22,7 @@ all("A data driven test can be asynchronous", [3, 1], [5, 2] ], - (a: number, b: number, done: () => void) => { + (a, b, done) => { setTimeout(() => { expect(a - b > 0).toBe(true); done(); @@ -33,7 +32,7 @@ all("A data driven test can be asynchronous", xall("A data driven test can be pending", [1, 2, 3], - (value: number) => { + value => { expect(value < 4).toBe(true); } ); @@ -47,7 +46,7 @@ describe("A suite", () => { all("can contain data driven tests", [1, 2, 3], - (b: number) => { + b => { expect(a - b > 0).toBe(true); } ); diff --git a/jasmine-data_driven_tests/tslint.json b/jasmine-data_driven_tests/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/jasmine-data_driven_tests/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/jasmine-fixture/index.d.ts b/jasmine-fixture/index.d.ts index 77d9c740b1..8ea5956f1e 100644 --- a/jasmine-fixture/index.d.ts +++ b/jasmine-fixture/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jasmine-fixture 1.0.7 +// Type definitions for Jasmine-fixture 1.0 // Project: https://github.com/searls/jasmine-fixture // Definitions by: Craig Brett // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/jasmine-fixture/tslint.json b/jasmine-fixture/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/jasmine-fixture/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/jasmine/package.json b/jasmine/package.json new file mode 100644 index 0000000000..7e47d54c61 --- /dev/null +++ b/jasmine/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "typescript": ">=2.1.4" + } +} \ No newline at end of file diff --git a/jasminewd2/jasminewd2-tests.ts b/jasminewd2/jasminewd2-tests.ts index c6612ae422..e201ed3cc0 100644 --- a/jasminewd2/jasminewd2-tests.ts +++ b/jasminewd2/jasminewd2-tests.ts @@ -95,9 +95,9 @@ describe('jasminewd', () => { describe('jasmine matchers', () => { it('should be able to add matchers', () => { let matchers = { - toBeLotsMoreThan: function() { + toBeLotsMoreThan() { return { - compare: function(actual: number, expected: number) { + compare(actual: number, expected: number) { return { pass: actual > expected + 100 }; @@ -105,9 +105,9 @@ describe('jasminewd', () => { }; }, // Example custom matcher returning a promise that resolves to true/false. - toBeDisplayed: function() { + toBeDisplayed() { return { - compare: function(actual: any, expected: void) { + compare(actual: any, expected: void) { return { pass: (actual.isDisplayed() as Promise) }; diff --git a/jasminewd2/tslint.json b/jasminewd2/tslint.json index 9ca86427bd..e689d36e71 100644 --- a/jasminewd2/tslint.json +++ b/jasminewd2/tslint.json @@ -1,6 +1,8 @@ { "extends": "../tslint.json", "rules": { - "callable-types": false + "callable-types": false, + "prefer-const": false, + "void-return": false } } diff --git a/jenkins/jenkins-tests.ts b/jenkins/jenkins-tests.ts index c3def89156..0b409a4b87 100644 --- a/jenkins/jenkins-tests.ts +++ b/jenkins/jenkins-tests.ts @@ -2,19 +2,19 @@ import * as J from 'jenkins'; const jenkins = J({ baseUrl: 'http://user:pass@localhost:8080', crumbIssuer: true }); -jenkins.info(function(err, data) { +jenkins.info((err, data) => { if (err) throw err; console.log('info', data); }); -jenkins.build.get('example', 1, function(err, data) { +jenkins.build.get('example', 1, (err, data) => { if (err) throw err; console.log('build', data); }); -jenkins.build.log('example', 1, function(err, data) { +jenkins.build.log('example', 1, (err, data) => { if (err) throw err; console.log('log', data); @@ -22,181 +22,181 @@ jenkins.build.log('example', 1, function(err, data) { var log = jenkins.build.logStream('example', 1); -log.on('data', function(text: string) { +log.on('data', (text: string) => { process.stdout.write(text); }); -log.on('error', function(err: Error) { +log.on('error', (err: Error) => { console.log('error', err); }); -log.on('end', function() { +log.on('end', () => { console.log('end'); }); -jenkins.build.stop('example', 1, function(err) { +jenkins.build.stop('example', 1, (err) => { if (err) throw err; }); -jenkins.job.build('example', function(err, data) { +jenkins.job.build('example', (err, data) => { if (err) throw err; console.log('queue item number', data); }); -jenkins.job.build({ name: 'example', parameters: { name: 'value' } }, function(err) { +jenkins.job.build({ name: 'example', parameters: { name: 'value' } }, (err) => { if (err) throw err; }); -jenkins.job.config('example', function(err, data) { +jenkins.job.config('example', (err, data) => { if (err) throw err; console.log('xml', data); }); -jenkins.job.config('example', '', function(err) { +jenkins.job.config('example', '', (err) => { if (err) throw err; }); -jenkins.job.copy('fromJob', 'example', function(err) { +jenkins.job.copy('fromJob', 'example', (err) => { if (err) throw err; }); -jenkins.job.create('example', '', function(err) { +jenkins.job.create('example', '', (err) => { if (err) throw err; }); -jenkins.job.destroy('example', function(err) { +jenkins.job.destroy('example', (err) => { if (err) throw err; }); -jenkins.job.disable('example', function(err) { +jenkins.job.disable('example', (err) => { if (err) throw err; }); -jenkins.job.enable('example', function(err) { +jenkins.job.enable('example', (err) => { if (err) throw err; }); -jenkins.job.exists('example', function(err, exists) { +jenkins.job.exists('example', (err, exists) => { if (err) throw err; console.log('exists', exists); }); -jenkins.job.get('example', function(err, data) { +jenkins.job.get('example', (err, data) => { if (err) throw err; console.log('job', data); }); -jenkins.job.list(function(err, data) { +jenkins.job.list((err, data) => { if (err) throw err; console.log('jobs', data); }); -jenkins.node.config('example', function(err, data) { +jenkins.node.config('example', (err, data) => { if (err) throw err; console.log('xml', data); }); -jenkins.node.create('slave', function(err) { +jenkins.node.create('slave', (err) => { if (err) throw err; }); -jenkins.node.destroy('slave', function(err) { +jenkins.node.destroy('slave', (err) => { if (err) throw err; }); -jenkins.node.disconnect('slave', 'no longer used', function(err) { +jenkins.node.disconnect('slave', 'no longer used', (err) => { if (err) throw err; }); -jenkins.node.disable('slave', 'network failure', function(err) { +jenkins.node.disable('slave', 'network failure', (err) => { if (err) throw err; }); -jenkins.node.enable('slave', function(err) { +jenkins.node.enable('slave', (err) => { if (err) throw err; }); -jenkins.node.exists('slave', function(err, exists) { +jenkins.node.exists('slave', (err, exists) => { if (err) throw err; console.log('exists', exists); }); -jenkins.node.get('slave', function(err, data) { +jenkins.node.get('slave', (err, data) => { if (err) throw err; console.log('node', data); }); -jenkins.node.list(function(err, data) { +jenkins.node.list((err, data) => { if (err) throw err; console.log('nodes', data); }); -jenkins.queue.list(function(err, data) { +jenkins.queue.list((err, data) => { if (err) throw err; console.log('queues', data); }); -jenkins.queue.item(130, function(err, data) { +jenkins.queue.item(130, (err, data) => { if (err) throw err; console.log('item', data); }); -jenkins.queue.cancel(23, function(err) { +jenkins.queue.cancel(23, (err) => { if (err) throw err; }); -jenkins.view.config('example', function(err, data) { +jenkins.view.config('example', (err, data) => { if (err) throw err; console.log('xml', data); }); -jenkins.view.config('example', '', function(err) { +jenkins.view.config('example', '', (err) => { if (err) throw err; }); -jenkins.view.create('example', 'list', function(err) { +jenkins.view.create('example', 'list', (err) => { if (err) throw err; }); -jenkins.view.destroy('example', function(err) { +jenkins.view.destroy('example', (err) => { if (err) throw err; }); -jenkins.view.exists('example', function(err, exists) { +jenkins.view.exists('example', (err, exists) => { if (err) throw err; console.log('exists', exists); }); -jenkins.view.get('example', function(err, data) { +jenkins.view.get('example', (err, data) => { if (err) throw err; console.log('view', data); }); -jenkins.view.list(function(err, data) { +jenkins.view.list((err, data) => { if (err) throw err; console.log('views', data); }); -jenkins.view.add('example', 'jobExample', function(err) { +jenkins.view.add('example', 'jobExample', (err) => { if (err) throw err; }); -jenkins.view.remove('example', 'jobExample', function(err) { +jenkins.view.remove('example', 'jobExample', (err) => { if (err) throw err; }); diff --git a/jfs/jfs-tests.ts b/jfs/jfs-tests.ts index 0deebbd4a4..d53d1305a2 100644 --- a/jfs/jfs-tests.ts +++ b/jfs/jfs-tests.ts @@ -8,19 +8,19 @@ interface TestStore { const db = new Store('data', {type: 'memory'}); // save with custom ID -db.save('bar', 123, function(err, id) { +db.save('bar', 123, (err, id) => { // now the data is stored in the file data/anId.json }); // save with generated ID -db.save(333, function(err, id) { +db.save(333, (err, id) => { // id is a unique ID }); // save synchronously db.saveSync('foo', 'test'); -db.get('bar', function(err, obj) { +db.get('bar', (err, obj) => { // obj = { foo: ''bar' } }); @@ -28,7 +28,7 @@ db.get('bar', function(err, obj) { const val = db.getSync('bar'); // get all available objects -db.all(function(err, objs) { +db.all((err, objs) => { // objs is a map: ID => OBJECT }); @@ -36,7 +36,7 @@ db.all(function(err, objs) { var objs = db.allSync(); // delete by ID -db.delete('foo', function(err) { +db.delete('foo', err => { // the file data/myId.json was removed }); diff --git a/jfs/tslint.json b/jfs/tslint.json index ec365f164b..377cc837d4 100644 --- a/jfs/tslint.json +++ b/jfs/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/jimp/index.d.ts b/jimp/index.d.ts new file mode 100644 index 0000000000..b8988e2ad4 --- /dev/null +++ b/jimp/index.d.ts @@ -0,0 +1,207 @@ +// Type definitions for jimp 0.2 +// Project: https://github.com/oliver-moran/jimp#readme +// Definitions by: Jack Works +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace jimp { + type Callback = (this: JimpImage, err: Error, data: T) => void; + type ResizeMode = string; + type PresetFont = string; + type FileMINE = string; + type AlignMode = number; + type FilterType = number; + + // Used in font info provided by parse-bmfont-ascii + type FontBoolean = 0 | 1; + interface FontChar { + id: number; + x: number; + y: number; + weight: number; + height: number; + xoffset: number; + yoffset: number; + xadvance: number; + page: number; + chnl: number; + } + type Font = { + common: {lineHeight: number, base: number, scaleW: number, scaleH: number, pages: number, packed: number}, + info: { + face: string, + size: number, + bold: FontBoolean, + italic: FontBoolean, + charset: string, + unicode: FontBoolean, + stretchH: number, + smooth: FontBoolean, + aa: number, + padding: [number, number, number, number], + spacing: [number, number] + }, + kernings: any, + pages: JIMP[], + chars: { + [char: number]: FontChar, + [char: string]: FontChar + } + } | PresetFont; + + + class JimpImage { + constructor(width: number, height: number, callback?: Callback); + constructor(width: number, height: number, initialColor: number, callback?: Callback); + + /* Get/set meta data */ + hash(n?: number): string; + + getExtension(): string; + getMIME(): FileMINE; + + getPixelColor(x: number, y: number): number; + setPixelColor(hex: number, x: number, y: number): void; + + /* Save */ + write(path: string, callback?: Callback): void; + getBase64(mine: FileMINE, callback?: Callback): void; + getBuffer(mine: FileMINE, callback?: Callback): void; + + /* Parameter */ + quality(n: number): JimpImage; + rgba(is: boolean): JimpImage; + filterType(type: FilterType): JimpImage; + deflateLevel(level: number): JimpImage; + + /* Operation */ + clone(): JimpImage; + print(font: Font, x: number, y: number, text: string, width?: number): JimpImage; + + /* Adv */ + color( + params: Array<{ + apply: 'lighten' | 'brighten' | 'darken' | 'desaturate' | 'saturate' | 'greyscale' | 'spin' | 'hue' | 'tint' | 'shade' | 'red' | 'green' | 'blue', + params: [number] + } | { + apply: 'mix', + params: [string, number] + } | { + apply: 'xor', + params: [string] + }>): JimpImage; + + convolution(matrix: number[][]): JimpImage; + scan(x: number, y: number, width: number, height: number, callback?: (this: JimpImage, x: number, y: number, idx: number) => void): JimpImage; + + /* Low level data */ + bitmap: {data: Buffer, readonly width: number, readonly height: number}; + readonly _originalMime: string; + + /* Resize */ + contain(width: number, height: number, callback?: Callback): JimpImage; + contain(width: number, height: number, alignBitsOrMode?: number | ResizeMode, callback?: Callback): JimpImage; + contain(width: number, height: number, alignBits: number, mode?: ResizeMode, callback?: Callback): JimpImage; + + cover(width: number, height: number, callback?: Callback): JimpImage; + cover(width: number, height: number, alignBitsOrmode?: ResizeMode | number, callback?: Callback): JimpImage; + cover(width: number, height: number, alignBits: number, mode?: ResizeMode, callback?: Callback): JimpImage; + + resize(width: number, height: number, callback?: Callback): JimpImage; + resize(width: number, height: number, mode?: ResizeMode, callback?: Callback): JimpImage; + + scale(factor: any, callback?: Callback): JimpImage; + scale(factor: any, mode?: ResizeMode, callback?: Callback): JimpImage; + + scaleToFit(width: number, height: number, callback?: Callback): JimpImage; + scaleToFit(width: number, height: number, mode?: ResizeMode, callback?: Callback): JimpImage; + + /* Crop */ + autocrop(callback?: Callback): JimpImage; + crop(x: number, y: number, width: number, height: number, callback?: Callback): JimpImage; + + /* Composing */ + blit(scr: string, x: number, y: number, callback?: Callback): JimpImage; + blit(scr: string, x: number, y: number, srcx?: number, srcy?: number, callback?: Callback): JimpImage; + blit(scr: string, x: number, y: number, srcx?: number, srcy?: number, srcw?: number, srch?: number, callback?: Callback): JimpImage; + + composite(scr: string, x: number, y: number, callback?: Callback): JimpImage; + mask(scr: string, x: number, y: number, callback?: Callback): JimpImage; + + /* Flip and rotate */ + flip(horz: any, vert: any, callback?: Callback): JimpImage; + mirror(horz: any, vert: any, callback?: Callback): JimpImage; + rotate(deg: number, callback?: Callback): JimpImage; + rotate(deg: number, mode?: any, callback?: Callback): JimpImage; + + /* Colour */ + brightness(val: number, callback?: Callback): JimpImage; + contrast(val: number, callback?: Callback): JimpImage; + dither565(callback?: Callback): JimpImage; + greyscale(callback?: Callback): JimpImage; + invert(callback?: Callback): JimpImage; + normalize(callback?: Callback): JimpImage; + + /* Alpha channel */ + fade(val: number, callback?: Callback): JimpImage; + opacity(val: number, callback?: Callback): JimpImage; + opaque(callback?: Callback): JimpImage; + background(hex: number, callback?: Callback): JimpImage; + + /* Blurs */ + gaussian(pixel: number, callback?: Callback): JimpImage; + blur(pixel: number, callback?: Callback): JimpImage; + + /* Effects */ + posterize(level: number, callback?: Callback): JimpImage; + sepia(callback?: Callback): JimpImage; + } + class JIMP extends JimpImage { + static read(path: string | Buffer, callback?: Callback): Promise; + static loadFont(path: string | PresetFont, callback?: Callback): Promise; + static rgbaToInt(r: number, g: number, b: number, alpha: number): number; + static intToRGBA(hex: number): {r: number, g: number, b: number, a: number}; + static distance(image: JimpImage, image2: JimpImage): number; + static diff(image1: JimpImage, image2: JimpImage, threshold?: number): {image: JimpImage, percent: number}; + static deflateStrategy(deflate: number): void; + + static readonly RESIZE_NEAREST_NEIGHBOR: ResizeMode; + static readonly RESIZE_BILINEAR: ResizeMode; + static readonly RESIZE_BICUBIC: ResizeMode; + static readonly RESIZE_HERMITE: ResizeMode; + static readonly RESIZE_BEZIER: ResizeMode; + + static readonly FONT_SANS_8_BLACK: PresetFont; + static readonly FONT_SANS_16_BLACK: PresetFont; + static readonly FONT_SANS_32_BLACK: PresetFont; + static readonly FONT_SANS_64_BLACK: PresetFont; + static readonly FONT_SANS_128_BLACK: PresetFont; + + static readonly FONT_SANS_8_WHITE: PresetFont; + static readonly FONT_SANS_16_WHITE: PresetFont; + static readonly FONT_SANS_32_WHITE: PresetFont; + static readonly FONT_SANS_64_WHITE: PresetFont; + static readonly FONT_SANS_128_WHITE: PresetFont; + + static readonly MIME_PNG: FileMINE; + static readonly MIME_JPEG: FileMINE; + static readonly MIME_BMP: FileMINE; + static readonly AUTO: number; + + static readonly HORIZONTAL_ALIGN_LEFT: AlignMode; + static readonly HORIZONTAL_ALIGN_CENTER: AlignMode; + static readonly HORIZONTAL_ALIGN_RIGHT: AlignMode; + static readonly VERTICAL_ALIGN_TOP: AlignMode; + static readonly VERTICAL_ALIGN_MIDDLE: AlignMode; + static readonly VERTICAL_ALIGN_BOTTOM: AlignMode; + + static readonly PNG_FILTER_AUTO: FilterType; + static readonly PNG_FILTER_NONE: FilterType; + static readonly PNG_FILTER_SUB: FilterType; + static readonly PNG_FILTER_UP: FilterType; + static readonly PNG_FILTER_AVERAGE: FilterType; + static readonly PNG_FILTER_PAETH: FilterType; + } +} +export = jimp.JIMP; diff --git a/jimp/jimp-tests.ts b/jimp/jimp-tests.ts new file mode 100644 index 0000000000..180ce27d7f --- /dev/null +++ b/jimp/jimp-tests.ts @@ -0,0 +1,215 @@ +import Jimp = require('jimp') + +// All code below is from node-jimp document +Jimp.read("lenna.png", function (err, data) { + if (err) throw err; + data.resize(256, 256) // resize + .quality(60) // set JPEG quality + .greyscale() // set greyscale + .write("lena-small-bw.jpg"); // save +}); + +Jimp.read("lenna.png").then(function (lenna) { + lenna.resize(256, 256) // resize + .quality(60) // set JPEG quality + .greyscale() // set greyscale + .write("lena-small-bw.jpg"); // save +}).catch(function (err) { + console.error(err); +}); + +Jimp.read("./path/to/image.jpg", function (err, image) { + // do stuff with the image (if no exception) +}); + +Jimp.read("./path/to/image.jpg").then(function (image) { + // do stuff with the image +}).catch(function (err) { + // handle an exception +}); + +Jimp.read(new Buffer(''), function (err, image) { + // do stuff with the image (if no exception) +}); + +Jimp.read("http://www.example.com/path/to/lenna.jpg", function (err, image) { + // do stuff with the image (if no exception) +}); + +var image = new Jimp(1, 2) +var w = 0 +var h = 0 +var x = 0 +var y = 0 +var f = 0 +var src = '' +var horz = Jimp.HORIZONTAL_ALIGN_CENTER +var vert = Jimp.VERTICAL_ALIGN_BOTTOM +var deg = 90 +var val = 0.5 +var hex = 0xFFFFFFFF +var r = 0 +var n = 1 +/* Resize */ +image.contain( w, h); // scale the image to the given width and height, some parts of the image may be letter boxed +image.cover( w, h); // scale the image to the given width and height, some parts of the image may be clipped +image.resize( w, h); // resize the image. Jimp.AUTO can be passed as one of the values. +image.scale(f ); // scale the image by the factor f +image.scaleToFit( w, h ); // scale the image to the largest size that fits inside the given width and height + +// An optional resize mode can be passed with all resize methods. + +/* Crop */ +image.autocrop(); // automatically crop same-color borders from image (if any) +image.crop( x, y, w, h ); // crop to the given region + +/* Composing */ +image.blit( src, x, y ); + // blit the image with another Jimp image at x, y, optionally cropped. +image.composite( src, x, y ); // composites another Jimp image over this image at x, y +image.mask( src, x, y ); // masks the image with another Jimp image at x, y using average pixel value + +/* Flip and rotate */ +image.flip( horz, vert ); // flip the image horizontally or vertically +image.mirror( horz, vert ); // an alias for flip +image.rotate( deg ); // rotate the image clockwise by a number of degrees. Optionally, a resize mode can be passed. If `false` is passed as the second parameter, the image width and height will not be resized. + +// JPEG images with EXIF orientation data will be automatically re-orientated as appropriate. + +/* Colour */ +image.brightness( val ); // adjust the brighness by a value -1 to +1 +image.contrast( val ); // adjust the contrast by a value -1 to +1 +image.dither565(); // ordered dithering of the image and reduce color space to 16-bits (RGB565) +image.greyscale(); // remove colour from the image +image.invert(); // invert the image colours +image.normalize(); // normalize the channels in an image + +/* Alpha channel */ +image.fade( f ); // an alternative to opacity, fades the image by a factor 0 - 1. 0 will haven no effect. 1 will turn the image +image.opacity( f ); // multiply the alpha channel by each pixel by the factor f, 0 - 1 +image.opaque(); // set the alpha channel on every pixel to fully opaque +image.background( hex ); // set the default new pixel colour (e.g. 0xFFFFFFFF or 0x00000000) for by some operations (e.g. image.contain and + +/* Blurs */ +image.gaussian( r ); // Gaussian blur the image by r pixels (VERY slow) +image.blur( r ); // fast blur the image by r pixels + +/* Effects */ +image.posterize( n ); // apply a posterization effect with n level +image.sepia(); // apply a sepia wash to the image + +image.clone(); // returns a clone of the image +image.resize(250, 250); // resize the image to 250 x 250 +image.resize(Jimp.AUTO, 250); // resize the height to 250 and scale the width accordingly +image.resize(250, Jimp.AUTO); // resize the width to 250 and scale the height accordingly + +image.resize(250, 250, Jimp.RESIZE_BEZIER); + +image.contain(250, 250, Jimp.HORIZONTAL_ALIGN_LEFT | Jimp.VERTICAL_ALIGN_TOP); + +var path = '' +var str = '' +var width = 0 +Jimp.loadFont( path ).then(function (font) { // load font from .fnt file + image.print(font, x, y, str); // print a message on an image + image.print(font, x, y, str, width); // print a message on an image with text wrapped at width +}); + +var cb = (err: Error, data: any) => {} +Jimp.loadFont( path, cb ); // using a callback pattern + +Jimp.loadFont(Jimp.FONT_SANS_32_BLACK).then(function (font) { + image.print(font, 10, 10, "Hello world!"); +}); + +image.write( path, cb ); // Node-style callback will be fired when write is successful + +var file = "new_name." + image.getExtension(); +image.write(file) + + +var mime = 'image/png' +image.getBuffer( mime, cb ); // Node-style callback will be fired with result +image.getBase64( mime, cb ); // Node-style callback will be fired with result +image.quality( n ); // set the quality of saved JPEG, 0 - 100 + +var bool = true +var number = 0 +image.rgba( bool ); // set whether PNGs are saved as RGBA (true, default) or RGB (false) +image.filterType( number ); // set the filter type for the saved PNG +image.deflateLevel( number ); // set the deflate level for the saved PNG +Jimp.deflateStrategy( number ); // set the deflate for the saved PNG (0-3) + +image.color([ + { apply: 'hue', params: [ -90 ] }, + { apply: 'lighten', params: [ 50 ] }, + { apply: 'xor', params: [ '#06D' ] } +]); + image.convolution([ + [-2,-1, 0], + [-1, 1, 1], + [ 0, 1, 2] + ]) +image.scan(0, 0, image.bitmap.width, image.bitmap.height, function (x, y, idx) { + // x, y is the position of this pixel on the image + // idx is the position start position of this rgba tuple in the bitmap Buffer + // this is the image + + var red = this.bitmap.data[ idx + 0 ]; + var green = this.bitmap.data[ idx + 1 ]; + var blue = this.bitmap.data[ idx + 2 ]; + var alpha = this.bitmap.data[ idx + 3 ]; + + // rgba values run from 0 - 255 + // e.g. this.bitmap.data[idx] = 0; // removes red from this pixel +}); +image.getPixelColor(x, y); // returns the colour of that pixel e.g. 0xFFFFFFFF +image.setPixelColor(hex, x, y); // sets the colour of that pixel + +var g = 0 +var b = 0 +var a = 0 +Jimp.rgbaToInt(r, g, b, a); // e.g. converts 255, 255, 255, 255 to 0xFFFFFFFF +Jimp.intToRGBA(hex); // e.g. converts 0xFFFFFFFF to {r: 255, g: 255, b: 255, a:255} + +var image = new Jimp(256, 256, function (err, image) { + // this image is 256 x 256, every pixel is set to 0x00000000 +}); + +var image = new Jimp(256, 256, 0xFF0000FF, function (err, image) { + // this image is 256 x 256, every pixel is set to 0xFF0000FF +}); + +image.hash(); // aHgG4GgoFjA +image.hash(2); // 1010101011010000101010000100101010010000011001001001010011100100 + +var image1 = new Jimp(0, 1) +var image2 = new Jimp(0, 1) +Jimp.distance(image1, image2); // returns a number 0-1, where 0 means the two images are perceived to be identical + +var threshold = 0 +var diff = Jimp.diff(image1, image2, threshold); // threshold ranges 0-1 (default: 0.1) +diff.image; // a Jimp image showing differences +diff.percent; // the proportion of different pixels (0-1), where 0 means the images are pixel identical + + +var distance = Jimp.distance(image, image2); // perceived distance +var diff = Jimp.diff(image, image2); // pixel difference + +if (distance < 0.15 || diff.percent < 0.15) { + // images match +} else { + // not a match +} + +Jimp.read("lenna.png", function (err, image) { + this.greyscale().scale(0.5).write("lena-half-bw.png"); +}); + +Jimp.read("lenna.png", function (err, image) { + image.greyscale(function(err, image) { + image.scale(0.5, function (err, image) { + image.write("lena-half-bw.png"); + }); + }); +}); \ No newline at end of file diff --git a/jimp/tsconfig.json b/jimp/tsconfig.json new file mode 100644 index 0000000000..d03d20f554 --- /dev/null +++ b/jimp/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jimp-tests.ts" + ] +} diff --git a/jimp/tslint.json b/jimp/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/jimp/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/joi/index.d.ts b/joi/index.d.ts index 55e6b9c75f..fe1f0e39f8 100644 --- a/joi/index.d.ts +++ b/joi/index.d.ts @@ -91,6 +91,12 @@ export interface IpOptions { cidr?: string; } +export type GuidVersions = 'uuidv1' | 'uuidv2' | 'uuidv3' | 'uuidv4' | 'uuidv5' + +export interface GuidOptions { + version: GuidVersions[] | GuidVersions +} + export interface UriOptions { /** * Specifies one or more acceptable Schemes, should only include the scheme name. @@ -443,7 +449,7 @@ export interface StringSchema extends AnySchema { /** * Requires the string value to be a valid GUID. */ - guid(): StringSchema; + guid(options?: GuidOptions): StringSchema; /** * Requires the string value to be a valid hexadecimal string. diff --git a/joi/joi-tests.ts b/joi/joi-tests.ts index 59eb446b2f..3a222ff832 100644 --- a/joi/joi-tests.ts +++ b/joi/joi-tests.ts @@ -691,6 +691,8 @@ strSchema = strSchema.ip(ipOpts); strSchema = strSchema.uri(); strSchema = strSchema.uri(uriOpts); strSchema = strSchema.guid(); +strSchema = strSchema.guid({version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5']}); +strSchema = strSchema.guid({version: 'uuidv4'}); strSchema = strSchema.hex(); strSchema = strSchema.hostname(); strSchema = strSchema.isoDate(); diff --git a/jointjs/index.d.ts b/jointjs/index.d.ts index aec9f1237d..c8ef9ae302 100644 --- a/jointjs/index.d.ts +++ b/jointjs/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Joint JS 1.0.1 // Project: http://www.jointjs.com/ -// Definitions by: Aidan Reel , David Durman , Ewout Van Gossum , Federico Caselli +// Definitions by: Aidan Reel , David Durman , Ewout Van Gossum , Federico Caselli , Chris Moran // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // typings: https://github.com/CaselIT/typings-jointjs @@ -188,6 +188,7 @@ declare namespace joint { vertices?: Point[]; smooth?: boolean; attrs?: TextAttrs; + z?: number; } class Link extends Cell { @@ -249,6 +250,7 @@ declare namespace joint { cellViewNamespace?: Object; /** useful undocumented option */ clickThreshold?: number; + highlighting?: any; } interface ScaleContentOptions { @@ -466,40 +468,319 @@ declare namespace joint { cy?: string | number; height?: string | number; width?: string | number; + transform?: string; + points?: string; + 'stroke-width'?: string | number; + 'ref-x'?: string | number; + 'ref-y'?: string | number; + ref?: string } + namespace basic { class Generic extends dia.Element { - constructor(attributes?: GenericAttributes, options?: Object) + constructor(attributes?: GenericAttributes, options?: Object); } interface RectAttrs extends dia.TextAttrs { rect?: ShapeAttrs; } class Rect extends Generic { - constructor(attributes?: GenericAttributes, options?: Object) + constructor(attributes?: GenericAttributes, options?: Object); } class Text extends Generic { - constructor(attributes?: GenericAttributes, options?: Object) + constructor(attributes?: GenericAttributes, options?: Object); } interface CircleAttrs extends dia.TextAttrs { circle?: ShapeAttrs; } class Circle extends Generic { - constructor(attributes?: GenericAttributes, options?: Object) + constructor(attributes?: GenericAttributes, options?: Object); } interface EllipseAttrs extends dia.TextAttrs { ellipse?: ShapeAttrs; } class Ellipse extends Generic { - constructor(attributes?: GenericAttributes, options?: Object) + constructor(attributes?: GenericAttributes, options?: Object); } - class Image extends Generic { - } - class Path extends Generic { + interface PolygonAttrs extends dia.TextAttrs { + polygon?: ShapeAttrs; } class Polygon extends Generic { + constructor(attributes?: GenericAttributes, options?: Object); + } + interface PolylineAttrs extends dia.TextAttrs { + polyline?: ShapeAttrs; } class Polyline extends Generic { } + class Image extends Generic { + constructor(attributes?: GenericAttributes, options?: Object); + } + interface PathAttrs extends dia.TextAttrs { + path?: ShapeAttrs; + } + class Path extends Generic { + constructor(attributes?: GenericAttributes, options?: Object); + } + interface RhombusAttrs extends dia.TextAttrs { + path?: ShapeAttrs; + } + class Rhombus extends Generic { + constructor(attributes?: GenericAttributes, options?: Object); + } + interface TextBlockAttrs extends dia.TextAttrs { + rect?: ShapeAttrs; + } + class TextBlock extends Generic { + constructor(attributes?: GenericAttributes, options?: Object); + updateSize(cell: dia.Cell, size: dia.Size): void; + updateContent(cell: dia.Cell, content: string): void; + } + } + + namespace chess { + class KingWhite extends basic.Generic { + } + class KingBlack extends basic.Generic { + } + class QueenWhite extends basic.Generic { + } + class QueenBlack extends basic.Generic { + } + class RookWhite extends basic.Generic { + } + class RookBlack extends basic.Generic { + } + class BishopWhite extends basic.Generic { + } + class BishopBlack extends basic.Generic { + } + class KnightWhite extends basic.Generic { + } + class KnightBlack extends basic.Generic { + } + class PawnWhite extends basic.Generic { + } + class PawnBlack extends basic.Generic { + } + } + + namespace devs { + interface ModelAttributes extends GenericAttributes { + inPorts?: string[]; + outPorts?: string[]; + ports?: Object; + } + class Model extends basic.Generic { + constructor(attributes?: ModelAttributes, options?: Object); + changeInGroup(properties: any, opt?: any): boolean; + changeOutGroup(properties: any, opt?: any): boolean; + createPortItem(group: string, port: string): any; + createPortItems(group: string, ports: string[]): any[]; + addOutPort(port: string, opt?: any): this; + addInPort(port: string, opt?: any): this; + removeOutPort(port: string, opt?: any): this; + removeInPort(port: string, opt?: any): this; + } + class Coupled extends Model { + } + class Atomic extends Model { + } + class Link extends dia.Link { + } + } + + namespace erd { + class Entity extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); + } + class WeakEntity extends Entity { + } + class Relationship extends dia.Element { + constructor(attributes?: GenericAttributes, options?: Object); + } + class IdentifyingRelationship extends Relationship { + } + interface AttributeAttrs extends dia.TextAttrs { + ellipse?: ShapeAttrs; + } + class Attribute extends dia.Element { + constructor(attributes?: GenericAttributes, options?: Object); + } + class Multivalued extends Attribute { + } + class Derived extends Attribute { + } + class Key extends Attribute { + } + class Normal extends Attribute { + } + interface ISAAttrs extends dia.Element { + polygon?: ShapeAttrs; + } + class ISA extends dia.Element { + constructor(attributes?: GenericAttributes, options?: Object); + } + class Line extends dia.Link { + cardinality(value: string | number): void; + } + } + + namespace fsa { + class State extends basic.Circle { + } + class StartState extends dia.Element { + constructor(attributes?: GenericAttributes, options?: Object); + } + class EndState extends dia.Element { + } + class Arrow extends dia.Link { + } + } + + namespace logic { + interface LogicAttrs extends ShapeAttrs { + ref?: string; + 'ref-x'?: number | string; + 'ref-dx'?: number | string; + 'ref-y'?: number | string; + 'ref-dy'?: number | string; + magnet?: boolean; + 'class'?: string; + port?: string; + } + interface IOAttrs extends dia.TextAttrs { + circle?: LogicAttrs; + } + class Gate extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); + } + class IO extends Gate { + } + class Input extends IO { + } + class Output extends IO { + } + class Gate11 extends Gate { + } + class Gate21 extends Gate { + } + interface Image { + 'xlink:href'?: string; + } + interface ImageAttrs extends LogicAttrs { + image?: Image; + } + class Repeater extends Gate11 { + constructor(attributes?: GenericAttributes, options?: Object); + operation(input: any): any; + } + class Note extends Gate11 { + constructor(attributes?: GenericAttributes, options?: Object); + operation(input: any): boolean; + } + class Or extends Gate21 { + constructor(attributes?: GenericAttributes, options?: Object); + operation(input1: any, input2: any): boolean; + } + class And extends Gate21 { + constructor(attributes?: GenericAttributes, options?: Object); + operation(input1: any, input2: any): boolean; + } + class Nor extends Gate21 { + constructor(attributes?: GenericAttributes, options?: Object); + operation(input1: any, input2: any): boolean; + } + class Nand extends Gate21 { + constructor(attributes?: GenericAttributes, options?: Object); + operation(input1: any, input2: any): boolean; + } + class Xor extends Gate21 { + constructor(attributes?: GenericAttributes, options?: Object); + operation(input1: any, input2: any): boolean; + } + class Xnor extends Gate21 { + constructor(attributes?: GenericAttributes, options?: Object); + operation(input1: any, input2: any): boolean; + } + interface WireArgs extends dia.LinkAttributes { + router?: Object; + connector?: Object; + } + class Wire extends dia.Link { + constructor(attributes?: WireArgs, options?: Object); + } + } + + namespace org { + interface MemberAttrs { + rect?: ShapeAttrs; + image?: ShapeAttrs; + } + class Member extends dia.Element { + constructor(attributes?: GenericAttributes, options?: Object); + } + class Arrow extends dia.Link { + } + } + + namespace pn { + class Place extends basic.Generic { + } + class PlaceView extends dia.ElementView { + renderTokens(): void; + } + class Transition extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); + } + class Link extends dia.Link { + } + } + + namespace uml { + interface ClassAttributes extends GenericAttributes { + name: string[]; + attributes: string[]; + methods: string[]; + } + class Class extends basic.Generic { + constructor(attributes?: ClassAttributes, options?: Object); + getClassName(): string[]; + updateRectangles(): void; + } + class ClassView extends dia.ElementView { + } + class Abstract extends Class { + } + class AbstractView extends ClassView { + } + class Interface extends Class { + } + class InterfaceView extends ClassView { + } + class Generalization extends dia.Link { + } + class Implementation extends dia.Link { + } + class Aggregation extends dia.Link { + } + class Composition extends dia.Link { + } + class Association extends dia.Link { + } + interface StateAttributes extends GenericAttributes { + events?: string[]; + } + class State extends basic.Generic { + updateName(): void; + updateEvents(): void; + updatePath(): void; + } + class StartState extends basic.Circle { + } + class EndState extends basic.Generic { + } + class Transition extends dia.Link { + } } } @@ -553,7 +834,7 @@ declare namespace joint { } class DirectedGraph { - static layout(graph: dia.Graph, options?: LayoutOptions): dia.BBox; + static layout(graph: dia.Graph | dia.Cell[], options?: LayoutOptions): dia.BBox; } } -} \ No newline at end of file +} diff --git a/jquery-mask-plugin/jquery-mask-plugin-tests.ts b/jquery-mask-plugin/jquery-mask-plugin-tests.ts index 269bc0719e..36362eccf7 100644 --- a/jquery-mask-plugin/jquery-mask-plugin-tests.ts +++ b/jquery-mask-plugin/jquery-mask-plugin-tests.ts @@ -1,6 +1,6 @@ // basic usage -$(document).ready(function () { +$(document).ready(() => { $('.date').mask('00/00/0000'); $('.time').mask('00:00:00'); $('.date_time').mask('00/00/0000 00:00:00'); @@ -15,7 +15,7 @@ $(document).ready(function () { $('.money2').mask("#.##0,00", { reverse: true }); $('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', { translation: { - 'Z': { + Z: { pattern: /[0-9]/, optional: true } } @@ -30,7 +30,7 @@ $(document).ready(function () { }); $('.fallback').mask("00r00r0000", { translation: { - 'r': { + r: { pattern: /[\/]/, fallback: '/' }, @@ -42,17 +42,17 @@ $(document).ready(function () { // callback examples let options: jQueryMask.Options = { - onComplete: function (cep: Object) { + onComplete(cep: Object) { alert('CEP Completed!:' + cep); }, - onKeyPress: function (cep: Object, event: Event, currentField: JQuery, options: jQueryMask.Options) { + onKeyPress(cep: Object, event: Event, currentField: JQuery, options: jQueryMask.Options) { console.log('An key was pressed!:', cep, ' event: ', event, 'currentField: ', currentField, ' options: ', options); }, - onChange: function (cep: Object) { + onChange(cep: Object) { console.log('cep changed! ', cep); }, - onInvalid: function (val: Object, e: Event, f: JQuery, invalid: jQueryMask.Invalid[], options: jQueryMask.Options) { + onInvalid(val: Object, e: Event, f: JQuery, invalid: jQueryMask.Invalid[], options: jQueryMask.Options) { var error = invalid[0]; console.log("Digit: ", error.v, " is invalid for the position: ", error.p, ". We expect something like: ", error.e); } @@ -62,9 +62,9 @@ $('.cep_with_callback').mask('00000-000', options); // on the fly mask changed options = { - onKeyPress: function (cep, e, field, options) { - let masks: string[] = ['00000-000', '0-00-00-00']; - let mask: string = (cep.length > 7) ? masks[1] : masks[0]; + onKeyPress(cep, e, field, options) { + const masks: string[] = ['00000-000', '0-00-00-00']; + const mask: string = (cep.length > 7) ? masks[1] : masks[0]; $('.crazy_cep').mask(mask, options); } }; @@ -72,12 +72,12 @@ options = { $('.crazy_cep').mask('00000-000', options); // mask as a function -let maskBehavior: (value: string) => string = function (val: string) { +let maskBehavior: (value: string) => string = val => { return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009'; }; options = { - onKeyPress: function(val: string, e: Event, field: JQuery, options: jQueryMask.Options) { + onKeyPress(val: string, e: Event, field: JQuery, options: jQueryMask.Options) { field.mask(maskBehavior.apply({}, arguments), options); } }; @@ -87,13 +87,13 @@ $('.sp_celphones').mask(maskBehavior, options); // translation // now the digit 0 on your mask pattern will be interpreted // as valid characters like 0,1,2,3,4,5,6,7,8,9 and * -$('.your-field').mask('00/00/0000', {'translation': {0: {pattern: /[0-9*]/}}}); +$('.your-field').mask('00/00/0000', {translation: {0: {pattern: /[0-9*]/}}}); // optional digits // way 1 $('.ip_address').mask('099.099.099.099'); // way 2 -$('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', {translation: {'Z': {pattern: /[0-9]/, optional: true}}}); +$('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', {translation: {Z: {pattern: /[0-9]/, optional: true}}}); // recursive digits $('.money_example').mask('#.##0,00', {reverse: true}); @@ -101,7 +101,7 @@ $('.money_example').mask('#.##0,00', {reverse: true}); // fallback digits $('.field_with_fallback').mask("00r00r0000", { translation: { - 'r': { + r: { pattern: /[\/]/, fallback: '/' }, diff --git a/jquery-mask-plugin/tslint.json b/jquery-mask-plugin/tslint.json index 192203ab54..f05741c59b 100644 --- a/jquery-mask-plugin/tslint.json +++ b/jquery-mask-plugin/tslint.json @@ -1,3 +1,6 @@ { - "extends": "../tslint.json" -} \ No newline at end of file + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/jquery.tools/index.d.ts b/jquery.tools/index.d.ts new file mode 100644 index 0000000000..e511a961fd --- /dev/null +++ b/jquery.tools/index.d.ts @@ -0,0 +1,161 @@ +// Type definitions for jQuery TOOLS 1.2 +// Project: https://github.com/jquerytools/jquerytools +// Definitions by: Joe Skeen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/// + +declare interface JQuery { + overlay(opts?: JQueryTools.overlay.OverlayOptions): JQuery; + overlay(opts?: JQueryTools.overlay.OverlayOptions): T; + data(key: 'overlay'): JQueryTools.overlay.Overlay; +} + +declare interface JQueryStatic { + tools: JQueryTools.ToolsStatic; +} + +/** jQuery Tools (http://jquerytools.github.io/documentation/overlay/index.html) */ +declare namespace JQueryTools { + interface ToolsStatic { + overlay: overlay.OverlayStatic; + } + + namespace overlay { + interface OverlayStatic { + addEffect(effectName: string, + effectFn: (this: Overlay, position: CssOptions, done: () => void) => void, + closeFn: (this: Overlay, done: () => void) => void): void; + } + + interface CssOptions { + [key: string]: any; + } + + interface OverlayOptions { + /** + * A jQuery selector for the closing elements inside the overlay. These + * can be any elements such as links, buttons or images. If this is not + * supplied, a close element is auto-generated. Read more about this in + * defining close actions. + */ + close?: JQuery; + /** + * By default, overlays are closed when the mouse is clicked outside the + * overlay area. Setting this property to false suppresses this behaviour + * which is suitable for modal dialogs. + * @default true + */ + closeOnClick?: boolean; + /** + * By default, overlays are closed when the ESC keyboard key is pressed. + * Setting this property to false suppresses this behaviour. + * @default true + */ + closeOnEsc?: boolean; + /** The speed to close the overlay, in milliseconds */ + closeSpeed?: number; + /** + * The effect to be used when an overlay is opened and closed. This can + * dramatically change the behaviour of the overlay. By default this tool + * uses an effect called "default" which is a simple show/hide effect. + * @default 'default' + */ + effect?: string; + /** + * since 1.2.0. whether overlay stays in the same position while the screen + * is scrolled. This is the default behaviour for all browsers except IE6 + * and below. IE6 does not support fixed positioning. If this property is + * set to false then the overlay is positioned in relationship to the document + * so that when the screen is scrolled then the overlay moves along with the document. + * @default true + */ + fixed?: boolean; + /** + * Previously known as expose. Overlay is very often used together with the + * Mask Tool. Because of this, the support for this feature has been built + * inside the tool. This option accepts the mask configuration. This is either + * a simple string specifying the background color of the mask or a more complex + * object literal specifying more configuration variables. See an example of an + * overlay together with mask. By default masking is disabled. + */ + mask?: string | MaskOptions; + /** + * Specifies how far from the left-hand edge of the screen the overlay should be + * placed. By default the overlay is horizontally centered with the value "center" + * but you can also supply a numerical value specifying a distance in pixels. + * @default 'center' + */ + left?: 'center' | number; + /** + * If enabled then the overlay loads immediately after it has been initialized. + * @default false + */ + load?: boolean; + /** + * By default, there can be only one overlay on the page at once. Setting this + * property to false allows you to have multiple overlay instances. + * @default true + */ + oneInstance?: boolean; + /** + * The speed of the fade-in animation on the "default" effect. Valid values are + * 'slow', 'normal' and 'fast', or you can supply a numerical value (in milliseconds). + * By setting this property to 0, the overlay will appear immediately without any animation. + * @default 'normal' + */ + speed?: 'slow' | 'normal' | 'fast' | number; + /** + * The element to be overlayed (if not specified in the rel attribute of the triggering element). + */ + target?: Element; + /** + * Specifies how far from the top edge of the screen the overlay should be placed. + * Acceptable values are an integer number specifying a distance in pixels, a string + * (such as '15%') specifying a percentage value or "center" in which case the overlay + * is vertically centered. Percentage values work consistently at different screen resolutions. + * @default '10%' + */ + top?: string | number; + + /** + * before the overlay is displayed. The overlay has already been positioned at the + * location from where it will start animating. + */ + onBeforeLoad?: (this: Overlay, event: JQueryEventObject) => void; + /** when the overlay has completely been displayed */ + onLoad?: (this: Overlay, event: JQueryEventObject) => void; + /** before the overlay is closed */ + onBeforeClose?: (this: Overlay, event: JQueryEventObject) => void; + /** when the overlay is closed */ + onClose?: (this: Overlay, event: JQueryEventObject) => void; + } + + interface MaskOptions { + /** CSS color string (i.e. hex value) */ + color?: string; + /** load speed in milliseconds */ + loadSpeed?: number; + /** Opacity of mask. Between 0 and 1. */ + opacity?: number; + } + + interface Overlay { + /** Closes the overlay. */ + close(): Overlay; + /** Returns the closing element(s) as a jQuery object. */ + getClosers(): JQuery; + /** Returns the configuration for the overlay. */ + getConf(): OverlayOptions; + /** Returns the overlayed element as a jQuery object. */ + getOverlay(): JQuery; + /** Returns the triggering element as a jQuery object. */ + getTrigger(): JQuery; + /** Returns `true` if the overlay is opened. */ + isOpened(): boolean; + /** Opens the overlay. */ + load(): Overlay; + } + } +} diff --git a/jquery.tools/jquery.tools-tests.ts b/jquery.tools/jquery.tools-tests.ts new file mode 100644 index 0000000000..f8a4e39f90 --- /dev/null +++ b/jquery.tools/jquery.tools-tests.ts @@ -0,0 +1,182 @@ +/// + +/* from documentation at http://jquerytools.github.io/documentation/overlay/index.html */ + + $("img[rel]").overlay(); + + var triggers = $(".modalInput").overlay({ +  + // some mask tweaks suitable for modal dialogs + mask: { + color: '#ebecff', + loadSpeed: 200, + opacity: 0.9 + }, +  + closeOnClick: false + }); + + var buttons = $("#yesno button").click(function(this: JQuery, e: JQueryEventObject) { +  + // get user input + var yes = buttons.index(this) === 0; +  + // do something with the answer + triggers.eq(0).html("You clicked " + (yes ? "yes" : "no")); + }); + +// select one or more elements to be overlay triggers +$(".my_overlay_trigger").overlay({ + // one configuration property + mask: { + color: '#ccc' + }, + // another property + top: 50 + // ... the rest of the configuration properties +}); + +$("#prompt form").submit(function(this: JQuery, e: JQueryEventObject) { +  + // close the overlay + triggers.eq(1).overlay().close(); + //or more straightforward: + triggers.data('overlay').close(); +  + // get user input + var input = $("input", this).val(); +  + // do something with the answer + triggers.eq(1).html(input); +  + // do not submit the form + return e.preventDefault(); + }); + +$.tools.overlay.addEffect('', function() {}, function() {}); + +/* custom effects */ +$.tools.overlay.addEffect("myEffect", function(position, done) { + /* + - 'this' variable is a reference to the overlay API + - here we use jQuery's fadeIn() method to perform the effect + */ + this.getOverlay().css(position).fadeIn(this.getConf().speed, done); + }, +  + // close function + function(done) { + // fade out the overlay + this.getOverlay().fadeOut(this.getConf().closeSpeed, done); + } +); + +$("#apple img[rel]").overlay({effect: 'apple'}); + + // select the overlay element - and "make it an overlay" + $("#facebox").overlay({ + // custom top position + top: 260, + // some mask tweaks suitable for facebox-looking dialogs + mask: { + // you might also consider a "transparent" color for the mask + color: '#fff', + // load mask a little faster + loadSpeed: 200, + // very transparent + opacity: 0.5 + }, + // disable this for modal dialog-type of overlays + closeOnClick: false, + // load it immediately after the construction + load: true +}); + +$(function() { +  + // if the function argument is given to overlay, + // it is assumed to be the onBeforeLoad event listener + $("a[rel]").overlay({ +  + mask: 'darkred', + effect: 'apple', +  + onBeforeLoad: function() { +  + // grab wrapper element inside content + var wrap = this.getOverlay().find(".contentWrap"); +  + // load the page specified in the trigger + wrap.load(this.getTrigger().attr("href")); + } +  + }); +}); + +$(function() { + // positions for each overlay + var positions = [ + [0, 530], + [400, 20], + [400, 530], + [0, 20] + ]; +  + // setup triggers + $("button[rel]").each(function(this: JQuery, i: number) { +  + $(this).overlay({ +  + // common configuration for each overlay + oneInstance: false, + closeOnClick: false, +  + // setup custom finish position + top: positions[i][0], + left: positions[i][1], +  + // use apple effect + effect: 'apple' +  + }); + }); +}); + +// loading animation +$.tools.overlay.addEffect("drop", function(css, done) { +  + // use Overlay API to gain access to crucial elements + var conf = this.getConf(), + overlay = this.getOverlay(); +  + // determine initial position for the overlay + if (conf.fixed) { + css['position'] = 'fixed'; + } else { + css['top'] += $(window).scrollTop(); + css['left'] += $(window).scrollLeft(); + css['position'] = 'absolute'; + } +  + // position the overlay and show it + overlay.css(css).show(); +  + // begin animating with our custom easing + overlay.animate( + { top: '+=55', opacity: 1, width: '+=20'}, 400, 'drop', done + ); +  + /* closing animation */ +}, function(done) { + this.getOverlay().animate( + {top:'-=55', opacity:0, width:'-=20'}, 300, 'drop', + function(this: JQuery) { + $(this).hide(); + done.call(null); + }); +}); + +$("img[rel]").overlay({ + effect: 'drop', + mask: '#789' +}); diff --git a/jquery.tools/tsconfig.json b/jquery.tools/tsconfig.json new file mode 100644 index 0000000000..64e79cb10d --- /dev/null +++ b/jquery.tools/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jquery.tools-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.tools/tslint.json b/jquery.tools/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/jquery.tools/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/js-data-http/index.d.ts b/js-data-http/index.d.ts index 7fe3b50ff0..2fa9c0e09a 100644 --- a/js-data-http/index.d.ts +++ b/js-data-http/index.d.ts @@ -1,22 +1,20 @@ -// Type definitions for JSData Http Adapter v1.2.0 -// Project: https://github.com/js-data/js-data-http +// Type definitions for JSData Http Adapter 1.2 +// Project: https://github.com/js-data/js-data-http 2.2 // Definitions by: Stefan Steinhart // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - import * as JSData from 'js-data'; declare module 'js-data' { interface DSHttpAdapterOptions { - serialize?: (resourceName:string, data:any)=>any; - deserialize?: (resourceName:string, data:any)=>any; - queryTransform?: (resourceName:string, params:DSFilterParams)=>any; + serialize?: (resourceName: string, data: any) => any; + deserialize?: (resourceName: string, data: any) => any; + queryTransform?: (resourceName: string, params: DSFilterParams) => any; httpConfig?: any; forceTrailingSlash?: boolean; - log?: boolean | ((message?:any, ...optionalParams:any[])=> void); - error?: boolean | ((message?:any, ...optionalParams:any[])=> void); + log?: boolean | ((message?: any, ...optionalParams: any[]) => void); + error?: boolean | ((message?: any, ...optionalParams: any[]) => void); basePath?: string; verbsUseBasePath?: string; } @@ -30,20 +28,20 @@ declare module 'js-data' { interface DSHttpAdapter extends IDSAdapter { - new(options?:DSHttpAdapterOptions):DSHttpAdapter; + new(options?: DSHttpAdapterOptions): DSHttpAdapter; defaults: DSHttpAdapterOptions; http: any; // DSHttpAdapter uses axios so options are axios config objects. - HTTP(options?:Object):JSDataPromise; - DEL(url:string, data?:Object, options?:Object):JSDataPromise; - GET(url:string, data?:Object, options?:Object):JSDataPromise; - POST(url:string, data?:Object, options?:Object):JSDataPromise; - PUT(url:string, data?:Object, options?:Object):JSDataPromise; + HTTP(options?: Object): JSDataPromise; + DEL(url: string, data?: Object, options?: Object): JSDataPromise; + GET(url: string, data?: Object, options?: Object): JSDataPromise; + POST(url: string, data?: Object, options?: Object): JSDataPromise; + PUT(url: string, data?: Object, options?: Object): JSDataPromise; } } -declare var DSHttpAdapter:JSData.DSHttpAdapter; +declare var DSHttpAdapter: JSData.DSHttpAdapter; export = DSHttpAdapter; export as namespace DSHttpAdapter; \ No newline at end of file diff --git a/js-data-http/js-data-http-tests.ts b/js-data-http/js-data-http-tests.ts index 1b863737ea..d98cdd642a 100644 --- a/js-data-http/js-data-http-tests.ts +++ b/js-data-http/js-data-http-tests.ts @@ -1,8 +1,7 @@ -/// import * as JSData from 'js-data'; import DSHttpAdapter = require("js-data-http"); -import * as axios from 'axios'; +declare var axios: any; var adapter = new DSHttpAdapter(); var store = new JSData.DS(); @@ -11,12 +10,12 @@ store.registerAdapter('http', adapter, { default: true }); adapter.defaults.basePath = '/api'; adapter.http = axios; -var ADocument:JSData.DSResourceDefinition = store.defineResource('document'); +var ADocument: JSData.DSResourceDefinition = store.defineResource('document'); ADocument.inject({ id: 5, author: 'John' }); // bypass the data store -adapter.update(ADocument, 5, { author: 'Johnny' }).then(function (document:any) { +adapter.update(ADocument, 5, { author: 'Johnny' }).then((document: any) => { document; // { id: 5, author: 'Johnny' } // The updated document has NOT been injected into the data store because we bypassed the data store @@ -24,7 +23,7 @@ adapter.update(ADocument, 5, { author: 'Johnny' }).then(function (document:any) }); // Normally you would just go through the data store -ADocument.update(5, { author: 'Johnny' }).then(function (document:any) { +ADocument.update(5, { author: 'Johnny' }).then((document: any) => { document; // { id: 5, author: 'Johnny' } // the updated document has been injected into the data store @@ -35,7 +34,7 @@ ADocument.inject({ id: 5, author: 'John' }); ADocument.inject({ id: 6, author: 'John' }); // bypass the data store -adapter.updateAll(ADocument, { author: 'Johnny' }, { author: 'John' }).then(function (documents) { +adapter.updateAll(ADocument, { author: 'Johnny' }, { author: 'John' }).then(documents => { documents[0]; // { id: 5, author: 'Johnny' } // The updated documents have NOT been injected into the data store because we bypassed the data store @@ -44,7 +43,7 @@ adapter.updateAll(ADocument, { author: 'Johnny' }, { author: 'John' }).then(func }); // Normally you would just go through the data store -ADocument.updateAll({ author: 'Johnny' }, { author: 'John' }).then(function (documents) { +ADocument.updateAll({ author: 'Johnny' }, { author: 'John' }).then(documents => { documents[0]; // { id: 5, author: 'Johnny' } // the updated documents have been injected into the data store @@ -52,44 +51,44 @@ ADocument.updateAll({ author: 'Johnny' }, { author: 'John' }).then(function (doc ADocument.filter({ author: 'Johnny' }); // [{...}, {...}] }); -adapter.PUT('/user/1', { name: 'Johnny' }).then(function (data) { +adapter.PUT('/user/1', { name: 'Johnny' }).then(data => { data.data; // { id: 1, name: 'Johnny', ... } data.headers; // {...} data.status; // 200 - data.config; //{...} + data.config; // {...} }); -adapter.POST('/user/1', { name: 'John' }).then(function (data) { +adapter.POST('/user/1', { name: 'John' }).then(data => { data.data; // { id: 1, name: 'John', ... } data.headers; // {...} data.status; // 200 - data.config; //{...} + data.config; // {...} }); -adapter.HTTP({ url: '/user/1', method: 'put', data: { name: 'Johnny' }}).then(function (data) { +adapter.HTTP({ url: '/user/1', method: 'put', data: { name: 'Johnny' }}).then(data => { data.data; // { id: 1, name: 'Johnny', ... } data.headers; // {...} data.status; // 200 - data.config; //{...} + data.config; // {...} }); -adapter.GET('/user/1').then(function (data) { +adapter.GET('/user/1').then(data => { data.data; // { id: 1, ... } data.headers; // {...} data.status; // 200 - data.config; //{...} + data.config; // {...} }); -var User:JSData.DSResourceDefinition = store.defineResource('user'); +var User: JSData.DSResourceDefinition = store.defineResource('user'); -var params:any = { +var params: any = { age: { '>': 30 } }; // bypass the data store -adapter.findAll(User, params).then(function (users) { +adapter.findAll(User, params).then(users => { // users[0].age; 55 // etc., etc. // the users have NOT been injected into the data store because we bypassed the data store @@ -97,7 +96,7 @@ adapter.findAll(User, params).then(function (users) { }); // normally you would go through the data store -User.findAll(params).then(function (users) { +User.findAll(params).then(users => { // users[0].age; 55 // etc., etc. // the users have been injected into the data store @@ -105,7 +104,7 @@ User.findAll(params).then(function (users) { }); // bypass the data store -adapter.find(ADocument, 5).then(function (document:any) { +adapter.find(ADocument, 5).then((document: any) => { document; // { id: 5, author: 'John Anderson' } // the document has NOT been injected into the data store because we bypassed the data store @@ -113,25 +112,25 @@ adapter.find(ADocument, 5).then(function (document:any) { }); // Normally you would just go through the data store -ADocument.find(5).then(function (document:any) { +ADocument.find(5).then((document: any) => { document; // { id: 5, author: 'John Anderson' } // the document has been injected into the data store ADocument.get(document.id); // { id: 5, author: 'John Anderson' } }); -var params:any = { +var params: any = { author: 'John' }; // bypass the data store -adapter.destroyAll(ADocument, params).then(function () { +adapter.destroyAll(ADocument, params).then(() => { // the documents have NOT been ejected from the data store because we bypassed the data store ADocument.filter(params); // [{...}, {...}, ...] }); // normally you would go through the data store -ADocument.destroyAll(params).then(function () { +ADocument.destroyAll(params).then(() => { // the documents have been ejected from the data store ADocument.filter(params); // [] }); @@ -139,26 +138,26 @@ ADocument.destroyAll(params).then(function () { ADocument.inject({ id: 5, author: 'John' }); // bypass the data store -adapter.destroy(ADocument, 5).then(function () { +adapter.destroy(ADocument, 5).then(() => { // the document is still in the data store because we bypassed the data store - //ADocument.get(document.id); // { id: 5, author: 'John' } + // ADocument.get(document.id); // { id: 5, author: 'John' } }); // Normally you would just go through the data store -ADocument.destroy(5).then(function () { +ADocument.destroy(5).then(() => { // the document has been ejected from the data store - //ADocument.get(document.id); // undefined + // ADocument.get(document.id); // undefined }); -adapter.DEL('/user/1').then(function (data) { +adapter.DEL('/user/1').then(data => { data.data; // 1 data.headers; // {...} data.status; // 204 - data.config; //{...} + data.config; // {...} }); // bypass the data store -adapter.create(ADocument, { author: 'John' }).then(function (document:any) { +adapter.create(ADocument, { author: 'John' }).then((document: any) => { document; // { id: 5, author: 'John' } // The new document has NOT been injected into the data store because we bypassed the data store @@ -166,7 +165,7 @@ adapter.create(ADocument, { author: 'John' }).then(function (document:any) { }); // Normally you would just go through the data store -ADocument.create({ author: 'John' }).then(function (document:any) { +ADocument.create({ author: 'John' }).then((document: any) => { document; // { id: 5, author: 'John' } // the new document has been injected into the data store diff --git a/js-data-http/tslint.json b/js-data-http/tslint.json new file mode 100644 index 0000000000..394d3ce319 --- /dev/null +++ b/js-data-http/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false, + "no-misused-new": false + } +} diff --git a/js-md5/tslint.json b/js-md5/tslint.json index f9e30021f4..377cc837d4 100644 --- a/js-md5/tslint.json +++ b/js-md5/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/js-quantities/js-quantities-tests.ts b/js-quantities/js-quantities-tests.ts index f743d9a8e5..95819381b5 100644 --- a/js-quantities/js-quantities-tests.ts +++ b/js-quantities/js-quantities-tests.ts @@ -123,8 +123,8 @@ qty = Qty('1.1234 m'); qty.format(); // same units, default formatter => '1.234 m' qty.format('cm'); // converted to 'cm', default formatter => '123.45 cm' -var configurableRoundingFormatter = function (maxDecimals: number) { - return function (scalar: number, units: string) { +var configurableRoundingFormatter = (maxDecimals: number) => { + return (scalar: number, units: string) => { var pow = Math.pow(10, maxDecimals); var rounded = Math.round(scalar * pow) / pow; @@ -146,7 +146,7 @@ qty.format(); // same units, current default formatter => '1.12 m' Qty('37 tempC').to('tempF'); // => 98.6 tempF -let scalar: number = 42; +const scalar: number = 42; Qty('100 tempC').add('10 degC'); // 110 tempC Qty('100 tempC').sub('10 degC'); // 90 tempC @@ -180,17 +180,17 @@ try { // From project spec -describe("js-quantities", function () { +describe("js-quantities", () => { "use strict"; - describe("initialization", function () { - it("should create unit only", function () { + describe("initialization", () => { + it("should create unit only", () => { var qty = Qty("m"); expect(qty.numerator).toEqual([""]); expect(qty.scalar).toBe(1); }); - it("should create unitless", function () { + it("should create unitless", () => { var qty = Qty("1"); expect(qty.toFloat()).toBe(1); expect(qty.numerator).toEqual(["<1>"]); @@ -201,21 +201,21 @@ describe("js-quantities", function () { expect(qty.denominator).toEqual(["<1>"]); }); - it("should create unitless from numbers", function () { + it("should create unitless from numbers", () => { var qty = Qty(1.5); expect(qty.toFloat()).toBe(1.5); expect(qty.numerator).toEqual(["<1>"]); expect(qty.denominator).toEqual(["<1>"]); }); - it("should create from numbers with explicit units", function () { + it("should create from numbers with explicit units", () => { var qty = Qty(1.5, "m"); expect(qty.scalar).toBe(1.5); expect(qty.numerator).toEqual([""]); expect(qty.denominator).toEqual(["<1>"]); }); - it("temperatures should have base unit in kelvin", function () { + it("temperatures should have base unit in kelvin", () => { var qty = Qty("1 tempK").toBase(); expect(qty.scalar).toBe(1); expect(qty.units()).toBe("tempK"); @@ -233,7 +233,7 @@ describe("js-quantities", function () { expect(qty.units()).toBe("tempK"); }); - it("temperature degrees should have base unit in kelvin", function () { + it("temperature degrees should have base unit in kelvin", () => { var qty = Qty("1 degK").toBase(); expect(qty.scalar).toBe(1); expect(qty.units()).toBe("degK"); @@ -251,50 +251,50 @@ describe("js-quantities", function () { expect(qty.units()).toBe("degK"); }); - it("should not create temperatures below absolute zero", function () { - expect(function () { Qty("-1 tempK"); }).toThrow("Temperatures must not be less than absolute zero"); - expect(function () { Qty("-273.16 tempC"); }).toThrow("Temperatures must not be less than absolute zero"); - expect(function () { Qty("-459.68 tempF"); }).toThrow("Temperatures must not be less than absolute zero"); - expect(function () { Qty("-1 tempR"); }).toThrow("Temperatures must not be less than absolute zero"); + it("should not create temperatures below absolute zero", () => { + expect(() => { Qty("-1 tempK"); }).toThrow("Temperatures must not be less than absolute zero"); + expect(() => { Qty("-273.16 tempC"); }).toThrow("Temperatures must not be less than absolute zero"); + expect(() => { Qty("-459.68 tempF"); }).toThrow("Temperatures must not be less than absolute zero"); + expect(() => { Qty("-1 tempR"); }).toThrow("Temperatures must not be less than absolute zero"); var qty = Qty("1 tempK"); - expect(function () { qty.mul("-1"); }).toThrow("Temperatures must not be less than absolute zero"); + expect(() => { qty.mul("-1"); }).toThrow("Temperatures must not be less than absolute zero"); qty = Qty("0 tempK"); - expect(function () { qty.sub("1 degK"); }).toThrow("Temperatures must not be less than absolute zero"); + expect(() => { qty.sub("1 degK"); }).toThrow("Temperatures must not be less than absolute zero"); qty = Qty("-273.15 tempC"); - expect(function () { qty.sub("1 degC"); }).toThrow("Temperatures must not be less than absolute zero"); + expect(() => { qty.sub("1 degC"); }).toThrow("Temperatures must not be less than absolute zero"); qty = Qty("-459.67 tempF"); - expect(function () { qty.sub("1 degF"); }).toThrow("Temperatures must not be less than absolute zero"); + expect(() => { qty.sub("1 degF"); }).toThrow("Temperatures must not be less than absolute zero"); qty = Qty("0 tempR"); - expect(function () { qty.sub("1 degR"); }).toThrow("Temperatures must not be less than absolute zero"); + expect(() => { qty.sub("1 degR"); }).toThrow("Temperatures must not be less than absolute zero"); }); - it("should create simple", function () { + it("should create simple", () => { var qty = Qty("1m"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual([""]); expect(qty.denominator).toEqual(["<1>"]); }); - it("should create negative", function () { + it("should create negative", () => { var qty = Qty("-1m"); expect(qty.scalar).toBe(-1); expect(qty.numerator).toEqual([""]); expect(qty.denominator).toEqual(["<1>"]); }); - it("should create compound", function () { + it("should create compound", () => { var qty = Qty("1 N*m"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["", ""]); expect(qty.denominator).toEqual(["<1>"]); }); - it("should create pressure units in term of height of water", function () { + it("should create pressure units in term of height of water", () => { var qty = Qty("1 inH2O"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual([""]); @@ -304,14 +304,14 @@ describe("js-quantities", function () { expect(qty.numerator).toEqual([""]); }); - it("should create with denominator", function () { + it("should create with denominator", () => { var qty = Qty("1 m/s"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual([""]); expect(qty.denominator).toEqual([""]); }); - it("should create with denominator only", function () { + it("should create with denominator only", () => { var qty = Qty("1 /s"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<1>"]); @@ -328,7 +328,7 @@ describe("js-quantities", function () { expect(qty.denominator).toEqual([""]); }); - it("should create with powers", function () { + it("should create with powers", () => { var qty = Qty("1 m^2/s^2"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["", ""]); @@ -343,14 +343,14 @@ describe("js-quantities", function () { expect(qty.denominator).toEqual(["", "", "", "", ""]); }); - it("should create with zero power", function () { + it("should create with zero power", () => { var qty = Qty("1 m^0"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<1>"]); expect(qty.denominator).toEqual(["<1>"]); }); - it("should create with negative powers", function () { + it("should create with negative powers", () => { var qty = Qty("1 m^2 s^-2"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["", ""]); @@ -358,57 +358,57 @@ describe("js-quantities", function () { expect(qty.same(Qty("1 m^2/s^2"))).toBe(true); }); - it("should accept powers without ^ syntax (simple)", function () { + it("should accept powers without ^ syntax (simple)", () => { var qty1 = Qty("1 m2"); var qty2 = Qty("1 m^2"); expect(qty1.eq(qty2)).toBe(true); }); - it("should accept powers without ^ syntax (negative power)", function () { + it("should accept powers without ^ syntax (negative power)", () => { var qty1 = Qty("1 m-2"); var qty2 = Qty("1 m^-2"); expect(qty1.eq(qty2)).toBe(true); }); - it("should accept powers without ^ syntax (compound)", function () { + it("should accept powers without ^ syntax (compound)", () => { var qty1 = Qty("1 m^2 kg^2 J^2/s^2"); var qty2 = Qty("1 m2 kg2 J2/s2"); expect(qty1.eq(qty2)).toBe(true); }); - it("should accept powers without ^ syntax (compound and negative power)", function () { + it("should accept powers without ^ syntax (compound and negative power)", () => { var qty1 = Qty("1 m^2 kg^2 J^2 s^-2"); var qty2 = Qty("1 m2 kg2 J2 s-2"); expect(qty1.eq(qty2)).toBe(true); }); - it("should throw 'Unit not recognized' error when initializing with an invalid unit", function () { - expect(function () { Qty("aa"); }).toThrow("Unit not recognized"); - expect(function () { Qty("m/aa"); }).toThrow("Unit not recognized"); - expect(function () { Qty("m-"); }).toThrow("Unit not recognized"); - expect(function () { Qty("N*m"); }).not.toThrow("Unit not recognized"); + it("should throw 'Unit not recognized' error when initializing with an invalid unit", () => { + expect(() => { Qty("aa"); }).toThrow("Unit not recognized"); + expect(() => { Qty("m/aa"); }).toThrow("Unit not recognized"); + expect(() => { Qty("m-"); }).toThrow("Unit not recognized"); + expect(() => { Qty("N*m"); }).not.toThrow("Unit not recognized"); // mm is millimeter, but mmm is not a valid unit - expect(function () { Qty("mmm"); }).toThrow("Unit not recognized"); + expect(() => { Qty("mmm"); }).toThrow("Unit not recognized"); }); - it("should accept empty string as unitless 1", function () { + it("should accept empty string as unitless 1", () => { expect(Qty("").same(Qty("1"))).toBe(true); expect(Qty(" ").same(Qty("1"))).toBe(true); }); - it("should throw error when passing NaN", function () { + it("should throw error when passing NaN", () => { expect( - function () { Qty(NaN); } + () => { Qty(NaN); } ).toThrow("Only string, number or quantity accepted as single " + "initialization value"); }); - it("should throw 'Unit not recognized' error when initializing with an invalid unit and a 0 exponent", function () { - expect(function () { Qty("3p0"); }).toThrow("Unit not recognized"); - expect(function () { Qty("3p-0"); }).toThrow("Unit not recognized"); + it("should throw 'Unit not recognized' error when initializing with an invalid unit and a 0 exponent", () => { + expect(() => { Qty("3p0"); }).toThrow("Unit not recognized"); + expect(() => { Qty("3p-0"); }).toThrow("Unit not recognized"); }); - it("should set baseScalar", function () { + it("should set baseScalar", () => { var qty = Qty("0.018 MPa"); expect(qty.baseScalar).toBe(18000); @@ -416,18 +416,18 @@ describe("js-quantities", function () { expect(qty.baseScalar).toBe(0.000066); }); - it("should keep init value as is", function () { + it("should keep init value as is", () => { var initValue = " 66 cm3 "; var qty = Qty(initValue); expect(qty.initValue).toEqual(initValue); }); - it("should allow whitespace-wrapped value", function () { - expect(function () { Qty(" 2 MPa "); }).not.toThrow(); + it("should allow whitespace-wrapped value", () => { + expect(() => { Qty(" 2 MPa "); }).not.toThrow(); }); - it("should allow whitespaces between sign and scalar", function () { + it("should allow whitespaces between sign and scalar", () => { var qty = Qty("- 1m"); expect(qty.scalar).toEqual(-1); @@ -435,13 +435,13 @@ describe("js-quantities", function () { }); it("should throw an error when parsing negative quantity " + - "with no scalar", function () { - expect(function () { Qty("-m"); }).toThrow("Unit not recognized"); + "with no scalar", () => { + expect(() => { Qty("-m"); }).toThrow("Unit not recognized"); }); }); - describe("isCompatible", function () { - it("should return true with compatible quantities", function () { + describe("isCompatible", () => { + it("should return true with compatible quantities", () => { var qty1 = Qty("1 m*kg/s"); var qty2 = Qty("1 in*pound/min"); expect(qty1.isCompatible(qty2)).toBe(true); @@ -449,15 +449,15 @@ describe("js-quantities", function () { expect(qty1.isCompatible(qty2)).toBe(false); }); - it("should return true with dimensionless quantities", function () { + it("should return true with dimensionless quantities", () => { var qty1 = Qty("1"); var qty2 = Qty("2"); expect(qty1.isCompatible(qty2)).toBe(true); }); }); - describe("conversion", function () { - it("should convert to base units", function () { + describe("conversion", () => { + it("should convert to base units", () => { var qty = Qty("100 cm"); expect(qty.toBase().scalar).toBe(1); expect(qty.toBase().units()).toBe("m"); @@ -469,7 +469,7 @@ describe("js-quantities", function () { expect(qty.toBase().units()).toBe("m2/s2"); }); - it("should convert to compatible units", function () { + it("should convert to compatible units", () => { var qty = Qty("10 cm"); expect(qty.to("ft").scalar).toBe(Qty.divSafe(0.1, 0.3048)); qty = Qty("2m^3"); @@ -492,17 +492,17 @@ describe("js-quantities", function () { expect(qty.to("cm^3").scalar).toBe(773); }); - describe('percents', function () { - it("should convert from % to unitless", function () { + describe('percents', () => { + it("should convert from % to unitless", () => { expect(Qty("10 %").to("").same(Qty("0.1"))).toBe(true); }); - it("should convert from unitless to %", function () { + it("should convert from unitless to %", () => { expect(Qty("0.1").to("%").same(Qty("10 %"))).toBe(true); }); }); - it("should convert temperatures to compatible units", function () { + it("should convert temperatures to compatible units", () => { var qty = Qty("0 tempK"); expect(qty.to("tempC").scalar).toBe(-273.15); @@ -516,7 +516,7 @@ describe("js-quantities", function () { expect(qty.to("tempF").scalar).toBeCloseTo(32, 10); }); - it("should convert temperature degrees to compatible units", function () { + it("should convert temperature degrees to compatible units", () => { var qty = Qty("0 degK"); expect(qty.to("degC").scalar).toBe(0); @@ -530,7 +530,7 @@ describe("js-quantities", function () { expect(qty.to("degF").scalar).toBe(18); }); - it("should convert temperature degrees to temperatures", function () { + it("should convert temperature degrees to temperatures", () => { // according to ruby-units, deg -> temp conversion adds the degress to 0 kelvin before converting var qty = Qty("100 degC"); expect(qty.to("tempC").scalar).toBeCloseTo(-173.15, 10); @@ -542,7 +542,7 @@ describe("js-quantities", function () { expect(qty.to("tempF").scalar).toBeCloseTo(1, 10); }); - it("should convert temperatures to temperature degrees", function () { + it("should convert temperatures to temperature degrees", () => { // according to ruby-units, temp -> deg conversion always uses the 0 relative degrees var qty = Qty("100 tempC"); expect(qty.to("degC").scalar).toBe(100); @@ -560,7 +560,7 @@ describe("js-quantities", function () { expect(qty.to("degF").scalar).toBe(18); }); - it("should calculate inverses", function () { + it("should calculate inverses", () => { var qty = Qty("1 ohm"); var result = qty.to("siemens"); expect(result.scalar).toBe(1); @@ -583,7 +583,7 @@ describe("js-quantities", function () { // cannot inverse a quantity with a 0 scalar qty = Qty("0 ohm"); - expect(function () { qty.inverse(); }).toThrow("Divide by zero"); + expect(() => { qty.inverse(); }).toThrow("Divide by zero"); qty = Qty("10 ohm").inverse(); result = qty.to("S"); @@ -595,7 +595,7 @@ describe("js-quantities", function () { expect(qty.to("ft").scalar).toBeCloseTo(1, 10); }); - it("should return itself if target units are the same", function () { + it("should return itself if target units are the same", () => { var qty = Qty("123 cm3"); expect(qty.to("cm3")).toBe(qty); @@ -605,7 +605,7 @@ describe("js-quantities", function () { expect(qty.to("ug")).toBe(qty); }); - it("should be cached", function () { + it("should be cached", () => { var qty = Qty("100 m"), converted = qty.to("ft"); @@ -613,14 +613,14 @@ describe("js-quantities", function () { }); }); - describe("comparison", function () { - it("should return true when comparing equal quantities", function () { + describe("comparison", () => { + it("should return true when comparing equal quantities", () => { var qty1 = Qty("1cm"); var qty2 = Qty("10mm"); expect(qty1.eq(qty2)).toBe(true); }); - it("should compare compatible quantities", function () { + it("should compare compatible quantities", () => { var qty1 = Qty("1cm"); var qty2 = Qty("1mm"); var qty3 = Qty("10mm"); @@ -628,7 +628,7 @@ describe("js-quantities", function () { expect(qty1.compareTo(qty2)).toBe(1); expect(qty2.compareTo(qty1)).toBe(-1); expect(qty1.compareTo(qty3)).toBe(0); - expect(function () { qty1.compareTo(qty4); }).toThrow("Incompatible units"); + expect(() => { qty1.compareTo(qty4); }).toThrow("Incompatible units"); expect(qty1.lt(qty2)).toBe(false); expect(qty1.lt(qty3)).toBe(false); @@ -638,7 +638,7 @@ describe("js-quantities", function () { expect(qty2.gt(qty1)).toBe(false); }); - it("should compare identical quantities", function () { + it("should compare identical quantities", () => { var qty1 = Qty("1cm"); var qty2 = Qty("1cm"); var qty3 = Qty("10mm"); @@ -646,7 +646,7 @@ describe("js-quantities", function () { expect(qty1.same(qty3)).toBe(false); }); - it("should accept strings as parameter", function () { + it("should accept strings as parameter", () => { var qty = Qty("1 cm"); expect(qty.lt("0.5 cm")).toBe(false); expect(qty.lte("1 cm")).toBe(true); @@ -656,9 +656,9 @@ describe("js-quantities", function () { }); - describe("non-ASCII character", function () { - describe("µ", function () { - it("should be supported as prefix", function () { + describe("non-ASCII character", () => { + describe("µ", () => { + it("should be supported as prefix", () => { // µ as greek letter expect(Qty("1 \u03BCm").eq(Qty("1 um"))).toBe(true); // µ as micro sign @@ -666,8 +666,8 @@ describe("js-quantities", function () { }); }); - describe("Ω", function () { - it("should be accepted as unit for ohm", function () { + describe("Ω", () => { + it("should be accepted as unit for ohm", () => { // Ω as greek letter expect(Qty("1 \u03A9").eq(Qty("1 ohm"))).toBe(true); // Ω as ohm sign @@ -676,9 +676,9 @@ describe("js-quantities", function () { }); }); - describe("math", function () { + describe("math", () => { - it("should add quantities", function () { + it("should add quantities", () => { var qty1 = Qty("2.5m"); var qty2 = Qty("3m"); expect(qty1.add(qty2).scalar).toBe(5.5); @@ -700,26 +700,26 @@ describe("js-quantities", function () { expect(result.units()).toBe("cm"); }); - it("should fail to add unlike quantities", function () { + it("should fail to add unlike quantities", () => { var qty1 = Qty("3m"); var qty2 = Qty("2s"); - expect(function () { qty1.add(qty2); }).toThrow("Incompatible units"); - expect(function () { qty2.add(qty1); }).toThrow("Incompatible units"); + expect(() => { qty1.add(qty2); }).toThrow("Incompatible units"); + expect(() => { qty2.add(qty1); }).toThrow("Incompatible units"); }); - it("should fail to add inverse quantities", function () { + it("should fail to add inverse quantities", () => { var qty1 = Qty("10S"); var qty2 = qty1.inverse(); - expect(function () { qty1.add(qty2); }).toThrow("Incompatible units"); - expect(function () { qty2.add(qty1); }).toThrow("Incompatible units"); + expect(() => { qty1.add(qty2); }).toThrow("Incompatible units"); + expect(() => { qty2.add(qty1); }).toThrow("Incompatible units"); qty1 = Qty("10S"); qty2 = Qty("0.1ohm"); - expect(function () { qty1.add(qty2); }).toThrow("Incompatible units"); - expect(function () { qty2.add(qty1); }).toThrow("Incompatible units"); + expect(() => { qty1.add(qty2); }).toThrow("Incompatible units"); + expect(() => { qty2.add(qty1); }).toThrow("Incompatible units"); }); - it("should subtract quantities", function () { + it("should subtract quantities", () => { var qty1 = Qty("2.5m"); var qty2 = Qty("3m"); expect(qty1.sub(qty2).scalar).toBe(-0.5); @@ -737,26 +737,26 @@ describe("js-quantities", function () { expect(result.units()).toBe("cm"); }); - it("should fail to subtract unlike quantities", function () { + it("should fail to subtract unlike quantities", () => { var qty1 = Qty("3m"); var qty2 = Qty("2s"); - expect(function () { qty1.sub(qty2); }).toThrow("Incompatible units"); - expect(function () { qty2.sub(qty1); }).toThrow("Incompatible units"); + expect(() => { qty1.sub(qty2); }).toThrow("Incompatible units"); + expect(() => { qty2.sub(qty1); }).toThrow("Incompatible units"); }); - it("should fail to subtract inverse quantities", function () { + it("should fail to subtract inverse quantities", () => { var qty1 = Qty("10S"); var qty2 = qty1.inverse(); - expect(function () { qty1.sub(qty2); }).toThrow("Incompatible units"); - expect(function () { qty2.sub(qty1); }).toThrow("Incompatible units"); + expect(() => { qty1.sub(qty2); }).toThrow("Incompatible units"); + expect(() => { qty2.sub(qty1); }).toThrow("Incompatible units"); qty1 = Qty("10S"); qty2 = Qty("0.1ohm"); - expect(function () { qty1.sub(qty2); }).toThrow("Incompatible units"); - expect(function () { qty2.sub(qty1); }).toThrow("Incompatible units"); + expect(() => { qty1.sub(qty2); }).toThrow("Incompatible units"); + expect(() => { qty2.sub(qty1); }).toThrow("Incompatible units"); }); - it("should multiply quantities", function () { + it("should multiply quantities", () => { var qty1 = Qty("2.5m"); var qty2 = Qty("3m"); var result = qty1.mul(qty2); @@ -791,7 +791,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("m2"); }); - it("should multiply unlike quantities", function () { + it("should multiply unlike quantities", () => { var qty1 = Qty("2.5 m"); var qty2 = Qty("3 N"); @@ -806,7 +806,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("kg"); }); - it("should multiply inverse quantities", function () { + it("should multiply inverse quantities", () => { var qty1 = Qty("10S"); var qty2 = Qty(".5S").inverse(); // 2/S var qty3 = qty1.inverse(); // .1/S @@ -832,13 +832,13 @@ describe("js-quantities", function () { expect(result.units()).toBe(""); }); - it("should divide quantities", function () { + it("should divide quantities", () => { var qty1 = Qty("2.5m"); var qty2 = Qty("3m"); var qty3 = Qty("0m"); - expect(function () { qty1.div(qty3); }).toThrow("Divide by zero"); - expect(function () { qty1.div(0); }).toThrow("Divide by zero"); + expect(() => { qty1.div(qty3); }).toThrow("Divide by zero"); + expect(() => { qty1.div(0); }).toThrow("Divide by zero"); expect(qty3.div(qty1).scalar).toBe(0); var result = qty1.div(qty2); @@ -860,7 +860,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("m"); }); - it("should divide unlike quantities", function () { + it("should divide unlike quantities", () => { var qty1 = Qty("7.5kg"); var qty2 = Qty("2.5m^2"); @@ -869,7 +869,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("kg/m2"); }); - it("should divide inverse quantities", function () { + it("should divide inverse quantities", () => { var qty1 = Qty("10 S"); var qty2 = Qty(".5 S").inverse(); // 2/S var qty3 = qty1.inverse(); // .1/S @@ -893,9 +893,9 @@ describe("js-quantities", function () { }); - describe("math with temperatures", function () { + describe("math with temperatures", () => { - it("should add temperature degrees", function () { + it("should add temperature degrees", () => { var qty = Qty("2degC"); expect(qty.add("3degF").scalar).toBeCloseTo(11 / 3, 10); expect(qty.add("-1degC").scalar).toBe(1); @@ -916,13 +916,13 @@ describe("js-quantities", function () { expect(result.units()).toBe("degC"); }); - it("should not add two temperatures", function () { + it("should not add two temperatures", () => { var qty = Qty("2tempC"); - expect(function () { qty.add("1 tempF"); }).toThrow("Cannot add two temperatures"); - expect(function () { qty.add("1 tempC"); }).toThrow("Cannot add two temperatures"); + expect(() => { qty.add("1 tempF"); }).toThrow("Cannot add two temperatures"); + expect(() => { qty.add("1 tempC"); }).toThrow("Cannot add two temperatures"); }); - it("should add temperatures to degrees", function () { + it("should add temperatures to degrees", () => { var qty = Qty("2degC"); var result = qty.add("3tempF"); expect(result.scalar).toBe(33 / 5); @@ -938,7 +938,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("tempC"); }); - it("should subtract degrees from degrees", function () { + it("should subtract degrees from degrees", () => { var qty = Qty("2degC"); expect(qty.sub("1.5degK").scalar).toBe(0.5); expect(qty.sub("-2degC").scalar).toBe(4); @@ -950,7 +950,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("degC"); }); - it("should subtract degrees from temperatures", function () { + it("should subtract degrees from temperatures", () => { var qty = Qty("2tempC"); expect(qty.sub("1.5degK").scalar).toBe(0.5); expect(qty.sub("-2degC").scalar).toBe(4); @@ -962,7 +962,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("tempC"); }); - it("should subtract temperatures from temperatures", function () { + it("should subtract temperatures from temperatures", () => { var qty = Qty("2tempC"); var result = qty.sub("1.5tempK"); @@ -978,13 +978,13 @@ describe("js-quantities", function () { expect(result.units()).toBe("degC"); }); - it("should not subtract temperatures from degrees", function () { + it("should not subtract temperatures from degrees", () => { var qty = Qty("2degC"); - expect(function () { qty.sub("1 tempF"); }).toThrow("Cannot subtract a temperature from a differential degree unit"); - expect(function () { qty.sub("1 tempC"); }).toThrow("Cannot subtract a temperature from a differential degree unit"); + expect(() => { qty.sub("1 tempF"); }).toThrow("Cannot subtract a temperature from a differential degree unit"); + expect(() => { qty.sub("1 tempC"); }).toThrow("Cannot subtract a temperature from a differential degree unit"); }); - it("should multiply temperature degrees", function () { + it("should multiply temperature degrees", () => { var qty = Qty("2degF"); var result = qty.mul(3); expect(result.scalar).toBe(6); @@ -1006,11 +1006,11 @@ describe("js-quantities", function () { expect(result.units()).toBe("degC*degF"); }); - it("should not multiply temperatures except by scalar", function () { + it("should not multiply temperatures except by scalar", () => { var qty = Qty("2tempF"); - expect(function () { qty.mul("1 tempC"); }).toThrow("Cannot multiply by temperatures"); - expect(function () { qty.mul("1 degC"); }).toThrow("Cannot multiply by temperatures"); - expect(function () { Qty("1 tempC*s"); }).toThrow("Cannot multiply by temperatures"); + expect(() => { qty.mul("1 tempC"); }).toThrow("Cannot multiply by temperatures"); + expect(() => { qty.mul("1 degC"); }).toThrow("Cannot multiply by temperatures"); + expect(() => { Qty("1 tempC*s"); }).toThrow("Cannot multiply by temperatures"); var result = qty.mul(2); expect(result.scalar).toBe(4); @@ -1021,7 +1021,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("tempF"); }); - it("should multiply temperature degrees with unlike quantities", function () { + it("should multiply temperature degrees with unlike quantities", () => { var qty1 = Qty("2.5 degF"); var qty2 = Qty("3 m"); @@ -1036,7 +1036,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("kg"); }); - it("should divide temperature degrees with unlike quantities", function () { + it("should divide temperature degrees with unlike quantities", () => { var qty1 = Qty("7.5degF"); var qty2 = Qty("2.5m^2"); @@ -1045,11 +1045,11 @@ describe("js-quantities", function () { expect(result.units()).toBe("degF/m2"); }); - it("should divide temperature degree quantities", function () { + it("should divide temperature degree quantities", () => { var qty = Qty("2.5 degF"); - expect(function () { qty.div("0 degF"); }).toThrow("Divide by zero"); - expect(function () { qty.div(0); }).toThrow("Divide by zero"); + expect(() => { qty.div("0 degF"); }).toThrow("Divide by zero"); + expect(() => { qty.div(0); }).toThrow("Divide by zero"); expect(Qty("0 degF").div(qty).scalar).toBe(0); expect(Qty("0 degF").div(qty).units()).toBe(""); @@ -1069,15 +1069,15 @@ describe("js-quantities", function () { expect(result.units()).toBe("degF/degC"); }); - it("should not divide with temperatures except by scalar", function () { - expect(function () { Qty("tempF").div("1 tempC"); }).toThrow("Cannot divide with temperatures"); - expect(function () { Qty("tempF").div("1 degC"); }).toThrow("Cannot divide with temperatures"); - expect(function () { Qty("2").div("tempF"); }).toThrow("Cannot divide with temperatures"); - expect(function () { Qty("2 tempF/s"); }).toThrow("Cannot divide with temperatures"); - expect(function () { Qty("2 s/tempF"); }).toThrow("Cannot divide with temperatures"); + it("should not divide with temperatures except by scalar", () => { + expect(() => { Qty("tempF").div("1 tempC"); }).toThrow("Cannot divide with temperatures"); + expect(() => { Qty("tempF").div("1 degC"); }).toThrow("Cannot divide with temperatures"); + expect(() => { Qty("2").div("tempF"); }).toThrow("Cannot divide with temperatures"); + expect(() => { Qty("2 tempF/s"); }).toThrow("Cannot divide with temperatures"); + expect(() => { Qty("2 s/tempF"); }).toThrow("Cannot divide with temperatures"); // inverse is division: 1/x - expect(function () { Qty("tempF").inverse(); }).toThrow("Cannot divide with temperatures"); + expect(() => { Qty("tempF").inverse(); }).toThrow("Cannot divide with temperatures"); var result = Qty("4 tempF").div(2); expect(result.scalar).toBe(2); @@ -1086,8 +1086,8 @@ describe("js-quantities", function () { }); - describe("errors", function () { - it("should be instance of Qty.Error", function () { + describe("errors", () => { + it("should be instance of Qty.Error", () => { try { Qty("aa"); } catch (e) { @@ -1096,16 +1096,16 @@ describe("js-quantities", function () { }); }); - describe("utility methods", function () { + describe("utility methods", () => { - it("should accept string as parameter for compatibility tests", function () { + it("should accept string as parameter for compatibility tests", () => { var qty = Qty("1 mm"); expect(qty.isCompatible("2 mm")).toBe(true); expect(qty.isCompatible("2 mm^3")).toBe(false); }); - it("should return kind", function () { + it("should return kind", () => { var qty = Qty("1 mm"); expect(qty.kind()).toBe("length"); @@ -1113,7 +1113,7 @@ describe("js-quantities", function () { expect(qty.kind()).toBe("force"); }); - it("should know if a quantity is in base units", function () { + it("should know if a quantity is in base units", () => { var qty = Qty("100 cm"); expect(qty.isBase()).toBe(false); @@ -1121,7 +1121,7 @@ describe("js-quantities", function () { expect(qty.isBase()).toBe(true); }); - it("should return unit part of quantities", function () { + it("should return unit part of quantities", () => { var qty = Qty("1"); expect(qty.units()).toBe(""); qty = Qty("1 /s"); @@ -1140,17 +1140,17 @@ describe("js-quantities", function () { }); - describe("toString", function () { - it("should generate readable human output", function () { + describe("toString", () => { + it("should generate readable human output", () => { var qty = Qty("2m"); expect(qty.toString()).toBe("2 m"); expect(qty.toString("cm")).toBe("200 cm"); expect(qty.toString("km")).toBe("0.002 km"); - expect(function () { qty.toString("A"); }).toThrow("Incompatible units"); + expect(() => { qty.toString("A"); }).toThrow("Incompatible units"); qty = Qty("24.5m/s"); expect(qty.toString()).toBe("24.5 m/s"); - expect(function () { qty.toString("m"); }).toThrow("Incompatible units"); + expect(() => { qty.toString("m"); }).toThrow("Incompatible units"); expect(qty.toString("km/h")).toBe("88.2 km/h"); qty = Qty("254kg/m^2"); @@ -1160,7 +1160,7 @@ describe("js-quantities", function () { expect(qty.toString()).toBe("2"); }); - it("should round readable human output when max decimals is specified", function () { + it("should round readable human output when max decimals is specified", () => { var qty = (Qty("2m")).div(3); expect(qty.toString("cm", 2)).toBe("66.67 cm"); @@ -1171,14 +1171,14 @@ describe("js-quantities", function () { expect(qty.toString("cm", 0)).toBe("282 cm"); }); - it("should round to max decimals", function () { + it("should round to max decimals", () => { var qty = (Qty("2.987654321 m")); expect(qty.toString(3)).toBe("2.988 m"); expect(qty.toString(0)).toBe("3 m"); }); - it("should round according to precision passed as quantity", function () { + it("should round according to precision passed as quantity", () => { var qty = Qty("5.17 ft"); expect(qty.toString(Qty("ft"))).toBe("5 ft"); @@ -1190,31 +1190,31 @@ describe("js-quantities", function () { expect(qty.toString(Qty("0.0001 ft"))).toBe("5.17 ft"); }); - it("should return same output with successive calls", function () { + it("should return same output with successive calls", () => { var qty = Qty("123 cm3"); expect(qty.toString("cm3", 0)).toBe("123 cm3"); expect(qty.toString("cm3", 0)).toBe("123 cm3"); }); - it("should return identical output when called with no parameters or same units", function () { + it("should return identical output when called with no parameters or same units", () => { var qty = Qty("123 cm3"); expect(qty.toString()).toBe(qty.toString("cm3")); }); }); - describe("format", function () { - describe("provided default formatter", function () { - it("should be applied to output", function () { + describe("format", () => { + describe("provided default formatter", () => { + it("should be applied to output", () => { var qty = (Qty("2.987654321 m")); expect(qty.format()).toBe("2.987654321 m"); }); }); - describe("custom formatter", function () { - var roundingFormatter = function (maxDecimals: number) { - return function (scalar: number, units: string) { + describe("custom formatter", () => { + var roundingFormatter = (maxDecimals: number) => { + return (scalar: number, units: string) => { var pow = Math.pow(10, maxDecimals); var rounded = Math.round(scalar * pow) / pow; @@ -1222,14 +1222,14 @@ describe("js-quantities", function () { }; }; - it("should be applied to output", function () { + it("should be applied to output", () => { var qty = (Qty("2.987654321 m")); expect(qty.format(roundingFormatter(3))).toBe("2.988 m"); expect(qty.format(roundingFormatter(0))).toBe("3 m"); }); - it("should be applied after conversion to target units", function () { + it("should be applied after conversion to target units", () => { var qty = (Qty("2m")).div(3); expect(qty.format("cm", roundingFormatter(2))).toBe("66.67 cm"); @@ -1241,20 +1241,20 @@ describe("js-quantities", function () { expect(qty.format("cm", intRoundingFormatter)).toBe("282 cm"); }); - describe("globally set as default formatter", function () { + describe("globally set as default formatter", () => { var previousFormatter: Qty.Formatter; - beforeEach(function () { + beforeEach(() => { previousFormatter = Qty.formatter; Qty.formatter = roundingFormatter(3); }); - afterEach(function () { + afterEach(() => { // Restore previous formatter Qty.formatter = previousFormatter; }); - it("should be applied when no formatter is passed", function () { + it("should be applied when no formatter is passed", () => { var qty = (Qty("2.987654321 m")); expect(qty.format()).toBe("2.988 m"); @@ -1263,8 +1263,8 @@ describe("js-quantities", function () { }); }); - describe("precision rounding", function () { - it("should round according to precision passed as quantity with same units", function () { + describe("precision rounding", () => { + it("should round according to precision passed as quantity with same units", () => { var qty = Qty("5.17 ft"); expect(qty.toPrec(Qty("ft")).toString()).toBe("5 ft"); @@ -1278,7 +1278,7 @@ describe("js-quantities", function () { expect(qty.toPrec(Qty("0.25 ft")).toString()).toBe("5.25 ft"); }); - it("should allow string as precision parameter", function () { + it("should allow string as precision parameter", () => { var qty = Qty("5.17 ft"); expect(qty.toPrec("ft").toString()).toBe("5 ft"); @@ -1286,7 +1286,7 @@ describe("js-quantities", function () { expect(qty.toPrec("0.05 ft").toString()).toBe("5.15 ft"); }); - it("should round according to precision passed as quantity with different prefixes", function () { + it("should round according to precision passed as quantity with different prefixes", () => { var qty = Qty("6.3782 m"); expect(qty.toPrec(Qty("dm")).toString()).toBe("6.4 m"); @@ -1296,7 +1296,7 @@ describe("js-quantities", function () { expect(qty.toPrec(Qty("5 cm")).toString()).toBe("6.4 m"); }); - it("should round according to precision passed as quantity with different compatible units", function () { + it("should round according to precision passed as quantity with different compatible units", () => { var qty = Qty("1.146 MPa"); expect(qty.toPrec(Qty("0.1 bar")).toString()).toBe("1.15 MPa"); expect(qty.toPrec(Qty("0.01 MPa")).toString()).toBe("1.15 MPa"); @@ -1312,48 +1312,48 @@ describe("js-quantities", function () { }); }); - describe("mulSafe", function () { - it("should multiply while trying to avoid numerical errors", function () { + describe("mulSafe", () => { + it("should multiply while trying to avoid numerical errors", () => { expect(Qty.mulSafe(0.1, 0.1)).toBe(0.01); expect(Qty.mulSafe(1e-11, 123.456789)).toBe(1.23456789e-9); expect(Qty.mulSafe(6e-12, 100000)).toBe(6e-7); }); }); - describe("divSafe", function () { - it("should divide while trying to avoid numerical errors", function () { + describe("divSafe", () => { + it("should divide while trying to avoid numerical errors", () => { expect(Qty.divSafe(0.000773, 0.000001)).toBe(773); // TODO uncomment and fix - //expect(Qty.divSafe(24.5, 0.2777777777777778)).toBe(88.2); + // expect(Qty.divSafe(24.5, 0.2777777777777778)).toBe(88.2); }); }); - describe("Qty.parse", function () { - it("should not throw if parsed argument is a string", function () { - expect(function () { Qty.parse("foo"); }).not.toThrow("Argument should be a string"); + describe("Qty.parse", () => { + it("should not throw if parsed argument is a string", () => { + expect(() => { Qty.parse("foo"); }).not.toThrow("Argument should be a string"); }); - it("should return parsed quantity when passing a valid quantity", function () { + it("should return parsed quantity when passing a valid quantity", () => { expect((Qty.parse("2.5 m") instanceof Qty)).toBe(true); }); - it("should return null when passing an invalid quantity", function () { + it("should return null when passing an invalid quantity", () => { expect(Qty.parse("aa")).toBeNull(); }); }); - describe("Qty.swiftConverter", function () { - it("should return a function", function () { + describe("Qty.swiftConverter", () => { + it("should return a function", () => { expect(typeof Qty.swiftConverter("m/h", "ft/s")).toBe("function"); }); - it("should throw when passing incompatible units", function () { - expect(function () { Qty.swiftConverter("m", "s"); }).toThrow("Incompatible units"); + it("should throw when passing incompatible units", () => { + expect(() => { Qty.swiftConverter("m", "s"); }).toThrow("Incompatible units"); }); - describe("converter", function () { - describe("single value", function () { - it("should convert value", function () { + describe("converter", () => { + describe("single value", () => { + it("should convert value", () => { // TODO Same test but with m/h -> ft/s triggers rounding issue // (For the sake of speed, converter does not check and fix rounding issues) var converter = Qty.swiftConverter("m/h", "m/s"); @@ -1361,27 +1361,27 @@ describe("js-quantities", function () { expect(converter(2500)).toEqual(Qty("2500 m/h").to("m/s").scalar); }); - it("should returned value unchanged when units are identical", function () { + it("should returned value unchanged when units are identical", () => { var converter = Qty.swiftConverter("m/h", "m/h"); expect(converter(2500)).toEqual(2500); }); - it("should convert temperatures", function () { + it("should convert temperatures", () => { var converter = Qty.swiftConverter("tempF", "tempC"); expect(converter(32)).toEqual(0); }); - it("should convert degrees", function () { + it("should convert degrees", () => { var converter = Qty.swiftConverter("degC", "degF"); expect(converter(10)).toEqual(18); }); }); - describe("array of values", function () { - it("should be converted", function () { + describe("array of values", () => { + it("should be converted", () => { var converter = Qty.swiftConverter("MPa", "bar"), values = [250, 10, 15], expected = [2500, 100, 150]; @@ -1392,106 +1392,106 @@ describe("js-quantities", function () { }); }); - describe("Qty.getKinds", function () { - it("should return an array of kind names", function () { + describe("Qty.getKinds", () => { + it("should return an array of kind names", () => { expect(Qty.getKinds()).toContain("resistance"); }); - it("should not contain duplicate kind names", function () { + it("should not contain duplicate kind names", () => { var kinds = Qty.getKinds(); var map: { [key: string]: number } = {}; - kinds.forEach(function (kind) { + kinds.forEach(kind => { map[kind] = 1; }); expect(kinds.length).toEqual(Object.keys(map).length); }); }); - describe("Qty.getUnits", function () { - it("should return an array of units of kind", function () { + describe("Qty.getUnits", () => { + it("should return an array of units of kind", () => { expect(Qty.getUnits("currency")).toContain("dollar"); }); - it("should return an array of all units without arg", function () { + it("should return an array of all units without arg", () => { expect(Qty.getUnits()).toContain("sievert"); }); - it("should throw unknown kind", function () { - expect(function () { Qty.getUnits('bogusKind'); }).toThrow("Kind not recognized"); + it("should throw unknown kind", () => { + expect(() => { Qty.getUnits('bogusKind'); }).toThrow("Kind not recognized"); }); }); - describe("Qty.getAliases", function () { - it("should return array of alternative names for unit", function () { + describe("Qty.getAliases", () => { + it("should return array of alternative names for unit", () => { expect(Qty.getAliases("m")).toContain("meter"); expect(Qty.getAliases("meter")).toContain("metre"); expect(Qty.getAliases("N")).toContain("newton"); }); }); - describe("information", function () { - describe("bits and bytes", function () { - it("should have 'information' as kind", function () { + describe("information", () => { + describe("bits and bytes", () => { + it("should have 'information' as kind", () => { expect(Qty("3 b").kind()).toBe("information"); expect(Qty("5 B").kind()).toBe("information"); }); - it("could be pluralized", function () { + it("could be pluralized", () => { expect(Qty("3 bits").eq(Qty("3 b"))).toBe(true); expect(Qty("5 bytes").eq(Qty("5 B"))).toBe(true); }); }); - describe("rate", function () { - it("should accept bps and Bps aliases", function () { + describe("rate", () => { + it("should accept bps and Bps aliases", () => { expect(Qty("3 bps").eq(Qty("3 b/s"))).toBe(true); expect(Qty("5 Bps").eq(Qty("5 B/s"))).toBe(true); }); - it("should be parsed when prefixed", function () { + it("should be parsed when prefixed", () => { expect(Qty("3 kbps").eq(Qty("3 kb/s"))).toBe(true); expect(Qty("5 MBps").eq(Qty("5 MB/s"))).toBe(true); }); - it("should have 'information_rate' as kind", function () { + it("should have 'information_rate' as kind", () => { expect(Qty("3 bps").kind()).toBe("information_rate"); expect(Qty("5 Bps").kind()).toBe("information_rate"); }); }); }); - describe("non regression tests", function () { - describe("Wh (#38)", function () { - it("should be parsed", function () { + describe("non regression tests", () => { + describe("Wh (#38)", () => { + it("should be parsed", () => { expect(Qty("Wh").eq(Qty("3600 J"))).toBe(true); }); - it("should be parsed when prefixed", function () { + it("should be parsed when prefixed", () => { expect(Qty("kWh").eq(Qty("1000 Wh"))).toBe(true); }); }); - describe("Ah (#25)", function () { - it("should be parsed", function () { + describe("Ah (#25)", () => { + it("should be parsed", () => { expect(Qty("Ah").eq(Qty("3600 C"))).toBe(true); }); - it("should be parsed when prefixed", function () { + it("should be parsed when prefixed", () => { expect(Qty("mAh").eq(Qty("3.6 C"))).toBe(true); }); }); - describe("Farad (#67)", function () { - it('should be equal to its definition', function () { + describe("Farad (#67)", () => { + it('should be equal to its definition', () => { expect(Qty("1 F").eq(Qty("1 C").div(Qty("1 V")))).toBe(true); }); - it('should not be defined as base unit', function () { + it('should not be defined as base unit', () => { var qty = Qty("F"); expect(qty.isBase()).toBe(false); expect(qty.toBase().units()).toEqual("s4*A2/m2*kg"); }); - it('should be parsed when prefixed', function () { + it('should be parsed when prefixed', () => { var qty = Qty("100 nF"); expect(qty.eq(Qty("100 F").div(1e9))).toBe(true); diff --git a/js-quantities/tslint.json b/js-quantities/tslint.json index f9e30021f4..377cc837d4 100644 --- a/js-quantities/tslint.json +++ b/js-quantities/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/jsdom/index.d.ts b/jsdom/index.d.ts index a7d8e1d58b..0f272a7c35 100644 --- a/jsdom/index.d.ts +++ b/jsdom/index.d.ts @@ -89,7 +89,7 @@ export interface DocumentWithParentWindow extends Document { * equivalent to what a browser will give if you open up an empty .html file. * @param options see the explanation of the config object above. */ -export declare function jsdom(markup: string, config?: Config): DocumentWithParentWindow; +export declare function jsdom(markup?: string, config?: Config): DocumentWithParentWindow; /** * Before creating any documents, you can modify the defaults for all future documents: diff --git a/jsnlog/jsnlog-tests.ts b/jsnlog/jsnlog-tests.ts index 64078fbd58..c988234394 100644 --- a/jsnlog/jsnlog-tests.ts +++ b/jsnlog/jsnlog-tests.ts @@ -70,7 +70,7 @@ var logger1: JL.JSNLogLogger = JL('mylogger'); var exception = {}; logger1.trace('log message').debug({ x: 1, y: 2}); -logger1.info(function() { return 5; }); +logger1.info(() => 5); logger1.warn('log message'); logger1.error('log message'); logger1.fatal('log message'); diff --git a/jsnlog/tslint.json b/jsnlog/tslint.json index 9bc375c06b..1b7fef4ac6 100644 --- a/jsnlog/tslint.json +++ b/jsnlog/tslint.json @@ -1,6 +1,7 @@ { "extends": "../tslint.json", "rules": { + "max-line-length": false, "no-empty-interface": false } -} \ No newline at end of file +} diff --git a/json-stable-stringify/index.d.ts b/json-stable-stringify/index.d.ts index 79402210f3..3339d8f28e 100644 --- a/json-stable-stringify/index.d.ts +++ b/json-stable-stringify/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for json-stable-stringify 1.0.0 +// Type definitions for json-stable-stringify 1.0 // Project: https://github.com/substack/json-stable-stringify // Definitions by: Matt Frantz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -14,13 +14,9 @@ declare namespace stringify { value: any; } - interface Comparator { - (a: Element, b: Element): number; - } + type Comparator = (a: Element, b: Element) => number; - interface Replacer { - (key: string, value: any): any; - } + type Replacer = (key: string, value: any) => any; interface Options { cmp?: Comparator; diff --git a/json-stable-stringify/json-stable-stringify-tests.ts b/json-stable-stringify/json-stable-stringify-tests.ts index dfd2ced587..761d01d06a 100644 --- a/json-stable-stringify/json-stable-stringify-tests.ts +++ b/json-stable-stringify/json-stable-stringify-tests.ts @@ -1,6 +1,6 @@ import stringify = require('json-stable-stringify'); -var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; +var obj = { c: 8, b: [{z: 6, y: 5, x: 4}, 7], a: 3 }; { console.log(stringify(obj)); diff --git a/json-stable-stringify/tsconfig.json b/json-stable-stringify/tsconfig.json index 65e9568adf..9ce550b0e8 100644 --- a/json-stable-stringify/tsconfig.json +++ b/json-stable-stringify/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/json-stable-stringify/tslint.json b/json-stable-stringify/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/json-stable-stringify/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/jsonrpc-serializer/tsconfig.json b/jsonrpc-serializer/tsconfig.json index 60a4d45f42..f17f1b210b 100644 --- a/jsonrpc-serializer/tsconfig.json +++ b/jsonrpc-serializer/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "jsonrpc-serializer-tests.ts" ] -} +} \ No newline at end of file diff --git a/jui-core/jui-core-tests.ts b/jui-core/jui-core-tests.ts index 6cf8a82c98..c0677926e6 100644 --- a/jui-core/jui-core-tests.ts +++ b/jui-core/jui-core-tests.ts @@ -1,15 +1,13 @@ -/// - import {jui, UtilColor, UtilBase} from "./index"; -jui.ready(["util.color"], function(color: UtilColor) { +jui.ready(["util.color"], (color: UtilColor) => { console.log(color.rgb("#ff0000")); }); -let _ : UtilBase = jui.include("util.base"); +const _: UtilBase = jui.include("util.base"); -let str: string = "10"; +const str: string = "10"; console.log(_.typeCheck("string", str)); -let i: number = 10; +const i: number = 10; console.log(_.typeCheck("string", i)); diff --git a/jui-grid/jui-grid-tests.ts b/jui-grid/jui-grid-tests.ts index 1d29dd059b..1fb65c4b97 100644 --- a/jui-grid/jui-grid-tests.ts +++ b/jui-grid/jui-grid-tests.ts @@ -4,8 +4,8 @@ import {jui} from 'jui-core'; import {GridTable, GridXTable, GridRow} from "./index"; -jui.ready([ "grid.table" ], function(table: GridTable) { - let table_1: GridTable = table("#table_1", { +jui.ready([ "grid.table" ], (table: GridTable) => { + const table_1: GridTable = table("#table_1", { data: [ { name: "Hong", age: "20", location: "Ilsan" }, { name: "Jung", age: "30", location: "Seoul" }, @@ -21,13 +21,13 @@ jui.ready([ "grid.table" ], function(table: GridTable) { table_1.scroll(100); }); -jui.ready([ "grid.table" ], function(table: GridTable) { - let table_3:GridTable = table("#table_3", { +jui.ready([ "grid.table" ], (table: GridTable) => { + const table_3: GridTable = table("#table_3", { event: { - expand: function(row: any, e: any): void { + expand(row: any, e: any): void { $(row.list[0]).html(""); }, - expandend: function(row: any, e: any): void { + expandend(row: any, e: any): void { $(row.list[0]).html(""); } }, @@ -40,21 +40,21 @@ jui.ready([ "grid.table" ], function(table: GridTable) { { name: "Park", age: "10", location: "Dangjin" } ]); - let table_3_submit: Function = function(index: number) { + const table_3_submit: Function = (index: number) => { var name = $(table_3.root).find(".name").val(), age = $(table_3.root).find(".age").val(), location = $(table_3.root).find(".location").val(); //noinspection TypeScriptValidateTypes - table_3.update(index, { name: name, age: age, location: location }); + table_3.update(index, { name, age, location }); table_3.hideExpand(); - } + }; }); -jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { +jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { var page = 1; - let xtable_2: GridXTable = xtable("#xtable_2", { + const xtable_2: GridXTable = xtable("#xtable_2", { fields: [ "name", "age", "location" ], resize: true, sort: true, @@ -62,28 +62,28 @@ jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { bufferCount: 20 }); - let xtable_2_submit: Function = function() { + const xtable_2_submit: Function = () => { var result: any[] = []; - for(var i = 0; i < 1000000; i++) { + for (var i = 0; i < 1000000; i++) { result.push({ name: "Alvin" + i, age: Math.floor(Math.random() * 100) + 1, location: "LA" }); } page = 1; xtable_2.update(result); xtable_2.resize(); - } + }; - let xtable_2_page: Function = function(no: number) { + const xtable_2_page: Function = (no: number) => { page += no; page = (page < 1) ? 1 : page; xtable_2.page(page); - } + }; }); -jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { - let xtable_4:GridXTable = xtable("#xtable_4", { +jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { + const xtable_4: GridXTable = xtable("#xtable_4", { fields: [ "name", "age", "location" ], data: [ { name: "Hong", age: "20", location: "Ilsan" }, @@ -96,25 +96,25 @@ jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { bufferCount: 20 }); - let xtable_4_submit: Function = function(isMulti: boolean) { - if(isMulti) { - xtable_4.filter(function(data: any) { - if(data.age >= 30 || data.name.indexOf("ng") != -1) { + const xtable_4_submit: Function = (isMulti: boolean) => { + if (isMulti) { + xtable_4.filter((data: any) => { + if (data.age >= 30 || data.name.indexOf("ng") !== -1) { return true; } }); } else { - xtable_4.filter(function(data: any) { - if(data.location.indexOf("eo") != -1) { + xtable_4.filter((data: any) => { + if (data.location.indexOf("eo") !== -1) { return true; } }); } - } + }; }); -jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { - let xtable_6: GridXTable = xtable("#xtable_6", { +jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { + const xtable_6: GridXTable = xtable("#xtable_6", { fields: [ "name", "age", "location" ], resize: true, sort: true, @@ -129,19 +129,19 @@ jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { } }); - let xtable_6_submit: Function = function() { + const xtable_6_submit: Function = () => { var result: any[] = []; - for(var i = 0; i < 1000000; i++) { + for (var i = 0; i < 1000000; i++) { result.push({ name: "Alvin" + i, age: Math.floor(Math.random() * 100) + 1, location: "LA" }); } xtable_6.update(result); - } + }; }); -jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { - let xtable_8: GridXTable = xtable("#xtable_8", { +jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { + const xtable_8: GridXTable = xtable("#xtable_8", { fields: [ "url", "count" ], resize: true, buffer: "vscroll", @@ -152,8 +152,8 @@ jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { none: $("#tpl_none").html() }, event: { - select: function(row: GridRow, e:any) { - if(row.type == "fold") { + select(row: GridRow, e: any) { + if (row.type === "fold") { xtable_8.open(row.index); } else { xtable_8.fold(row.index); diff --git a/jui-grid/tslint.json b/jui-grid/tslint.json index 377cc837d4..f05741c59b 100644 --- a/jui-grid/tslint.json +++ b/jui-grid/tslint.json @@ -1 +1,6 @@ -{ "extends": "../tslint.json" } +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/jui/jui-tests.ts b/jui/jui-tests.ts index 5bee2fdc2e..8a7a5d03f4 100644 --- a/jui/jui-tests.ts +++ b/jui/jui-tests.ts @@ -1,5 +1,3 @@ -/// - import {jui} from 'jui-core'; import { UIAccordion, UIAutoComplete, UIColorPicker, UICombo, UIDatePicker, UIDropdown, UIModal, UINotify, @@ -19,7 +17,7 @@ jui.ready([ 'ui.progress', 'ui.property', 'ui.select' -], function ( +], ( accordion: UIAccordion, autocomplete: UIAutoComplete, colorpicker: UIColorPicker, @@ -32,32 +30,32 @@ jui.ready([ progress: UIProgress, property: UIProperty, select: UISelect -) { - let a: UIAccordion = accordion("#test", { +) => { + const a: UIAccordion = accordion("#test", { multipanel: false }); console.log(a.activeIndex()); - let autoComplete: UIAutoComplete = autocomplete("#test", { + const autoComplete: UIAutoComplete = autocomplete("#test", { words : [] }); autoComplete.update([]); - let colorPicker: UIColorPicker = colorpicker("#test", { + const colorPicker: UIColorPicker = colorpicker("#test", { color: '#FFFF00' }); console.log(colorPicker.getColor('hex')); - let comboInstance: UICombo = combo("#test", { + const comboInstance: UICombo = combo("#test", { keydown: true - }) + }); console.log(comboInstance.getValue()); - let datePicker: UIDatePicker = datepicker("#test", { + const datePicker: UIDatePicker = datepicker("#test", { type: "daily" }); @@ -67,9 +65,9 @@ jui.ready([ datePicker.select(new Date()); - let dropdownInstance: UIDropdown = dropdown("#test", { + const dropdownInstance: UIDropdown = dropdown("#test", { width: 100 - }) + }); dropdownInstance.update([]); @@ -77,17 +75,17 @@ jui.ready([ dropdownInstance.reload(); - let m : UIModal = modal("#test", {autoHide: true}); + const m: UIModal = modal("#test", {autoHide: true}); m.show(); - let n: UINotify = notify("#test"); + const n: UINotify = notify("#test"); n.add({ title: "Caution message Send!!!", message: "Feb 15, 2013-12-24 02:24:19", color: 'warning' }, 1000); n.add({ title: "Caution message Send!!!", message: "Feb 15, 2013-12-24 02:24:19", color: 'success' }, 1000); n.reset(); - let p: UIPaging = paging("#test", { count :100, pageCount : 5 }); + const p: UIPaging = paging("#test", { count: 100, pageCount : 5 }); p.first(); p.last(); @@ -95,22 +93,22 @@ jui.ready([ p.prev(); p.page(10); - let prog: UIProgress = progress("#test", { striped: true }); + const prog: UIProgress = progress("#test", { striped: true }); console.log(prog.getValue()); prog.setValue(100); - let propertyView: UIProperty = property("#test", { + const propertyView: UIProperty = property("#test", { items : [ { type : 'group', title : 'Sample Category'}, { type : 'text', title : 'Category Name', key: 'sample-category-name', value : 'test'} ] - }) + }); console.log(propertyView.getValue()); - let selectInstance: UISelect = select("#test", { + const selectInstance: UISelect = select("#test", { items : [ { type : 'item', value : '0', text : 'first', html : '
test
', selected : true }, { type : 'divider' } diff --git a/jump.js/jump.js-tests.ts b/jump.js/jump.js-tests.ts index 4ae48074b2..bce5d68f21 100644 --- a/jump.js/jump.js-tests.ts +++ b/jump.js/jump.js-tests.ts @@ -1,6 +1,6 @@ import jump = require('jump.js'); -const node = document.querySelector('.target'); +const node = document.querySelector('.target')!; jump(node); jump('.target'); jump('.target', { @@ -12,5 +12,5 @@ jump('.target', { }); jump(100); jump(-100, { - callback: () => { console.log('Done!') } + callback: () => { console.log('Done!'); } }); diff --git a/jump.js/tsconfig.json b/jump.js/tsconfig.json index 0c6ab6d7c8..eb922b4eeb 100644 --- a/jump.js/tsconfig.json +++ b/jump.js/tsconfig.json @@ -1,7 +1,10 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6", + "dom" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +20,4 @@ "index.d.ts", "jump.js-tests.ts" ] -} +} \ No newline at end of file diff --git a/kendo-ui/index.d.ts b/kendo-ui/index.d.ts index ecdbffae66..86f9624227 100644 --- a/kendo-ui/index.d.ts +++ b/kendo-ui/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Kendo UI Professional v2016.3.1029 +// Type definitions for Kendo UI Professional v2017.1.118 // Project: http://www.telerik.com/kendo-ui // Definitions by: Telerik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -678,8 +678,8 @@ declare namespace kendo.data { static fields: DataSourceSchemaModelFields; id: any; - predecessorId: any; - successorId: any; + predecessorId: number; + successorId: number; type: number; static define(options: DataSourceSchemaModelWithFieldsObject): typeof GanttDependency; @@ -1135,7 +1135,7 @@ declare namespace kendo.data { interface DataSourceFilters extends DataSourceFilter { logic?: string; - filters?: DataSourceFilter[]; + filters?: DataSourceFilter[]; } interface DataSourceGroupItemAggregate { @@ -1656,6 +1656,7 @@ declare namespace kendo.ui { interface AutoCompleteOptions { name?: string; animation?: boolean|AutoCompleteAnimation; + autoWidth?: boolean; dataSource?: any|any|kendo.data.DataSource; clearButton?: boolean; dataTextField?: string; @@ -1790,6 +1791,7 @@ declare namespace kendo.ui { interface CalendarMonth { content?: string; + weekNumber?: string; empty?: string; } @@ -1804,6 +1806,7 @@ declare namespace kendo.ui { max?: Date; min?: Date; month?: CalendarMonth; + weekNumber?: boolean; start?: string; value?: Date; change?(e: CalendarEvent): void; @@ -1898,6 +1901,7 @@ declare namespace kendo.ui { interface ColorPickerOptions { name?: string; buttons?: boolean; + clearButton?: boolean; columns?: number; tileSize?: ColorPickerTileSize; messages?: ColorPickerMessages; @@ -2000,6 +2004,7 @@ declare namespace kendo.ui { name?: string; animation?: ComboBoxAnimation; autoBind?: boolean; + autoWidth?: boolean; cascadeFrom?: string; cascadeFromField?: string; clearButton?: boolean; @@ -2022,6 +2027,7 @@ declare namespace kendo.ui { placeholder?: string; popup?: ComboBoxPopup; suggest?: boolean; + syncValueAndText?: boolean; headerTemplate?: string|Function; template?: string|Function; text?: string; @@ -2159,6 +2165,7 @@ declare namespace kendo.ui { name?: string; alignToAnchor?: boolean; animation?: boolean|ContextMenuAnimation; + appendTo?: string|JQuery; closeOnClick?: boolean; dataSource?: any|any; direction?: string; @@ -2263,6 +2270,7 @@ declare namespace kendo.ui { interface DatePickerMonth { content?: string; + weekNumber?: string; empty?: string; } @@ -2279,6 +2287,7 @@ declare namespace kendo.ui { max?: Date; min?: Date; month?: DatePickerMonth; + weekNumber?: boolean; parseFormats?: any; start?: string; value?: Date; @@ -2353,6 +2362,7 @@ declare namespace kendo.ui { interface DateTimePickerMonth { content?: string; + weekNumber?: string; empty?: string; } @@ -2370,6 +2380,7 @@ declare namespace kendo.ui { max?: Date; min?: Date; month?: DateTimePickerMonth; + weekNumber?: boolean; parseFormats?: any; start?: string; timeFormat?: string; @@ -2558,6 +2569,7 @@ declare namespace kendo.ui { name?: string; animation?: boolean|DropDownListAnimation; autoBind?: boolean; + autoWidth?: boolean; cascadeFrom?: string; cascadeFromField?: string; dataSource?: any|any|kendo.data.DataSource; @@ -2986,6 +2998,7 @@ declare namespace kendo.ui { tooltip?: string; exec?: Function; items?: EditorToolItem[]; + palette?: string|any; template?: string; } @@ -3065,6 +3078,9 @@ declare namespace kendo.ui { clear?: string; filter?: string; info?: string; + additionalValue?: string; + additionalOperator?: string; + logic?: string; isFalse?: string; isTrue?: string; or?: string; @@ -3625,6 +3641,7 @@ declare namespace kendo.ui { } interface GridColumnCommandItem { + visible?: Function; name?: string; text?: GridColumnCommandItemText; className?: string; @@ -3659,6 +3676,7 @@ declare namespace kendo.ui { interface GridColumnSortable { compare?: Function; + initialDirection?: string; } interface GridColumn { @@ -3666,6 +3684,7 @@ declare namespace kendo.ui { attributes?: any; columns?: any; command?: GridColumnCommandItem[]; + editable?: Function; encoded?: boolean; field?: string; filterable?: boolean|GridColumnFilterable; @@ -3680,6 +3699,7 @@ declare namespace kendo.ui { hidden?: boolean; locked?: boolean; lockable?: boolean; + minResizableWidth?: number; minScreenWidth?: number; sortable?: boolean|GridColumnSortable; template?: string|Function; @@ -3779,8 +3799,8 @@ declare namespace kendo.ui { interface GridFilterable { extra?: boolean; messages?: GridFilterableMessages; - operators?: GridFilterableOperators; mode?: string; + operators?: GridFilterableOperators; } interface GridGroupableMessages { @@ -3873,6 +3893,7 @@ declare namespace kendo.ui { interface GridSortable { allowUnsort?: boolean; + initialDirection?: string; mode?: string; } @@ -4428,6 +4449,7 @@ declare namespace kendo.ui { animation?: boolean|MultiSelectAnimation; autoBind?: boolean; autoClose?: boolean; + autoWidth?: boolean; clearButton?: boolean; dataSource?: any|any|kendo.data.DataSource; dataTextField?: string; @@ -4797,15 +4819,30 @@ declare namespace kendo.ui { expand?: PanelBarAnimationExpand; } + interface PanelBarMessages { + loading?: string; + requestFailed?: string; + retry?: string; + } + interface PanelBarOptions { name?: string; animation?: boolean|PanelBarAnimation; + autoBind?: boolean; contentUrls?: any; - dataSource?: any|any; + dataImageUrlField?: string; + dataSource?: any|any|kendo.data.HierarchicalDataSource; + dataSpriteCssClassField?: string; + dataTextField?: string|any; + dataUrlField?: string; expandMode?: string; + loadOnDemand?: boolean; + messages?: PanelBarMessages; + template?: string|Function; activate?(e: PanelBarActivateEvent): void; collapse?(e: PanelBarCollapseEvent): void; contentLoad?(e: PanelBarContentLoadEvent): void; + dataBound?(e: PanelBarDataBoundEvent): void; error?(e: PanelBarErrorEvent): void; expand?(e: PanelBarExpandEvent): void; select?(e: PanelBarSelectEvent): void; @@ -4829,6 +4866,10 @@ declare namespace kendo.ui { contentElement?: Element; } + interface PanelBarDataBoundEvent extends PanelBarEvent { + node?: JQuery; + } + interface PanelBarErrorEvent extends PanelBarEvent { xhr?: JQueryXHR; status?: string; @@ -5629,6 +5670,7 @@ declare namespace kendo.ui { eventTemplate?: string|Function; footer?: boolean|SchedulerFooter; group?: SchedulerGroup; + groupHeaderTemplate?: string|Function; height?: number|string; majorTick?: number; majorTimeHeaderTemplate?: string|Function; @@ -5647,7 +5689,6 @@ declare namespace kendo.ui { timezone?: string; toolbar?: SchedulerToolbarItem[]; views?: SchedulerView[]; - groupHeaderTemplate?: string|Function; width?: number|string; workDayStart?: Date; workDayEnd?: Date; @@ -6021,6 +6062,9 @@ declare namespace kendo.ui { activeSheet(): kendo.spreadsheet.Sheet; activeSheet(sheet?: kendo.spreadsheet.Sheet): void; + cellContextMenu(): kendo.ui.ContextMenu; + rowHeaderContextMenu(): kendo.ui.ContextMenu; + colHeaderContextMenu(): kendo.ui.ContextMenu; sheets(): any; fromFile(blob: Blob): JQueryPromise; fromFile(blob: File): JQueryPromise; @@ -6040,6 +6084,17 @@ declare namespace kendo.ui { } + interface SpreadsheetDefaultCellStyle { + background?: string; + color?: string; + fontFamily?: string; + fontSize?: string; + Italic?: boolean; + bold?: boolean; + underline?: boolean; + wrap?: boolean; + } + interface SpreadsheetExcel { fileName?: string; forceProxy?: boolean; @@ -6209,6 +6264,7 @@ declare namespace kendo.ui { activeSheet?: string; columnWidth?: number; columns?: number; + defaultCellStyle?: SpreadsheetDefaultCellStyle; headerHeight?: number; headerWidth?: number; excel?: SpreadsheetExcel; @@ -6218,6 +6274,20 @@ declare namespace kendo.ui { sheets?: SpreadsheetSheet[]; sheetsbar?: boolean; toolbar?: boolean|SpreadsheetToolbar; + insertSheet?(e: SpreadsheetInsertSheetEvent): void; + removeSheet?(e: SpreadsheetRemoveSheetEvent): void; + renameSheet?(e: SpreadsheetRenameSheetEvent): void; + selectSheet?(e: SpreadsheetSelectSheetEvent): void; + unhideColumn?(e: SpreadsheetUnhideColumnEvent): void; + unhideRow?(e: SpreadsheetUnhideRowEvent): void; + hideColumn?(e: SpreadsheetHideColumnEvent): void; + hideRow?(e: SpreadsheetHideRowEvent): void; + deleteColumn?(e: SpreadsheetDeleteColumnEvent): void; + deleteRow?(e: SpreadsheetDeleteRowEvent): void; + insertColumn?(e: SpreadsheetInsertColumnEvent): void; + insertRow?(e: SpreadsheetInsertRowEvent): void; + select?(e: SpreadsheetSelectEvent): void; + changeFormat?(e: SpreadsheetChangeFormatEvent): void; change?(e: SpreadsheetChangeEvent): void; render?(e: SpreadsheetRenderEvent): void; excelExport?(e: SpreadsheetExcelExportEvent): void; @@ -6230,6 +6300,70 @@ declare namespace kendo.ui { isDefaultPrevented(): boolean; } + interface SpreadsheetInsertSheetEvent extends SpreadsheetEvent { + } + + interface SpreadsheetRemoveSheetEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + } + + interface SpreadsheetRenameSheetEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + newSheetName?: string; + } + + interface SpreadsheetSelectSheetEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + } + + interface SpreadsheetUnhideColumnEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetUnhideRowEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetHideColumnEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetHideRowEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetDeleteColumnEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetDeleteRowEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetInsertColumnEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetInsertRowEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetSelectEvent extends SpreadsheetEvent { + range?: kendo.spreadsheet.Range; + } + + interface SpreadsheetChangeFormatEvent extends SpreadsheetEvent { + range?: kendo.spreadsheet.Range; + } + interface SpreadsheetChangeEvent extends SpreadsheetEvent { range?: kendo.spreadsheet.Range; } @@ -6616,6 +6750,7 @@ declare namespace kendo.ui { options: TooltipOptions; + popup: kendo.ui.Popup; element: JQuery; wrapper: JQuery; @@ -6774,6 +6909,7 @@ declare namespace kendo.ui { interface TouchSwipeEvent extends TouchEvent { touch?: kendo.mobile.ui.TouchEventOptions; event?: JQueryEventObject; + direction?: string; } interface TouchGesturestartEvent extends TouchEvent { @@ -6873,6 +7009,7 @@ declare namespace kendo.ui { interface TreeListColumnCommandItem { className?: string; + imageClass?: string; click?: Function; name?: string; text?: string; @@ -7344,15 +7481,16 @@ declare namespace kendo.ui { clearAllFiles(): void; - clearFile(): void; + clearFile(callback: Function): void; clearFileByUid(uid: string): void; destroy(): void; disable(): void; enable(enable?: boolean): void; + focus(): void; getFiles(): any; removeAllFiles(): void; - removeFile(): void; - removeFileByUid(): void; + removeFile(callback: Function): void; + removeFileByUid(uid: string): void; toggle(enable: boolean): void; upload(): void; @@ -7412,6 +7550,7 @@ declare namespace kendo.ui { template?: string|Function; validation?: UploadValidation; cancel?(e: UploadCancelEvent): void; + clear?(e: UploadClearEvent): void; complete?(e: UploadEvent): void; error?(e: UploadErrorEvent): void; progress?(e: UploadProgressEvent): void; @@ -7427,39 +7566,43 @@ declare namespace kendo.ui { } interface UploadCancelEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; + } + + interface UploadClearEvent extends UploadEvent { + e?: any; } interface UploadErrorEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; operation?: string; XMLHttpRequest?: any; } interface UploadProgressEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; percentComplete?: number; } interface UploadRemoveEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; data?: any; } interface UploadSelectEvent extends UploadEvent { e?: any; - files?: UploadFile[]; + files?: any[]; } interface UploadSuccessEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; operation?: string; response?: any; XMLHttpRequest?: any; } interface UploadUploadEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; data?: any; formData?: any; XMLHttpRequest?: any; @@ -7496,6 +7639,7 @@ declare namespace kendo.ui { rules?: any; validateOnBlur?: boolean; validate?(e: ValidatorValidateEvent): void; + validateInput?(e: ValidatorValidateInputEvent): void; } interface ValidatorEvent { sender: Validator; @@ -7507,6 +7651,11 @@ declare namespace kendo.ui { valid?: boolean; } + interface ValidatorValidateInputEvent extends ValidatorEvent { + input?: JQuery; + valid?: boolean; + } + class Window extends kendo.ui.Widget { @@ -7629,6 +7778,274 @@ declare namespace kendo.ui { } +} +declare namespace kendo.geometry { + class Arc extends Observable { + + + options: ArcOptions; + + anticlockwise: boolean; + center: kendo.geometry.Point; + endAngle: number; + radiusX: number; + radiusY: number; + startAngle: number; + + constructor(center: any|kendo.geometry.Point, options?: ArcOptions); + + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + getAnticlockwise(): boolean; + getCenter(): kendo.geometry.Point; + getEndAngle(): number; + getRadiusX(): number; + getRadiusY(): number; + getStartAngle(): number; + pointAt(angle: number): kendo.geometry.Point; + setAnticlockwise(value: boolean): kendo.geometry.Arc; + setCenter(value: kendo.geometry.Point): kendo.geometry.Arc; + setEndAngle(value: number): kendo.geometry.Arc; + setRadiusX(value: number): kendo.geometry.Arc; + setRadiusY(value: number): kendo.geometry.Arc; + setStartAngle(value: number): kendo.geometry.Arc; + + } + + interface ArcOptions { + name?: string; + } + interface ArcEvent { + sender: Arc; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Circle extends Observable { + + + options: CircleOptions; + + center: kendo.geometry.Point; + radius: number; + + constructor(center: any|kendo.geometry.Point, radius: number); + + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + clone(): kendo.geometry.Circle; + equals(other: kendo.geometry.Circle): boolean; + getCenter(): kendo.geometry.Point; + getRadius(): number; + pointAt(angle: number): kendo.geometry.Point; + setCenter(value: kendo.geometry.Point): kendo.geometry.Point; + setCenter(value: any): kendo.geometry.Point; + setRadius(value: number): kendo.geometry.Circle; + + } + + interface CircleOptions { + name?: string; + } + interface CircleEvent { + sender: Circle; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Matrix extends Observable { + + + options: MatrixOptions; + + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + + + static rotate(angle: number, x: number, y: number): kendo.geometry.Matrix; + static scale(scaleX: number, scaleY: number): kendo.geometry.Matrix; + static translate(x: number, y: number): kendo.geometry.Matrix; + static unit(): kendo.geometry.Matrix; + + clone(): kendo.geometry.Matrix; + equals(other: kendo.geometry.Matrix): boolean; + round(digits: number): kendo.geometry.Matrix; + multiplyCopy(matrix: kendo.geometry.Matrix): kendo.geometry.Matrix; + toArray(digits: number): any; + toString(digits: number, separator: string): string; + + } + + interface MatrixOptions { + name?: string; + } + interface MatrixEvent { + sender: Matrix; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Point extends Observable { + + + options: PointOptions; + + x: number; + y: number; + + constructor(x: number, y: number); + + static create(x: number, y: number): kendo.geometry.Point; + static create(x: any, y: number): kendo.geometry.Point; + static create(x: kendo.geometry.Point, y: number): kendo.geometry.Point; + static min(): kendo.geometry.Point; + static max(): kendo.geometry.Point; + static minPoint(): kendo.geometry.Point; + static maxPoint(): kendo.geometry.Point; + + clone(): kendo.geometry.Point; + distanceTo(point: kendo.geometry.Point): number; + equals(other: kendo.geometry.Point): boolean; + getX(): number; + getY(): number; + move(x: number, y: number): kendo.geometry.Point; + rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Point; + rotate(angle: number, center: any): kendo.geometry.Point; + round(digits: number): kendo.geometry.Point; + scale(scaleX: number, scaleY: number): kendo.geometry.Point; + scaleCopy(scaleX: number, scaleY: number): kendo.geometry.Point; + setX(value: number): kendo.geometry.Point; + setY(value: number): kendo.geometry.Point; + toArray(digits: number): any; + toString(digits: number, separator: string): string; + transform(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; + transformCopy(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; + translate(dx: number, dy: number): kendo.geometry.Point; + translateWith(vector: kendo.geometry.Point): kendo.geometry.Point; + translateWith(vector: any): kendo.geometry.Point; + + } + + interface PointOptions { + name?: string; + } + interface PointEvent { + sender: Point; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Rect extends Observable { + + + options: RectOptions; + + origin: kendo.geometry.Point; + size: kendo.geometry.Size; + + 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; + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + bottomLeft(): kendo.geometry.Point; + bottomRight(): kendo.geometry.Point; + center(): kendo.geometry.Point; + clone(): kendo.geometry.Rect; + equals(other: kendo.geometry.Rect): boolean; + getOrigin(): kendo.geometry.Point; + getSize(): kendo.geometry.Size; + height(): number; + setOrigin(value: kendo.geometry.Point): kendo.geometry.Rect; + setOrigin(value: any): kendo.geometry.Rect; + setSize(value: kendo.geometry.Size): kendo.geometry.Rect; + setSize(value: any): kendo.geometry.Rect; + topLeft(): kendo.geometry.Point; + topRight(): kendo.geometry.Point; + width(): number; + + } + + interface RectOptions { + name?: string; + } + interface RectEvent { + sender: Rect; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Size extends Observable { + + + options: SizeOptions; + + width: number; + height: number; + + + static create(width: number, height: number): kendo.geometry.Size; + static create(width: any, height: number): kendo.geometry.Size; + static create(width: kendo.geometry.Size, height: number): kendo.geometry.Size; + + clone(): kendo.geometry.Size; + equals(other: kendo.geometry.Size): boolean; + getWidth(): number; + getHeight(): number; + setWidth(value: number): kendo.geometry.Size; + setHeight(value: number): kendo.geometry.Size; + + } + + interface SizeOptions { + name?: string; + } + interface SizeEvent { + sender: Size; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Transformation extends Observable { + + + options: TransformationOptions; + + + + + clone(): kendo.geometry.Transformation; + equals(other: kendo.geometry.Transformation): boolean; + matrix(): kendo.geometry.Matrix; + multiply(transformation: kendo.geometry.Transformation): kendo.geometry.Transformation; + rotate(angle: number, center: any): kendo.geometry.Transformation; + rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Transformation; + scale(scaleX: number, scaleY: number): kendo.geometry.Transformation; + translate(x: number, y: number): kendo.geometry.Transformation; + + } + + interface TransformationOptions { + name?: string; + } + interface TransformationEvent { + sender: Transformation; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + } declare namespace kendo.drawing { class Arc extends kendo.drawing.Element { @@ -8419,274 +8836,6 @@ declare namespace kendo.drawing { -} -declare namespace kendo.geometry { - class Arc extends Observable { - - - options: ArcOptions; - - anticlockwise: boolean; - center: kendo.geometry.Point; - endAngle: number; - radiusX: number; - radiusY: number; - startAngle: number; - - constructor(center: any|kendo.geometry.Point, options?: ArcOptions); - - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - getAnticlockwise(): boolean; - getCenter(): kendo.geometry.Point; - getEndAngle(): number; - getRadiusX(): number; - getRadiusY(): number; - getStartAngle(): number; - pointAt(angle: number): kendo.geometry.Point; - setAnticlockwise(value: boolean): kendo.geometry.Arc; - setCenter(value: kendo.geometry.Point): kendo.geometry.Arc; - setEndAngle(value: number): kendo.geometry.Arc; - setRadiusX(value: number): kendo.geometry.Arc; - setRadiusY(value: number): kendo.geometry.Arc; - setStartAngle(value: number): kendo.geometry.Arc; - - } - - interface ArcOptions { - name?: string; - } - interface ArcEvent { - sender: Arc; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Circle extends Observable { - - - options: CircleOptions; - - center: kendo.geometry.Point; - radius: number; - - constructor(center: any|kendo.geometry.Point, radius: number); - - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - clone(): kendo.geometry.Circle; - equals(other: kendo.geometry.Circle): boolean; - getCenter(): kendo.geometry.Point; - getRadius(): number; - pointAt(angle: number): kendo.geometry.Point; - setCenter(value: kendo.geometry.Point): kendo.geometry.Point; - setCenter(value: any): kendo.geometry.Point; - setRadius(value: number): kendo.geometry.Circle; - - } - - interface CircleOptions { - name?: string; - } - interface CircleEvent { - sender: Circle; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Matrix extends Observable { - - - options: MatrixOptions; - - a: number; - b: number; - c: number; - d: number; - e: number; - f: number; - - - static rotate(angle: number, x: number, y: number): kendo.geometry.Matrix; - static scale(scaleX: number, scaleY: number): kendo.geometry.Matrix; - static translate(x: number, y: number): kendo.geometry.Matrix; - static unit(): kendo.geometry.Matrix; - - clone(): kendo.geometry.Matrix; - equals(other: kendo.geometry.Matrix): boolean; - round(digits: number): kendo.geometry.Matrix; - multiplyCopy(matrix: kendo.geometry.Matrix): kendo.geometry.Matrix; - toArray(digits: number): any; - toString(digits?: number, separator?: string): string; - - } - - interface MatrixOptions { - name?: string; - } - interface MatrixEvent { - sender: Matrix; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Point extends Observable { - - - options: PointOptions; - - x: number; - y: number; - - constructor(x: number, y: number); - - static create(x: number, y: number): kendo.geometry.Point; - static create(x: any, y: number): kendo.geometry.Point; - static create(x: kendo.geometry.Point, y: number): kendo.geometry.Point; - static min(): kendo.geometry.Point; - static max(): kendo.geometry.Point; - static minPoint(): kendo.geometry.Point; - static maxPoint(): kendo.geometry.Point; - - clone(): kendo.geometry.Point; - distanceTo(point: kendo.geometry.Point): number; - equals(other: kendo.geometry.Point): boolean; - getX(): number; - getY(): number; - move(x: number, y: number): kendo.geometry.Point; - rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Point; - rotate(angle: number, center: any): kendo.geometry.Point; - round(digits: number): kendo.geometry.Point; - scale(scaleX: number, scaleY: number): kendo.geometry.Point; - scaleCopy(scaleX: number, scaleY: number): kendo.geometry.Point; - setX(value: number): kendo.geometry.Point; - setY(value: number): kendo.geometry.Point; - toArray(digits: number): any; - toString(digits?: number, separator?: string): string; - transform(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; - transformCopy(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; - translate(dx: number, dy: number): kendo.geometry.Point; - translateWith(vector: kendo.geometry.Point): kendo.geometry.Point; - translateWith(vector: any): kendo.geometry.Point; - - } - - interface PointOptions { - name?: string; - } - interface PointEvent { - sender: Point; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Rect extends Observable { - - - options: RectOptions; - - origin: kendo.geometry.Point; - size: kendo.geometry.Size; - - 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; - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - bottomLeft(): kendo.geometry.Point; - bottomRight(): kendo.geometry.Point; - center(): kendo.geometry.Point; - clone(): kendo.geometry.Rect; - equals(other: kendo.geometry.Rect): boolean; - getOrigin(): kendo.geometry.Point; - getSize(): kendo.geometry.Size; - height(): number; - setOrigin(value: kendo.geometry.Point): kendo.geometry.Rect; - setOrigin(value: any): kendo.geometry.Rect; - setSize(value: kendo.geometry.Size): kendo.geometry.Rect; - setSize(value: any): kendo.geometry.Rect; - topLeft(): kendo.geometry.Point; - topRight(): kendo.geometry.Point; - width(): number; - - } - - interface RectOptions { - name?: string; - } - interface RectEvent { - sender: Rect; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Size extends Observable { - - - options: SizeOptions; - - width: number; - height: number; - - - static create(width: number, height: number): kendo.geometry.Size; - static create(width: any, height: number): kendo.geometry.Size; - static create(width: kendo.geometry.Size, height: number): kendo.geometry.Size; - - clone(): kendo.geometry.Size; - equals(other: kendo.geometry.Size): boolean; - getWidth(): number; - getHeight(): number; - setWidth(value: number): kendo.geometry.Size; - setHeight(value: number): kendo.geometry.Size; - - } - - interface SizeOptions { - name?: string; - } - interface SizeEvent { - sender: Size; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Transformation extends Observable { - - - options: TransformationOptions; - - - - - clone(): kendo.geometry.Transformation; - equals(other: kendo.geometry.Transformation): boolean; - matrix(): kendo.geometry.Matrix; - multiply(transformation: kendo.geometry.Transformation): kendo.geometry.Transformation; - rotate(angle: number, center: any): kendo.geometry.Transformation; - rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Transformation; - scale(scaleX: number, scaleY: number): kendo.geometry.Transformation; - translate(x: number, y: number): kendo.geometry.Transformation; - - } - - interface TransformationOptions { - name?: string; - } - interface TransformationEvent { - sender: Transformation; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - } declare namespace kendo.dataviz.ui { class Barcode extends kendo.ui.Widget { @@ -9681,6 +9830,7 @@ declare namespace kendo.dataviz.ui { margin?: ChartSeriesItemLabelsMargin; padding?: ChartSeriesItemLabelsPadding; position?: string|Function; + rotation?: string|number; template?: string|Function; visible?: boolean|Function; visual?: Function; @@ -9833,6 +9983,7 @@ declare namespace kendo.dataviz.ui { aggregate?: string|Function; axis?: string; border?: ChartSeriesItemBorder; + categoryAxis?: string; categoryField?: string; closeField?: string; color?: string|Function; @@ -10009,6 +10160,7 @@ declare namespace kendo.dataviz.ui { format?: string; margin?: ChartSeriesDefaultsLabelsMargin; padding?: ChartSeriesDefaultsLabelsPadding; + rotation?: string|number; template?: string|Function; visible?: boolean; visual?: Function; @@ -14295,7 +14447,7 @@ declare namespace kendo.dataviz.ui { inactiveItems?: StockChartLegendInactiveItems; } - interface StockChartNavigatorCategoryAxisItemAutoBaseUnitSteps { + interface StockChartNavigatorCategoryAxisAutoBaseUnitSteps { seconds?: any; minutes?: any; hours?: any; @@ -14305,45 +14457,45 @@ declare namespace kendo.dataviz.ui { years?: any; } - interface StockChartNavigatorCategoryAxisItemCrosshairTooltipBorder { + interface StockChartNavigatorCategoryAxisCrosshairTooltipBorder { color?: string; dashType?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemCrosshairTooltipPadding { + interface StockChartNavigatorCategoryAxisCrosshairTooltipPadding { bottom?: number; left?: number; right?: number; top?: number; } - interface StockChartNavigatorCategoryAxisItemCrosshairTooltip { + interface StockChartNavigatorCategoryAxisCrosshairTooltip { background?: string; - border?: StockChartNavigatorCategoryAxisItemCrosshairTooltipBorder; + border?: StockChartNavigatorCategoryAxisCrosshairTooltipBorder; color?: string; font?: string; format?: string; - padding?: StockChartNavigatorCategoryAxisItemCrosshairTooltipPadding; + padding?: StockChartNavigatorCategoryAxisCrosshairTooltipPadding; template?: string|Function; visible?: boolean; } - interface StockChartNavigatorCategoryAxisItemCrosshair { + interface StockChartNavigatorCategoryAxisCrosshair { color?: string; opacity?: number; - tooltip?: StockChartNavigatorCategoryAxisItemCrosshairTooltip; + tooltip?: StockChartNavigatorCategoryAxisCrosshairTooltip; visible?: boolean; width?: number; } - interface StockChartNavigatorCategoryAxisItemLabelsBorder { + interface StockChartNavigatorCategoryAxisLabelsBorder { color?: string; dashType?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemLabelsDateFormats { + interface StockChartNavigatorCategoryAxisLabelsDateFormats { days?: string; hours?: string; months?: string; @@ -14351,31 +14503,31 @@ declare namespace kendo.dataviz.ui { years?: string; } - interface StockChartNavigatorCategoryAxisItemLabelsMargin { + interface StockChartNavigatorCategoryAxisLabelsMargin { bottom?: number; left?: number; right?: number; top?: number; } - interface StockChartNavigatorCategoryAxisItemLabelsPadding { + interface StockChartNavigatorCategoryAxisLabelsPadding { bottom?: number; left?: number; right?: number; top?: number; } - interface StockChartNavigatorCategoryAxisItemLabels { + interface StockChartNavigatorCategoryAxisLabels { background?: string; - border?: StockChartNavigatorCategoryAxisItemLabelsBorder; + border?: StockChartNavigatorCategoryAxisLabelsBorder; color?: string; culture?: string; - dateFormats?: StockChartNavigatorCategoryAxisItemLabelsDateFormats; + dateFormats?: StockChartNavigatorCategoryAxisLabelsDateFormats; font?: string; format?: string; - margin?: StockChartNavigatorCategoryAxisItemLabelsMargin; + margin?: StockChartNavigatorCategoryAxisLabelsMargin; mirror?: boolean; - padding?: StockChartNavigatorCategoryAxisItemLabelsPadding; + padding?: StockChartNavigatorCategoryAxisLabelsPadding; rotation?: number; skip?: number; step?: number; @@ -14383,14 +14535,14 @@ declare namespace kendo.dataviz.ui { visible?: boolean; } - interface StockChartNavigatorCategoryAxisItemLine { + interface StockChartNavigatorCategoryAxisLine { color?: string; dashType?: string; visible?: boolean; width?: number; } - interface StockChartNavigatorCategoryAxisItemMajorGridLines { + interface StockChartNavigatorCategoryAxisMajorGridLines { color?: string; dashType?: string; visible?: boolean; @@ -14399,7 +14551,7 @@ declare namespace kendo.dataviz.ui { skip?: number; } - interface StockChartNavigatorCategoryAxisItemMajorTicks { + interface StockChartNavigatorCategoryAxisMajorTicks { color?: string; size?: number; visible?: boolean; @@ -14408,7 +14560,7 @@ declare namespace kendo.dataviz.ui { skip?: number; } - interface StockChartNavigatorCategoryAxisItemMinorGridLines { + interface StockChartNavigatorCategoryAxisMinorGridLines { color?: string; dashType?: string; visible?: boolean; @@ -14417,7 +14569,7 @@ declare namespace kendo.dataviz.ui { skip?: number; } - interface StockChartNavigatorCategoryAxisItemMinorTicks { + interface StockChartNavigatorCategoryAxisMinorTicks { color?: string; size?: number; visible?: boolean; @@ -14426,28 +14578,28 @@ declare namespace kendo.dataviz.ui { skip?: number; } - interface StockChartNavigatorCategoryAxisItemNotesDataItemIconBorder { + interface StockChartNavigatorCategoryAxisNotesDataItemIconBorder { color?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemNotesDataItemIcon { + interface StockChartNavigatorCategoryAxisNotesDataItemIcon { background?: string; - border?: StockChartNavigatorCategoryAxisItemNotesDataItemIconBorder; + border?: StockChartNavigatorCategoryAxisNotesDataItemIconBorder; size?: number; type?: string; visible?: boolean; } - interface StockChartNavigatorCategoryAxisItemNotesDataItemLabelBorder { + interface StockChartNavigatorCategoryAxisNotesDataItemLabelBorder { color?: string; dashType?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemNotesDataItemLabel { + interface StockChartNavigatorCategoryAxisNotesDataItemLabel { background?: string; - border?: StockChartNavigatorCategoryAxisItemNotesDataItemLabelBorder; + border?: StockChartNavigatorCategoryAxisNotesDataItemLabelBorder; color?: string; font?: string; template?: string|Function; @@ -14458,42 +14610,42 @@ declare namespace kendo.dataviz.ui { position?: string; } - interface StockChartNavigatorCategoryAxisItemNotesDataItemLine { + interface StockChartNavigatorCategoryAxisNotesDataItemLine { width?: number; color?: string; length?: number; } - interface StockChartNavigatorCategoryAxisItemNotesDataItem { + interface StockChartNavigatorCategoryAxisNotesDataItem { value?: any; position?: string; - icon?: StockChartNavigatorCategoryAxisItemNotesDataItemIcon; - label?: StockChartNavigatorCategoryAxisItemNotesDataItemLabel; - line?: StockChartNavigatorCategoryAxisItemNotesDataItemLine; + icon?: StockChartNavigatorCategoryAxisNotesDataItemIcon; + label?: StockChartNavigatorCategoryAxisNotesDataItemLabel; + line?: StockChartNavigatorCategoryAxisNotesDataItemLine; } - interface StockChartNavigatorCategoryAxisItemNotesIconBorder { + interface StockChartNavigatorCategoryAxisNotesIconBorder { color?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemNotesIcon { + interface StockChartNavigatorCategoryAxisNotesIcon { background?: string; - border?: StockChartNavigatorCategoryAxisItemNotesIconBorder; + border?: StockChartNavigatorCategoryAxisNotesIconBorder; size?: number; type?: string; visible?: boolean; } - interface StockChartNavigatorCategoryAxisItemNotesLabelBorder { + interface StockChartNavigatorCategoryAxisNotesLabelBorder { color?: string; dashType?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemNotesLabel { + interface StockChartNavigatorCategoryAxisNotesLabel { background?: string; - border?: StockChartNavigatorCategoryAxisItemNotesLabelBorder; + border?: StockChartNavigatorCategoryAxisNotesLabelBorder; color?: string; font?: string; template?: string|Function; @@ -14503,87 +14655,87 @@ declare namespace kendo.dataviz.ui { position?: string; } - interface StockChartNavigatorCategoryAxisItemNotesLine { + interface StockChartNavigatorCategoryAxisNotesLine { width?: number; color?: string; length?: number; } - interface StockChartNavigatorCategoryAxisItemNotes { + interface StockChartNavigatorCategoryAxisNotes { position?: string; - icon?: StockChartNavigatorCategoryAxisItemNotesIcon; - label?: StockChartNavigatorCategoryAxisItemNotesLabel; - line?: StockChartNavigatorCategoryAxisItemNotesLine; - data?: StockChartNavigatorCategoryAxisItemNotesDataItem[]; + icon?: StockChartNavigatorCategoryAxisNotesIcon; + label?: StockChartNavigatorCategoryAxisNotesLabel; + line?: StockChartNavigatorCategoryAxisNotesLine; + data?: StockChartNavigatorCategoryAxisNotesDataItem[]; } - interface StockChartNavigatorCategoryAxisItemPlotBand { + interface StockChartNavigatorCategoryAxisPlotBand { color?: string; from?: number; opacity?: number; to?: number; } - interface StockChartNavigatorCategoryAxisItemTitleBorder { + interface StockChartNavigatorCategoryAxisTitleBorder { color?: string; dashType?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemTitleMargin { + interface StockChartNavigatorCategoryAxisTitleMargin { bottom?: number; left?: number; right?: number; top?: number; } - interface StockChartNavigatorCategoryAxisItemTitlePadding { + interface StockChartNavigatorCategoryAxisTitlePadding { bottom?: number; left?: number; right?: number; top?: number; } - interface StockChartNavigatorCategoryAxisItemTitle { + interface StockChartNavigatorCategoryAxisTitle { background?: string; - border?: StockChartNavigatorCategoryAxisItemTitleBorder; + border?: StockChartNavigatorCategoryAxisTitleBorder; color?: string; font?: string; - margin?: StockChartNavigatorCategoryAxisItemTitleMargin; - padding?: StockChartNavigatorCategoryAxisItemTitlePadding; + margin?: StockChartNavigatorCategoryAxisTitleMargin; + padding?: StockChartNavigatorCategoryAxisTitlePadding; position?: string; rotation?: number; text?: string; visible?: boolean; } - interface StockChartNavigatorCategoryAxisItem { - autoBaseUnitSteps?: StockChartNavigatorCategoryAxisItemAutoBaseUnitSteps; + interface StockChartNavigatorCategoryAxis { + autoBaseUnitSteps?: StockChartNavigatorCategoryAxisAutoBaseUnitSteps; axisCrossingValue?: any|Date|any; background?: string; baseUnit?: string; baseUnitStep?: any; categories?: any; color?: string; - crosshair?: StockChartNavigatorCategoryAxisItemCrosshair; + crosshair?: StockChartNavigatorCategoryAxisCrosshair; field?: string; justified?: boolean; - labels?: StockChartNavigatorCategoryAxisItemLabels; - line?: StockChartNavigatorCategoryAxisItemLine; - majorGridLines?: StockChartNavigatorCategoryAxisItemMajorGridLines; - majorTicks?: StockChartNavigatorCategoryAxisItemMajorTicks; + labels?: StockChartNavigatorCategoryAxisLabels; + line?: StockChartNavigatorCategoryAxisLine; + majorGridLines?: StockChartNavigatorCategoryAxisMajorGridLines; + majorTicks?: StockChartNavigatorCategoryAxisMajorTicks; max?: any; maxDateGroups?: number; min?: any; - minorGridLines?: StockChartNavigatorCategoryAxisItemMinorGridLines; - minorTicks?: StockChartNavigatorCategoryAxisItemMinorTicks; - plotBands?: StockChartNavigatorCategoryAxisItemPlotBand[]; + minorGridLines?: StockChartNavigatorCategoryAxisMinorGridLines; + minorTicks?: StockChartNavigatorCategoryAxisMinorTicks; + plotBands?: StockChartNavigatorCategoryAxisPlotBand[]; reverse?: boolean; roundToBaseUnit?: boolean; - title?: StockChartNavigatorCategoryAxisItemTitle; + title?: StockChartNavigatorCategoryAxisTitle; visible?: boolean; weekStartDay?: number; - notes?: StockChartNavigatorCategoryAxisItemNotes; + notes?: StockChartNavigatorCategoryAxisNotes; } interface StockChartNavigatorHint { @@ -14781,7 +14933,7 @@ declare namespace kendo.dataviz.ui { } interface StockChartNavigator { - categoryAxis?: StockChartNavigatorCategoryAxisItem[]; + categoryAxis?: StockChartNavigatorCategoryAxis; dataSource?: any; autoBind?: boolean; dateField?: string; @@ -16959,6 +17111,27 @@ declare namespace kendo { } + namespace date { + function setDayOfWeek(targetDate: Date, dayOfWeek: number, direction: number): void; + function dayOfWeek(targetDate: Date, dayOfWeek: number, direction: number): Date; + function weekInYear(date: Date, weekStart?: Date): number; + function getDate(date: Date): Date; + function isInDateRange(targetDate: Date, lowerLimitDate: Date, upperLimitDate: Date): boolean; + function isInTimeRange(targetDate: Date, lowerLimitDate: Date, upperLimitDate: Date): boolean; + function isToday(targetDate: Date): boolean; + function nextDay(targetDate: Date): Date; + function previousDay(targetDate: Date): Date; + function toUtcTime(targetDate: Date): number; + function setTime(targetDate: Date, millisecondsToAdd: number, ignoreDST: boolean): void; + function setHours(targetDate: Date, sourceDate: number): Date; + function addDays(targetDate: Date, numberOfDaysToAdd: number): Date; + function today(): Date; + function toInvariantTime(targetDate: Date): Date; + function firstDayOfMonth(targetDate: Date): Date; + function lastDayOfMonth(targetDate: Date): Date; + function getMilliseconds(targetDate: Date): Date; + } + namespace drawing { function align(elements: any, rect: kendo.geometry.Rect, alignment: string): void; function drawDOM(element: JQuery, options: any): JQueryPromise; @@ -17022,6 +17195,22 @@ declare namespace kendo { function defineFont(map: any): void; } + namespace timezone { + function offset(utcTime: Date, timezone: string): number; + function offset(utcTime: number, timezone: string): number; + function convert(targetDate: Date, fromOffset: number, toOffset: number): Date; + function convert(targetDate: Date, fromOffset: number, toOffset: string): Date; + function convert(targetDate: Date, fromOffset: string, toOffset: number): Date; + function convert(targetDate: Date, fromOffset: string, toOffset: string): Date; + function apply(targetDate: Date, offset: number): Date; + function apply(targetDate: Date, offset: string): Date; + function remove(targetDate: Date, offset: number): Date; + function remove(targetDate: Date, offset: string): Date; + function abbr(targetDate: Date, timezone: string): string; + function toLocalDate(targetDate: Date): Date; + function toLocalDate(targetDate: number): Date; + } + } declare namespace kendo.spreadsheet { class CustomFilter extends Observable { @@ -18306,7 +18495,7 @@ declare namespace kendo.ooxml { interface WorkbookSheetRow { cells?: WorkbookSheetRowCell[]; index?: number; - height?: number; + height?: number; type?: "header" | "footer" | "group-header" | "group-footer" | "data"; } @@ -18337,6 +18526,268 @@ declare namespace kendo.ooxml { } +declare namespace kendo.dataviz.geometry { + class Arc extends Observable { + + + options: ArcOptions; + + anticlockwise: boolean; + center: kendo.geometry.Point; + endAngle: number; + radiusX: number; + radiusY: number; + startAngle: number; + + constructor(center: any|kendo.geometry.Point, options?: ArcOptions); + + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + getAnticlockwise(): boolean; + getCenter(): kendo.geometry.Point; + getEndAngle(): number; + getRadiusX(): number; + getRadiusY(): number; + getStartAngle(): number; + pointAt(angle: number): kendo.geometry.Point; + setAnticlockwise(value: boolean): kendo.geometry.Arc; + setCenter(value: kendo.geometry.Point): kendo.geometry.Arc; + setEndAngle(value: number): kendo.geometry.Arc; + setRadiusX(value: number): kendo.geometry.Arc; + setRadiusY(value: number): kendo.geometry.Arc; + setStartAngle(value: number): kendo.geometry.Arc; + + } + + interface ArcOptions { + name?: string; + } + interface ArcEvent { + sender: Arc; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Circle extends Observable { + + + options: CircleOptions; + + center: kendo.geometry.Point; + radius: number; + + constructor(center: any|kendo.geometry.Point, radius: number); + + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + clone(): kendo.geometry.Circle; + equals(other: kendo.geometry.Circle): boolean; + getCenter(): kendo.geometry.Point; + getRadius(): number; + pointAt(angle: number): kendo.geometry.Point; + setCenter(value: kendo.geometry.Point): kendo.geometry.Point; + setCenter(value: any): kendo.geometry.Point; + setRadius(value: number): kendo.geometry.Circle; + + } + + interface CircleOptions { + name?: string; + } + interface CircleEvent { + sender: Circle; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Matrix extends Observable { + + + options: MatrixOptions; + + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + + + static rotate(angle: number, x: number, y: number): kendo.geometry.Matrix; + static scale(scaleX: number, scaleY: number): kendo.geometry.Matrix; + static translate(x: number, y: number): kendo.geometry.Matrix; + static unit(): kendo.geometry.Matrix; + + clone(): kendo.geometry.Matrix; + equals(other: kendo.geometry.Matrix): boolean; + round(digits: number): kendo.geometry.Matrix; + multiplyCopy(matrix: kendo.geometry.Matrix): kendo.geometry.Matrix; + toArray(digits: number): any; + toString(digits: number, separator: string): string; + + } + + interface MatrixOptions { + name?: string; + } + interface MatrixEvent { + sender: Matrix; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Point extends Observable { + + + options: PointOptions; + + x: number; + y: number; + + constructor(x: number, y: number); + + static create(x: number, y: number): kendo.geometry.Point; + static create(x: any, y: number): kendo.geometry.Point; + static create(x: kendo.geometry.Point, y: number): kendo.geometry.Point; + static min(): kendo.geometry.Point; + static max(): kendo.geometry.Point; + static minPoint(): kendo.geometry.Point; + static maxPoint(): kendo.geometry.Point; + + clone(): kendo.geometry.Point; + distanceTo(point: kendo.geometry.Point): number; + equals(other: kendo.geometry.Point): boolean; + getX(): number; + getY(): number; + move(x: number, y: number): kendo.geometry.Point; + rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Point; + rotate(angle: number, center: any): kendo.geometry.Point; + round(digits: number): kendo.geometry.Point; + scale(scaleX: number, scaleY: number): kendo.geometry.Point; + scaleCopy(scaleX: number, scaleY: number): kendo.geometry.Point; + setX(value: number): kendo.geometry.Point; + setY(value: number): kendo.geometry.Point; + toArray(digits: number): any; + toString(digits: number, separator: string): string; + transform(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; + transformCopy(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; + translate(dx: number, dy: number): kendo.geometry.Point; + translateWith(vector: kendo.geometry.Point): kendo.geometry.Point; + translateWith(vector: any): kendo.geometry.Point; + + } + + interface PointOptions { + name?: string; + } + interface PointEvent { + sender: Point; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Rect extends Observable { + + + options: RectOptions; + + origin: kendo.geometry.Point; + size: kendo.geometry.Size; + + 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; + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + bottomLeft(): kendo.geometry.Point; + bottomRight(): kendo.geometry.Point; + center(): kendo.geometry.Point; + clone(): kendo.geometry.Rect; + equals(other: kendo.geometry.Rect): boolean; + getOrigin(): kendo.geometry.Point; + getSize(): kendo.geometry.Size; + height(): number; + setOrigin(value: kendo.geometry.Point): kendo.geometry.Rect; + setOrigin(value: any): kendo.geometry.Rect; + setSize(value: kendo.geometry.Size): kendo.geometry.Rect; + setSize(value: any): kendo.geometry.Rect; + topLeft(): kendo.geometry.Point; + topRight(): kendo.geometry.Point; + width(): number; + + } + + interface RectOptions { + name?: string; + } + interface RectEvent { + sender: Rect; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Size extends Observable { + + + options: SizeOptions; + + width: number; + height: number; + + + static create(width: number, height: number): kendo.geometry.Size; + static create(width: any, height: number): kendo.geometry.Size; + static create(width: kendo.geometry.Size, height: number): kendo.geometry.Size; + + clone(): kendo.geometry.Size; + equals(other: kendo.geometry.Size): boolean; + getWidth(): number; + getHeight(): number; + setWidth(value: number): kendo.geometry.Size; + setHeight(value: number): kendo.geometry.Size; + + } + + interface SizeOptions { + name?: string; + } + + class Transformation extends Observable { + + + options: TransformationOptions; + + + + + clone(): kendo.geometry.Transformation; + equals(other: kendo.geometry.Transformation): boolean; + matrix(): kendo.geometry.Matrix; + multiply(transformation: kendo.geometry.Transformation): kendo.geometry.Transformation; + rotate(angle: number, center: any): kendo.geometry.Transformation; + rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Transformation; + scale(scaleX: number, scaleY: number): kendo.geometry.Transformation; + translate(x: number, y: number): kendo.geometry.Transformation; + + } + + interface TransformationOptions { + name?: string; + } + interface TransformationEvent { + sender: Transformation; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + +} declare namespace kendo.dataviz.drawing { class Arc extends kendo.drawing.Element { @@ -19126,274 +19577,6 @@ declare namespace kendo.dataviz.drawing { -} -declare namespace kendo.dataviz.geometry { - class Arc extends Observable { - - - options: ArcOptions; - - anticlockwise: boolean; - center: kendo.geometry.Point; - endAngle: number; - radiusX: number; - radiusY: number; - startAngle: number; - - constructor(center: any|kendo.geometry.Point, options?: ArcOptions); - - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - getAnticlockwise(): boolean; - getCenter(): kendo.geometry.Point; - getEndAngle(): number; - getRadiusX(): number; - getRadiusY(): number; - getStartAngle(): number; - pointAt(angle: number): kendo.geometry.Point; - setAnticlockwise(value: boolean): kendo.geometry.Arc; - setCenter(value: kendo.geometry.Point): kendo.geometry.Arc; - setEndAngle(value: number): kendo.geometry.Arc; - setRadiusX(value: number): kendo.geometry.Arc; - setRadiusY(value: number): kendo.geometry.Arc; - setStartAngle(value: number): kendo.geometry.Arc; - - } - - interface ArcOptions { - name?: string; - } - interface ArcEvent { - sender: Arc; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Circle extends Observable { - - - options: CircleOptions; - - center: kendo.geometry.Point; - radius: number; - - constructor(center: any|kendo.geometry.Point, radius: number); - - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - clone(): kendo.geometry.Circle; - equals(other: kendo.geometry.Circle): boolean; - getCenter(): kendo.geometry.Point; - getRadius(): number; - pointAt(angle: number): kendo.geometry.Point; - setCenter(value: kendo.geometry.Point): kendo.geometry.Point; - setCenter(value: any): kendo.geometry.Point; - setRadius(value: number): kendo.geometry.Circle; - - } - - interface CircleOptions { - name?: string; - } - interface CircleEvent { - sender: Circle; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Matrix extends Observable { - - - options: MatrixOptions; - - a: number; - b: number; - c: number; - d: number; - e: number; - f: number; - - - static rotate(angle: number, x: number, y: number): kendo.geometry.Matrix; - static scale(scaleX: number, scaleY: number): kendo.geometry.Matrix; - static translate(x: number, y: number): kendo.geometry.Matrix; - static unit(): kendo.geometry.Matrix; - - clone(): kendo.geometry.Matrix; - equals(other: kendo.geometry.Matrix): boolean; - round(digits: number): kendo.geometry.Matrix; - multiplyCopy(matrix: kendo.geometry.Matrix): kendo.geometry.Matrix; - toArray(digits: number): any; - toString(digits?: number, separator?: string): string; - - } - - interface MatrixOptions { - name?: string; - } - interface MatrixEvent { - sender: Matrix; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Point extends Observable { - - - options: PointOptions; - - x: number; - y: number; - - constructor(x: number, y: number); - - static create(x: number, y: number): kendo.geometry.Point; - static create(x: any, y: number): kendo.geometry.Point; - static create(x: kendo.geometry.Point, y: number): kendo.geometry.Point; - static min(): kendo.geometry.Point; - static max(): kendo.geometry.Point; - static minPoint(): kendo.geometry.Point; - static maxPoint(): kendo.geometry.Point; - - clone(): kendo.geometry.Point; - distanceTo(point: kendo.geometry.Point): number; - equals(other: kendo.geometry.Point): boolean; - getX(): number; - getY(): number; - move(x: number, y: number): kendo.geometry.Point; - rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Point; - rotate(angle: number, center: any): kendo.geometry.Point; - round(digits: number): kendo.geometry.Point; - scale(scaleX: number, scaleY: number): kendo.geometry.Point; - scaleCopy(scaleX: number, scaleY: number): kendo.geometry.Point; - setX(value: number): kendo.geometry.Point; - setY(value: number): kendo.geometry.Point; - toArray(digits: number): any; - toString(digits: number, separator: string): string; - transform(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; - transformCopy(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; - translate(dx: number, dy: number): kendo.geometry.Point; - translateWith(vector: kendo.geometry.Point): kendo.geometry.Point; - translateWith(vector: any): kendo.geometry.Point; - - } - - interface PointOptions { - name?: string; - } - interface PointEvent { - sender: Point; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Rect extends Observable { - - - options: RectOptions; - - origin: kendo.geometry.Point; - size: kendo.geometry.Size; - - 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; - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - bottomLeft(): kendo.geometry.Point; - bottomRight(): kendo.geometry.Point; - center(): kendo.geometry.Point; - clone(): kendo.geometry.Rect; - equals(other: kendo.geometry.Rect): boolean; - getOrigin(): kendo.geometry.Point; - getSize(): kendo.geometry.Size; - height(): number; - setOrigin(value: kendo.geometry.Point): kendo.geometry.Rect; - setOrigin(value: any): kendo.geometry.Rect; - setSize(value: kendo.geometry.Size): kendo.geometry.Rect; - setSize(value: any): kendo.geometry.Rect; - topLeft(): kendo.geometry.Point; - topRight(): kendo.geometry.Point; - width(): number; - - } - - interface RectOptions { - name?: string; - } - interface RectEvent { - sender: Rect; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Size extends Observable { - - - options: SizeOptions; - - width: number; - height: number; - - - static create(width: number, height: number): kendo.geometry.Size; - static create(width: any, height: number): kendo.geometry.Size; - static create(width: kendo.geometry.Size, height: number): kendo.geometry.Size; - - clone(): kendo.geometry.Size; - equals(other: kendo.geometry.Size): boolean; - getWidth(): number; - getHeight(): number; - setWidth(value: number): kendo.geometry.Size; - setHeight(value: number): kendo.geometry.Size; - - } - - interface SizeOptions { - name?: string; - } - interface SizeEvent { - sender: Size; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Transformation extends Observable { - - - options: TransformationOptions; - - - - - clone(): kendo.geometry.Transformation; - equals(other: kendo.geometry.Transformation): boolean; - matrix(): kendo.geometry.Matrix; - multiply(transformation: kendo.geometry.Transformation): kendo.geometry.Transformation; - rotate(angle: number, center: any): kendo.geometry.Transformation; - rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Transformation; - scale(scaleX: number, scaleY: number): kendo.geometry.Transformation; - translate(x: number, y: number): kendo.geometry.Transformation; - - } - - interface TransformationOptions { - name?: string; - } - interface TransformationEvent { - sender: Transformation; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - } interface HTMLElement { diff --git a/keycloak-js/keycloak-js-tests.ts b/keycloak-js/keycloak-js-tests.ts index dc97d8da18..f0c78392b7 100644 --- a/keycloak-js/keycloak-js-tests.ts +++ b/keycloak-js/keycloak-js-tests.ts @@ -14,5 +14,5 @@ import { import * as KeycloakAuthorization from 'keycloak-js/keycloak-authz'; import { KeycloakAuthorizationPromise } from 'keycloak-js/keycloak-authz'; -let keycloak = Keycloak(); -let keycloakAuthz = KeycloakAuthorization(keycloak); +const keycloak = Keycloak(); +const keycloakAuthz = KeycloakAuthorization(keycloak); diff --git a/keygrip/keygrip-tests.ts b/keygrip/keygrip-tests.ts index afa66e04b1..d8447867b5 100644 --- a/keygrip/keygrip-tests.ts +++ b/keygrip/keygrip-tests.ts @@ -1,4 +1,4 @@ import * as Keygrip from 'keygrip'; -let keys = Keygrip(['123']); -let hash = keys.sign('abc'); +const keys = Keygrip(['123']); +const hash = keys.sign('abc'); diff --git a/koa-basic-auth/tslint.json b/koa-basic-auth/tslint.json index ec365f164b..377cc837d4 100644 --- a/koa-basic-auth/tslint.json +++ b/koa-basic-auth/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/koa-hbs/index.d.ts b/koa-hbs/index.d.ts index 8adfeaf20f..f38d2e9fdd 100644 --- a/koa-hbs/index.d.ts +++ b/koa-hbs/index.d.ts @@ -1,22 +1,21 @@ -// Type definitions for koa-favicon v2.x +// Type definitions for koa-hbs v1.x // Project: https://github.com/gilt/koa-hbs -// Definitions by: Jacob Malone +// Definitions by: Jacob Malone , Mudkip // Definitions: https://github.com/jcbmln/DefinitelyTyped /* =================== USAGE =================== - import * as Hbs from "koa-hbs"; import * as Koa from "koa"; +....import hbs = require("koa-hbs"); - var hbs = new Hbs(); var app = new Koa(); app.use(hbs.middleware({ viewPath: __dirname + '/views' })); - app.use(function *() { - yield this.render('main', { + app.use(async (ctx, next) => { + await ctx.render('main', { title: 'koa-hbs' }); }); @@ -25,31 +24,33 @@ /// -declare module "koa-hbs" { +import * as Koa from "koa"; - import * as Koa from "koa"; - - namespace Hbs { - export interface Middleware { - viewPath: Array | string, - handlebars?: Function, - templateOptions?: {}, - extname?: string, - partialsPath?: Array | string, - defaultLayout?: string, - layoutsPath?: string, - contentHelperName?: string, - blockHelperName?: string, - disableCache?: boolean - } +declare namespace Hbs { + export interface Middleware { + viewPath: Array | string, + handlebars?: Function, + templateOptions?: {}, + extname?: string, + partialsPath?: Array | string, + defaultLayout?: string, + layoutsPath?: string, + contentHelperName?: string, + blockHelperName?: string, + disableCache?: boolean } - - class Hbs { - constructor(); - - middleware(opts: Hbs.Middleware): any; - } - - namespace Hbs {} - export = Hbs; } + +declare class Hbs { + constructor(); + middleware(opts: Hbs.Middleware): any; +} + +declare const hbs: Hbs; +export = hbs; + +declare module "koa" { + export interface Context { + render(tpl: string, locals?: {[key: string]: any}): Promise; + } +} \ No newline at end of file diff --git a/koa-hbs/koa-hbs-tests.ts b/koa-hbs/koa-hbs-tests.ts index 647eee7f22..3c86a51cad 100644 --- a/koa-hbs/koa-hbs-tests.ts +++ b/koa-hbs/koa-hbs-tests.ts @@ -1,16 +1,15 @@ -import * as Hbs from 'koa-hbs'; import * as Koa from 'koa'; +import hbs = require("koa-hbs"); import * as Path from 'path'; const app = new Koa(); -const hbs = new Hbs(); app.use(hbs.middleware({ viewPath: Path.join(__dirname, './views') })); -app.use(function *(next: any) { - yield this.render('index', { +app.use(async (ctx, next) => { + await ctx.render('index', { title: 'Hello World!' }); }); diff --git a/koa-json-error/index.d.ts b/koa-json-error/index.d.ts index 9f02cce994..dfe23c26b0 100644 --- a/koa-json-error/index.d.ts +++ b/koa-json-error/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for koa-json-error v3.x +// Type definitions for koa-json-error 3.1 // Project: https://github.com/koajs/json-error // Definitions by: Mudkip // Definitions: https://github.com/mudkipme/DefinitelyTyped +// TypeScript Version: 2.1 import * as Koa from "koa"; @@ -9,23 +10,23 @@ interface JSONErrorOptions { /** * Perform some task before calling `options.format`. Must be a function with the original err as its only argument. */ - preFormat?: { (err: Error): any }; + preFormat?: (err: Error) => any; /** * Runs inmediatly after `options.preFormat`. It receives two arguments: the original `err` and the output of `options.preFormat`. It should `return` a newly formatted error. */ - format?: { (err: Error, obj: any): any }; + format?: (err: Error, obj: any) => any; /** * Runs inmediatly after `options.format`. It receives two arguments: the original `err` and the output of `options.format`. It should `return` a newly formatted error. */ - postFormat?: { (err: Error, obj: any): any }; + postFormat?: (err: Error, obj: any) => any; } /** * Error handler for pure Koa 2.0.0+ JSON apps */ -declare function jsonError(options?: JSONErrorOptions) : Koa.Middleware; +declare function jsonError(options?: JSONErrorOptions): Koa.Middleware; declare namespace jsonError {} export = jsonError; diff --git a/koa-json-error/koa-json-error-tests.ts b/koa-json-error/koa-json-error-tests.ts index 07ac0fd129..77a13a1f64 100644 --- a/koa-json-error/koa-json-error-tests.ts +++ b/koa-json-error/koa-json-error-tests.ts @@ -1,9 +1,8 @@ import * as Koa from "koa"; import * as error from "koa-json-error"; -import { assign } from "lodash"; const app = new Koa(); app.use(error({ - preFormat: err => assign({}, err) + preFormat: err => Object.assign({}, err) })); \ No newline at end of file diff --git a/koa-json-error/tslint.json b/koa-json-error/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/koa-json-error/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/koa-jwt/tslint.json b/koa-jwt/tslint.json index f9e30021f4..377cc837d4 100644 --- a/koa-jwt/tslint.json +++ b/koa-jwt/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/koa-passport/index.d.ts b/koa-passport/index.d.ts index 2bdf4bcfac..e3a318004a 100644 --- a/koa-passport/index.d.ts +++ b/koa-passport/index.d.ts @@ -13,7 +13,7 @@ import * as Koa from "koa"; declare module "koa" { - interface Request { + interface Context { authInfo?: any; user?: any; diff --git a/koa-session-minimal/index.d.ts b/koa-session-minimal/index.d.ts index 3fe9da3a52..02d3a68004 100644 --- a/koa-session-minimal/index.d.ts +++ b/koa-session-minimal/index.d.ts @@ -17,7 +17,7 @@ import * as Koa from "koa"; import * as cookies from "cookies"; declare module "koa" { - interface Request { + interface Context { session: any; sessionHandler: { regenerateId: () => void }; } diff --git a/koa/index.d.ts b/koa/index.d.ts index 09b2a64426..99e2c04498 100644 --- a/koa/index.d.ts +++ b/koa/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Koa 2.x // Project: http://koajs.com -// Definitions by: DavidCai1993 +// Definitions by: DavidCai1993 , jKey Lu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* =================== USAGE =================== @@ -14,172 +14,645 @@ =============================================== */ /// -import { EventEmitter } from "events"; -import * as cookies from "cookies"; -import * as http from "http"; -import * as net from "net"; +import { EventEmitter } from 'events'; +import { IncomingMessage, ServerResponse, Server } from 'http'; +import { Socket, ListenOptions } from 'net'; +import * as compose from 'koa-compose'; +import * as Keygrip from 'keygrip'; +import * as httpAssert from 'http-assert'; +import * as Cookies from 'cookies'; +import * as accepts from 'accepts'; + +declare interface ContextDelegatedRequest { + /** + * Return request header. + */ + header: any; + /** + * Return request header, alias as request.header + */ + headers: any; + + /** + * Get/Set request URL. + */ + url: string; + + /** + * Get origin of URL. + */ + origin: string; + + /** + * Get full request URL. + */ + href: string; + + /** + * Get/Set request method. + */ + method: string; + + /** + * Get request pathname. + * Set pathname, retaining the query-string when present. + */ + path: string; + + /** + * Get parsed query-string. + * Set query-string as an object. + */ + query: any; + + /** + * Get/Set query string. + */ + querystring: string; + + /** + * Get the search string. Same as the querystring + * except it includes the leading ?. + * + * Set the search string. Same as + * response.querystring= but included for ubiquity. + */ + search: string; -export = Koa; + /** + * Parse the "Host" header field host + * and support X-Forwarded-Host when a + * proxy is enabled. + */ + host: string; -declare namespace Koa { - export interface Context extends Request, Response { - app: Koa; - req: http.IncomingMessage; - res: http.ServerResponse; - request: Request; - response: Response; + /** + * Parse the "Host" header field hostname + * and support X-Forwarded-Host when a + * proxy is enabled. + */ + hostname: string; - cookies: cookies.ICookies; - originalUrl: string; - state: any; + /** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + */ + fresh: boolean; - name?: string; - respond?: boolean; + /** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + */ + stale: boolean; - assert(test: any, ...args: any[]): void; - onerror(err?: any): void; - throw(...args: any[]): void; + /** + * Check if the request is idempotent. + */ + idempotent: boolean; - toJSON(): any; - inspect(): any; + /** + * Return the request socket. + */ + socket: Socket; - [key: string]: any; - } + /** + * Return the protocol string "http" or "https" + * when requested with TLS. When the proxy setting + * is enabled the "X-Forwarded-Proto" header + * field will be trusted. If you're running behind + * a reverse proxy that supplies https for you this + * may be enabled. + */ + protocol: string; - export interface Request { - app: Koa; - req: http.IncomingMessage; - res: http.ServerResponse; - ctx: Context; - response: Response; + /** + * Short-hand for: + * + * this.protocol == 'https' + */ + secure: boolean; - fresh: boolean; - header: any; - headers: any; - host: string; - hostname: string; - href: string; - idempotent: boolean; - ip: string; - ips: string[]; - method: string; - origin: string; - originalUrl: string; - path: string; - protocol: string; - query: any; - querystring: string; - search: string; - secure: boolean; - socket: net.Socket; - stale: boolean; - subdomains: string[]; - type: string; - url: string; + /** + * When `app.proxy` is `true`, parse + * the "X-Forwarded-For" ip address list. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream. + */ + ips: string[]; - charset?: string; - length?: number; + /** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain + * of the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting `app.subdomainOffset`. + * + * For example, if the domain is "tobi.ferrets.example.com": + * If `app.subdomainOffset` is not set, this.subdomains is + * `["ferrets", "tobi"]`. + * If `app.subdomainOffset` is 3, this.subdomains is `["tobi"]`. + */ + subdomains: string[]; - accepts(): string[]; - accepts(arg: string): void | string; - accepts(arg: string[]): void | string; - accepts(...args: string[]): void | string; - acceptsCharsets(): string[]; - acceptsCharsets(arg: string): void | string; - acceptsCharsets(arg: string[]): void | string; - acceptsCharsets(...args: string[]): void | string; - acceptsEncodings(): string[]; - acceptsEncodings(arg: string): void | string; - acceptsEncodings(arg: string[]): void | string; - acceptsEncodings(...args: string[]): void | string; - acceptsLanguages(): string[]; - acceptsLanguages(arg: string): void | string; - acceptsLanguages(arg: string[]): void | string; - acceptsLanguages(...args: string[]): void | string; - get(field: string): string; - is(): string[]; - is(arg: string): void | string; - is(arg: string[]): void | string; - is(...args: string[]): void | string; + /** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.accepts('html'); + * // => "html" + * this.accepts('text/html'); + * // => "text/html" + * this.accepts('json', 'text'); + * // => "json" + * this.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.accepts('image/png'); + * this.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.accepts(['html', 'json']); + * this.accepts('html', 'json'); + * // => "json" + */ + accepts(): string[] | boolean; + accepts(...types: string[]): string | boolean; + accepts(types: string[]): string | boolean; - toJSON(): any; - inspect(): any; - } + /** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + */ + acceptsEncodings(): string[] | boolean; + acceptsEncodings(...encodings: string[]): string | boolean; + acceptsEncodings(encodings: string[]): string | boolean; - export interface Response { - app: Koa; - req: http.IncomingMessage; - res: http.ServerResponse; - ctx: Context; - request: Request; + /** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + */ + acceptsCharsets(): string[] | boolean; + acceptsCharsets(...charsets: string[]): string | boolean; + acceptsCharsets(charsets: string[]): string | boolean; - body: any; - etag: string; - header: any; - headers: any; - headerSent: boolean; - lastModified: Date; - message: string; - socket: net.Socket; - status: number; - type: string; - writable: boolean; + /** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + */ + acceptsLanguages(): string[] | boolean; + acceptsLanguages(...langs: string[]): string | boolean; + acceptsLanguages(langs: string[]): string | boolean; - charset?: string; - length?: number; + /** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + */ + // is(): string | boolean; + is(...types: string[]): string | boolean; + is(types: string[]): string | boolean; - append(field: string, val: string | string[]): void; - attachment(filename?: string): void; - get(field: string): string; - is(): string[]; - is(arg: string): void | string; - is(arg: string[]): void | string; - is(...args: string[]): void | string; - redirect(url: string, alt?: string): void; - remove(field: string): void; - set(field: string, val: string | string[]): void; - set(field: any): void; - vary(field: string): void; - - toJSON(): any; - inspect(): any; - } - - export type Middleware = (ctx: Koa.Context, next: () => Promise) => any; + /** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * this.get('Content-Type'); + * // => "text/plain" + * + * this.get('content-type'); + * // => "text/plain" + * + * this.get('Something'); + * // => undefined + */ + get(field: string): string; } -declare class Koa extends EventEmitter { - subdomainOffset: number; - server: http.Server; - env: string; - context: Koa.Context; - keys: string[]; +declare interface BaseRequest extends ContextDelegatedRequest { + /** + * Get the charset when present or undefined. + */ + charset: string; + + /** + * Return parsed Content-Length when present. + */ + length: number; + + /** + * Return the request mime type void of + * parameters such as "charset". + */ + type: string; + + /** + * Inspect implementation. + */ + inspect(): any; + + /** + * Return JSON representation. + */ + toJSON(): any; +} + +declare interface ContextDelegatedResponse { + /** + * Get/Set response status code. + */ + status: number; + + /** + * Get response status message + */ + message: string; + + /** + * Get/Set response body. + */ + body: any; + + /** + * Return parsed response Content-Length when present. + * Set Content-Length field to `n`. + */ + length: number; + + /** + * Check if a header has been written to the socket. + */ + headerSent: boolean; + + /** + * Vary on `field`. + */ + vary(field: string): void; + + /** + * Perform a 302 redirect to `url`. + * + * The string "back" is special-cased + * to provide Referrer support, when Referrer + * is not present `alt` or "/" is used. + * + * Examples: + * + * this.redirect('back'); + * this.redirect('back', '/index.html'); + * this.redirect('/login'); + * this.redirect('http://google.com'); + */ + redirect(url: string, alt?: string): void; + + /** + * Set Content-Disposition header to "attachment" with optional `filename`. + */ + attachment(filename: string): void; + + /** + * Return the response mime type void of + * parameters such as "charset". + * + * Set Content-Type response header with `type` through `mime.lookup()` + * when it does not contain a charset. + * + * Examples: + * + * this.type = '.html'; + * this.type = 'html'; + * this.type = 'json'; + * this.type = 'application/json'; + * this.type = 'png'; + */ + type: string; + + /** + * Get the Last-Modified date in Date form, if it exists. + * Set the Last-Modified date using a string or a Date. + * + * this.response.lastModified = new Date(); + * this.response.lastModified = '2013-09-13'; + */ + lastModified: Date; + + /** + * Get/Set the ETag of a response. + * This will normalize the quotes if necessary. + * + * this.response.etag = 'md5hashsum'; + * this.response.etag = '"md5hashsum"'; + * this.response.etag = 'W/"123456789"'; + * + * @param {String} etag + * @api public + */ + etag: string; + + /** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * this.set('Foo', ['bar', 'baz']); + * this.set('Accept', 'application/json'); + * this.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + */ + set(field: { [key: string]: string; }): void; + set(field: string, val: string | string[]): void; + + /** + * Append additional header `field` with value `val`. + * + * Examples: + * + * ``` + * this.append('Link', ['', '']); + * this.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); + * this.append('Warning', '199 Miscellaneous warning'); + * ``` + */ + append(field: string, val: string | string[]): void; + + /** + * Remove header `field`. + */ + remove(field: string): void; + + /** + * Checks if the request is writable. + * Tests for the existence of the socket + * as node sometimes does not set it. + */ + writable: boolean; + + /** + * Flush any set headers, and begin the body + */ + flushHeaders(): void; +} + +declare interface BaseResponse extends ContextDelegatedResponse { + /** + * Return the request socket. + * + * @return {Connection} + * @api public + */ + socket: Socket; + + /** + * Return response header. + */ + header: any; + + /** + * Return response header, alias as response.header + */ + headers: any; + + /** + * Check whether the response is one of the listed types. + * Pretty much the same as `this.request.is()`. + * + * @param {String|Array} types... + * @return {String|false} + * @api public + */ + // is(): string; + is(...types: string[]): string; + is(types: string[]): string; + + /** + * Return response header. + * + * Examples: + * + * this.get('Content-Type'); + * // => "text/plain" + * + * this.get('content-type'); + * // => "text/plain" + */ + get(field: string): string; + + /** + * Inspect implementation. + */ + inspect(): any; + + /** + * Return JSON representation. + */ + toJSON(): any; +} + + +declare interface BaseContext extends ContextDelegatedRequest, ContextDelegatedResponse { + /** + * util.inspect() implementation, which + * just returns the JSON output. + */ + inspect(): any; + + /** + * Return JSON representation. + * + * Here we explicitly invoke .toJSON() on each + * object, as iteration will otherwise fail due + * to the getters and cause utilities such as + * clone() to fail. + */ + toJSON(): any; + + /** + * Similar to .throw(), adds assertion. + * + * this.assert(this.user, 401, 'Please login!'); + * + * See: https://github.com/jshttp/http-assert + */ + assert: typeof httpAssert; + + /** + * Throw an error with `msg` and optional `status` + * defaulting to 500. Note that these are user-level + * errors, and the message may be exposed to the client. + * + * this.throw(403) + * this.throw('name required', 400) + * this.throw(400, 'name required') + * this.throw('something exploded') + * this.throw(new Error('invalid'), 400); + * this.throw(400, new Error('invalid')); + * + * See: https://github.com/jshttp/http-errors + */ + throw(message: string, code?: number, properties?: {}): never; + throw(status: number): never; + throw(...properties: Array): never; + + /** + * Default error handling. + */ + onerror(err: Error): void; +} + +declare class Application extends EventEmitter { proxy: boolean; - request: Koa.Request; - response: Koa.Response; + middleware: Application.Middleware[]; + subdomainOffset: number; + env: string; + context: BaseContext; + request: BaseRequest; + response: BaseResponse; silent: boolean; + keys: Keygrip | string[]; constructor(); - // From node.d.ts - listen(): http.Server; - listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): http.Server; - listen(port: number, hostname?: string, listeningListener?: Function): http.Server; - listen(port: number, backlog?: number, listeningListener?: Function): http.Server; - listen(port: number, listeningListener?: Function): http.Server; - listen(path: string, backlog?: number, listeningListener?: Function): http.Server; - listen(path: string, listeningListener?: Function): http.Server; - listen(handle: any, backlog?: number, listeningListener?: Function): http.Server; - listen(handle: any, listeningListener?: Function): http.Server; - listen(options: net.ListenOptions, listeningListener?: Function): http.Server; + /** + * Shorthand for: + * + * http.createServer(app.callback()).listen(...) + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): Server; + listen(port: number, hostname?: string, listeningListener?: () => void): Server; + /* tslint:disable:unified-signatures */ + listen(port: number, backlog?: number, listeningListener?: () => void): Server; + listen(port: number, listeningListener?: () => void): Server; + listen(path: string, backlog?: number, listeningListener?: () => void): Server; + listen(path: string, listeningListener?: () => void): Server; + listen(options: ListenOptions, listeningListener?: () => void): Server; + listen(handle: any, backlog?: number, listeningListener?: () => void): Server; + listen(handle: any, listeningListener?: () => void): Server; + /* tslint:enable:unified-signatures*/ - callback(): (req: http.IncomingMessage, res: http.ServerResponse) => void; - onerror(err: any): void; - use(middleware: Koa.Middleware): Koa; - - toJSON(): any; + /** + * Return JSON representation. + * We only bother showing settings. + */ inspect(): any; - onerror(err: any): void; + + /** + * Return JSON representation. + * We only bother showing settings. + */ + toJSON(): any; + + /** + * Use the given middleware `fn`. + * + * Old-style middleware will be converted. + */ + use(middleware: Application.Middleware): this; + + /** + * Return a request handler callback + * for node's native http server. + */ + callback(): (req: IncomingMessage, res: ServerResponse) => void; + + /** + * Initialize a new context. + * + * @api private + */ + createContext(req: IncomingMessage, res: ServerResponse): Application.Context; + + /** + * Default error handler. + * + * @api private + */ + onerror(err: Error): void; } +declare namespace Application { + type Middleware = compose.Middleware; + + interface Request extends BaseRequest { + app: Application; + req: IncomingMessage; + res: ServerResponse; + ctx: Context; + response: Response; + originalUrl: string; + ip: string; + accept: accepts.Accepts; + } + + interface Response extends BaseResponse { + app: Application; + req: IncomingMessage; + res: ServerResponse; + ctx: Context; + request: Request; + } + + interface Context extends BaseContext { + app: Application; + request: Request; + response: Response; + req: IncomingMessage; + res: ServerResponse; + originalUrl: string; + cookies: Cookies; + accept: accepts.Accepts; + state: any; + } +} + +export = Application; diff --git a/later/index.d.ts b/later/index.d.ts index c5c2449a00..5dd68ec90a 100644 --- a/later/index.d.ts +++ b/later/index.d.ts @@ -142,7 +142,7 @@ declare namespace later { * For acces to custom time periods created as extension to the later static type * and modifiers created on the later modifier static type. */ - [ timeperiodAndModifierName: string ]: number[]; + [ timeperiodAndModifierName: string ]: number[] | undefined; } interface ParseStatic { diff --git a/later/later-tests.ts b/later/later-tests.ts index 1d8c272f1b..1ecd1d6d0e 100644 --- a/later/later-tests.ts +++ b/later/later-tests.ts @@ -6,7 +6,7 @@ namespace LaterTest_DefineSchedule { var textSched = later.parse.text('at 10:15am every weekday'); var cronSched = later.parse.cron('0 0/5 14,18 * * ?'); var recurSched = later.parse.recur().last().dayOfMonth(); - var manualSched = { schedules: [ { M: [ 3 ], D: [ 21 ] } ] }; + var manualSched = { schedules: [ { M: [ 3 ], D: [ 21 ] } ] }; // this schedule will fire on the closest weekday to the 15th // every month at 2:00 am except in March @@ -406,13 +406,13 @@ namespace LaterTest_TimePeriods { // 'Mon, 31 Dec 2012 23:59:59 GMT' } - export interface IPartOfDayLater extends later.Static { + export interface PartOfDayLater extends later.Static { partOfDay: later.TimePeriod; } export function custom() { - var customLater = later; + var customLater = later; customLater.partOfDay = { @@ -420,7 +420,7 @@ namespace LaterTest_TimePeriods { range: later.hour.range * 6, - val: function(d: Date): number { + val(d: Date): number { return later.hour.val(d) < 12 ? 0 : later.hour.val(d) < 18 @@ -428,15 +428,15 @@ namespace LaterTest_TimePeriods { : 2; }, - isValid: function(d: Date, val: any) { + isValid(d: Date, val: any) { return customLater.partOfDay.val(d) === val; }, - extent: function(date?: Date) { + extent(date?: Date) { return [0, 2]; }, - start: function(date: Date) { + start(date: Date) { var hour = customLater.partOfDay.val(date) === 0 ? 0 : customLater.partOfDay.val(date) === 1 @@ -451,7 +451,7 @@ namespace LaterTest_TimePeriods { ); }, - end: function(date: Date) { + end(date: Date) { var hour = customLater.partOfDay.val(date) === 0 ? 11 : customLater.partOfDay.val(date) === 1 @@ -466,7 +466,7 @@ namespace LaterTest_TimePeriods { ); }, - next: function(date: Date, val: any) { + next(date: Date, val: any) { var hour = val === 0 ? 0 : val === 1 @@ -482,7 +482,7 @@ namespace LaterTest_TimePeriods { ); }, - prev: function(date: Date, val: any) { + prev(date: Date, val: any) { var hour = val === 0 ? 11 : val === 1 @@ -578,7 +578,7 @@ namespace LaterTest_GenerateRecurences { var sched = later.parse.recur() .every(2).hour().first().dayOfMonth() .and() - .on(8, 20).hour().last().dayOfMonth() + .on(8, 20).hour().last().dayOfMonth(); } export function except_method() { diff --git a/later/tsconfig.json b/later/tsconfig.json index 78a6cefd34..add4a07667 100644 --- a/later/tsconfig.json +++ b/later/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/later/tslint.json b/later/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/later/tslint.json +++ b/later/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/leaflet-draw/leaflet-draw-tests.ts b/leaflet-draw/leaflet-draw-tests.ts index 98d3681789..4260eac263 100644 --- a/leaflet-draw/leaflet-draw-tests.ts +++ b/leaflet-draw/leaflet-draw-tests.ts @@ -37,7 +37,7 @@ var drawControl = new L.Control.Draw({ }); map.addControl(drawControl); -map.on('draw:created', function (e: any) { +map.on('draw:created', (e: any) => { var drawEvent = (e as L.DrawEvents.Created); var type = drawEvent.layerType, layer = drawEvent.layer; diff --git a/leaflet-draw/tslint.json b/leaflet-draw/tslint.json index 9bc375c06b..105f5736e6 100644 --- a/leaflet-draw/tslint.json +++ b/leaflet-draw/tslint.json @@ -3,4 +3,4 @@ "rules": { "no-empty-interface": false } -} \ No newline at end of file +} diff --git a/leaflet-imageoverlay-rotated/tsconfig.json b/leaflet-imageoverlay-rotated/tsconfig.json index 4a9d4d5049..c6f8181b86 100644 --- a/leaflet-imageoverlay-rotated/tsconfig.json +++ b/leaflet-imageoverlay-rotated/tsconfig.json @@ -1,7 +1,10 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6", + "dom" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +20,4 @@ "index.d.ts", "leaflet-imageoverlay-rotated-tests.ts" ] -} +} \ No newline at end of file diff --git a/leaflet-label/leaflet-label-tests.ts b/leaflet-label/leaflet-label-tests.ts index bdfee67e62..eba8c5907b 100644 --- a/leaflet-label/leaflet-label-tests.ts +++ b/leaflet-label/leaflet-label-tests.ts @@ -23,7 +23,7 @@ circleMarker.showLabel(); circleMarker.hideLabel(); circleMarker.setLabelNoHide(true); circleMarker.updateLabelContent('test2'); -label = circleMarker.getLabel() +label = circleMarker.getLabel(); circleMarker = circleMarker.unbindLabel(); // Marker @@ -43,7 +43,7 @@ marker.showLabel(); marker.hideLabel(); marker.setLabelNoHide(true); marker.updateLabelContent('test2'); -label = marker.getLabel() +label = marker.getLabel(); marker = marker.unbindLabel(); marker.setOpacity(0.5); marker.setOpacity(0.5, true); diff --git a/leaflet-label/tslint.json b/leaflet-label/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/leaflet-label/tslint.json +++ b/leaflet-label/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/leaflet-markercluster/leaflet-markercluster-tests.ts b/leaflet-markercluster/leaflet-markercluster-tests.ts index 346239f836..7488a4e132 100644 --- a/leaflet-markercluster/leaflet-markercluster-tests.ts +++ b/leaflet-markercluster/leaflet-markercluster-tests.ts @@ -26,7 +26,7 @@ markerClusterGroupOptions = { }, chunkedLoading: false, chunkDelay: 100 -} +}; let markerClusterGroup: L.MarkerClusterGroup; markerClusterGroup = L.markerClusterGroup(); diff --git a/leaflet-markercluster/tslint.json b/leaflet-markercluster/tslint.json index 192203ab54..377cc837d4 100644 --- a/leaflet-markercluster/tslint.json +++ b/leaflet-markercluster/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/leaflet.gridlayer.googlemutant/tsconfig.json b/leaflet.gridlayer.googlemutant/tsconfig.json index 2e8651b58b..7001206f48 100644 --- a/leaflet.gridlayer.googlemutant/tsconfig.json +++ b/leaflet.gridlayer.googlemutant/tsconfig.json @@ -1,7 +1,10 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6", + "dom" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +20,4 @@ "index.d.ts", "leaflet.gridlayer.googlemutant-tests.ts" ] -} +} \ No newline at end of file diff --git a/leaflet.pm/tsconfig.json b/leaflet.pm/tsconfig.json index 21ac03fd2a..f106913bbd 100644 --- a/leaflet.pm/tsconfig.json +++ b/leaflet.pm/tsconfig.json @@ -1,7 +1,10 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6", + "dom" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +20,4 @@ "index.d.ts", "leaflet.pm-tests.ts" ] -} +} \ No newline at end of file diff --git a/leaflet/index.d.ts b/leaflet/index.d.ts index 5ca606811a..de463ae997 100644 --- a/leaflet/index.d.ts +++ b/leaflet/index.d.ts @@ -1405,8 +1405,8 @@ declare namespace L { */ export function map(element: string | HTMLElement, options?: MapOptions): Map; - export interface IconOptions extends LayerOptions { - iconUrl: string; + interface BaseIconOptions extends LayerOptions { + iconUrl?: string; iconRetinaUrl?: string; iconSize?: PointExpression; iconAnchor?: PointExpression; @@ -1418,25 +1418,38 @@ declare namespace L { className?: string; } - class InternalIcon extends Layer { - constructor(options: IconOptions); - createIcon(oldIcon?: HTMLElement): HTMLElement; + export interface IconOptions extends BaseIconOptions { + iconUrl: string; } - export class Icon extends InternalIcon { + // This class does not exist in reality, it's just a way to provide + // options of more specific types in the sub classes + class BaseIcon extends Layer { + createIcon(oldIcon?: HTMLElement): HTMLElement; createShadow(oldIcon?: HTMLElement): HTMLElement; + options: BaseIconOptions; + } + + export class Icon extends BaseIcon { + constructor(options: IconOptions); options: IconOptions; } export namespace Icon { - export class Default extends InternalIcon { - imagePath: string; + export interface DefaultIconOptions extends BaseIconOptions { + imagePath?: string; + } + + export class Default extends BaseIcon { + static imagePath?: string; + constructor(options?: DefaultIconOptions); + options: DefaultIconOptions; } } export function icon(options: IconOptions): Icon; - export interface DivIconOptions extends LayerOptions { + export interface DivIconOptions extends BaseIconOptions { html?: string; bgPos?: PointExpression; iconSize?: PointExpression; @@ -1445,7 +1458,7 @@ declare namespace L { className?: string; } - export class DivIcon extends InternalIcon { + export class DivIcon extends BaseIcon { constructor(options?: DivIconOptions); options: DivIconOptions; } @@ -1463,8 +1476,6 @@ declare namespace L { opacity?: number; riseOnHover?: boolean; riseOffset?: number; - - options?: DivIconOptions; } export class Marker extends Layer { @@ -1513,6 +1524,27 @@ declare namespace L { export const svg: boolean; } + export namespace Util { + export function extend(dest: any, src?: any): any; + export function create(proto: any, properties?: any): any; + export function bind(fn: () => void, ...obj: any[]): () => void; + export function stamp(obj: any): number; + export function throttle(fn: () => void, time: number, context: any): () => void; + export function wrapNum(num: number, range: number[], includeMax?: boolean): number; + export function falseFn(): () => false; + export function formatNum(num: number, digits?: number): number; + export function trim(str: string): string; + export function splitWords(str: string): string[]; + export function setOptions(obj: any, options: any): any; + export function getParamString(obj: any, existingUrl?: string, uppercase?: boolean): string; + export function template(str: string, data: any): string; + export function isArray(obj: any): boolean; + export function indexOf(array: any[], el: any): number; + export function requestAnimFrame(fn: () => void, context?: any, immediate?: boolean): number; + export function cancelAnimFrame(id: number): void; + export let lastId: string; + export let emptyImageUrl: string; + } } declare module 'leaflet' { diff --git a/leaflet/leaflet-tests.ts b/leaflet/leaflet-tests.ts index 8d9b91e37b..cce5565851 100644 --- a/leaflet/leaflet-tests.ts +++ b/leaflet/leaflet-tests.ts @@ -65,7 +65,7 @@ bounds = new L.Bounds(pointTuple, pointTuple); bounds = new L.Bounds([point, point]); bounds = new L.Bounds(boundsLiteral); -let points: Array; +let points: L.Point[]; points = L.LineUtil.simplify([point, point], 1); points = L.LineUtil.simplify([pointTuple, pointTuple], 2); @@ -141,9 +141,9 @@ let layer: L.Layer; const htmlElement = document.getElementById('foo'); -let popupOptions: L.PopupOptions = {}; +const popupOptions: L.PopupOptions = {}; -let tooltipOptions: L.TooltipOptions = {}; +const tooltipOptions: L.TooltipOptions = {}; let zoomPanOptions: L.ZoomPanOptions = {}; zoomPanOptions = { @@ -153,11 +153,11 @@ zoomPanOptions = { noMoveStart: true }; -let zoomOptions: L.ZoomOptions = {}; +const zoomOptions: L.ZoomOptions = {}; -let panOptions: L.PanOptions = {}; +const panOptions: L.PanOptions = {}; -let fitBoundsOptions: L.FitBoundsOptions = {}; +const fitBoundsOptions: L.FitBoundsOptions = {}; let map = L.map('foo'); map = L.map('foo', mapOptions); @@ -175,7 +175,7 @@ doesItHaveLayer = map.hasLayer(L.tileLayer('')); let html: HTMLElement; html = map.createPane('foo'); -html = map.createPane('foo', htmlElement) +html = map.createPane('foo', htmlElement); html = map.getPane('foo'); html = map.getPane(htmlElement); html = map.getContainer(); @@ -245,7 +245,7 @@ tileLayerOptions.subdomains = ['a', 'b']; tileLayerOptions.tileSize = 256; tileLayerOptions.tileSize = point; -//tileLayerOptions.tileSize = pointTuple; investigate if this is valid +// tileLayerOptions.tileSize = pointTuple; investigate if this is valid tileLayerOptions.bounds = latLngBounds; tileLayerOptions.bounds = latLngBoundsLiteral; @@ -259,17 +259,17 @@ tileLayer = new L.TileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png'); tileLayer = new L.TileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', tileLayerOptions); tileLayer = new L.TileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}&{bar}&{abc}', {foo: 'bar', bar: (data: any) => 'foo', abc: () => ''}); -let eventHandler = () => {}; -let domEvent: Event = {} as Event; +const eventHandler = () => {}; +const domEvent: Event = {} as Event; L.DomEvent .on(htmlElement, 'click', eventHandler) .addListener(htmlElement, 'click', eventHandler) .off(htmlElement, 'click', eventHandler) .removeListener(htmlElement, 'click', eventHandler) - .on(htmlElement, {'click': eventHandler}) - .addListener(htmlElement, {'click': eventHandler}) - .off(htmlElement, {'click': eventHandler}, eventHandler) - .removeListener(htmlElement, {'click': eventHandler}, eventHandler) + .on(htmlElement, {click: eventHandler}) + .addListener(htmlElement, {click: eventHandler}) + .off(htmlElement, {click: eventHandler}, eventHandler) + .removeListener(htmlElement, {click: eventHandler}, eventHandler) .stopPropagation(domEvent) .disableScrollPropagation(htmlElement) .disableClickPropagation(htmlElement) @@ -381,8 +381,8 @@ map = map .whenReady(() => {}) .whenReady(() => {}, {}); -let elementToDrag = document.createElement('div'); -let draggable = new L.Draggable(elementToDrag); +const elementToDrag = document.createElement('div'); +const draggable = new L.Draggable(elementToDrag); draggable.enable(); draggable.disable(); draggable.on('drag', () => {}); @@ -396,7 +396,7 @@ latLng = L.GeoJSON.coordsToLatLng(threeCoords); threeCoords = L.GeoJSON.latLngToCoords(latLng); let nestedTwoCoords = [ [12, 13], [13, 14], [14, 15] ]; -let nestedLatLngs: L.LatLng[] = L.GeoJSON.coordsToLatLngs(nestedTwoCoords, 1); +const nestedLatLngs: L.LatLng[] = L.GeoJSON.coordsToLatLngs(nestedTwoCoords, 1); nestedTwoCoords = L.GeoJSON.latLngsToCoords(nestedLatLngs, 1); class MyMarker extends L.Marker { @@ -404,24 +404,31 @@ class MyMarker extends L.Marker { super([12, 13]); } } + class MyLayer extends L.Layer { constructor() { super(); } } + class MyIcon extends L.Icon { constructor() { super({iconUrl: 'icon.png'}); } } + class MyDivIcon extends L.DivIcon { constructor() { super(); } } -let myControlClass = L.Control.extend({}); -let myControl = new myControlClass(); +const divIcon = L.divIcon({html: ''}); +let defaultIcon = new L.Icon.Default(); +defaultIcon = new L.Icon.Default({imagePath: 'apath'}); + +const myControlClass = L.Control.extend({}); +const myControl = new myControlClass(); L.Control.include({}); L.Control.mergeOptions({}); @@ -440,3 +447,22 @@ L.marker([1, 2], { iconUrl: 'my-icon.png' }) }).bindPopup('

Hi

'); + +L.Util.extend({}); +L.Util.create({}); +L.Util.bind(() => {}, {}); +L.Util.stamp({}); +L.Util.throttle(() => {}, 123, {}); +L.Util.wrapNum(123, []); +L.Util.falseFn(); +L.Util.formatNum(123); +L.Util.trim('word '); +L.Util.splitWords('word word'); +L.Util.setOptions({}, {}); +L.Util.getParamString({}); +L.Util.template('template', {}); +L.Util.isArray({}); +L.Util.indexOf([], {}); +L.Util.requestAnimFrame(() => {}); +L.Util.cancelAnimFrame(1); +L.Util.emptyImageUrl; diff --git a/libpq/libpq-tests.ts b/libpq/libpq-tests.ts index dda341a4bb..8a9aced3c3 100644 --- a/libpq/libpq-tests.ts +++ b/libpq/libpq-tests.ts @@ -5,20 +5,21 @@ import {Buffer} from 'buffer'; import * as assert from 'assert'; import * as async from 'async'; import * as PQ from 'libpq'; -import * as _ from 'lodash'; + +declare const _: { times(n: number, f: () => T): T[] }; declare const ok: Function; const createTable = (pq: PQ) => { pq.exec('CREATE TEMP TABLE test_data(name text, age int)'); console.log(pq.resultErrorMessage()); - pq.exec("INSERT INTO test_data(name, age) VALUES ('brian', 32), ('aaron', 30), ('', null);") + pq.exec("INSERT INTO test_data(name, age) VALUES ('brian', 32), ('aaron', 30), ('', null);"); }; const blink = (n: number, cb: Function) => { const connections: PQ[] = []; for (let i = 0; i < 30; i++) { - connections.push(new PQ()) + connections.push(new PQ()); } const connect = (con: PQ, cb: (err?: Error) => void) => { con.connect(cb); @@ -28,7 +29,7 @@ const blink = (n: number, cb: Function) => { con.finish(); }); cb(); - })) + })); }; const queryText = "SELECT * FROM generate_series(1, 1000)"; @@ -54,7 +55,7 @@ const query = (pq: PQ, cb: Function) => { return readError('Only one result at a time is accepted'); } cleanup(); - return cb(null, []) + return cb(null, []); }; const sent = pq.sendQuery(queryText); @@ -126,7 +127,7 @@ const consume = (pq: PQ, cb: Function) => { }; describe('async simple query', () => { - let pq: PQ; + const pq: PQ = null as any; it('dispatches simple query', (done: Function) => { assert(pq.setNonBlocking(true)); @@ -156,7 +157,7 @@ describe('async simple query', () => { assert.strictEqual(pq.ntuples(), 1); assert.equal(pq.getvalue(0, 0), 'Brian'); done(); - }) + }); }); it('dispatches named query', (done: Function) => { @@ -167,30 +168,30 @@ describe('async simple query', () => { consume(pq, () => { assert.ifError(pq.errorMessage()); - //first time there should be a result + // first time there should be a result assert(pq.getResult()); - //call 'getResult' until it returns false indicating - //there is no more input to consume + // call 'getResult' until it returns false indicating + // there is no more input to consume assert.strictEqual(pq.getResult(), false); - //since we only prepared a statement there should be - //0 tuples in the result + // since we only prepared a statement there should be + // 0 tuples in the result assert.equal(pq.ntuples(), 0); - //now execute the previously prepared statement + // now execute the previously prepared statement const success = pq.sendQueryPrepared(statementName, ['Brian']); assert(success, pq.errorMessage()); assert.strictEqual(pq.flush(), 0, 'Should have flushed parameters'); consume(pq, () => { assert.ifError(pq.errorMessage()); - //consume the result of the query execution + // consume the result of the query execution assert(pq.getResult()); assert.equal(pq.ntuples(), 1); assert.equal(pq.getvalue(0, 0), 'Brian'); - //call 'getResult' again to ensure we're finished + // call 'getResult' again to ensure we're finished assert.strictEqual(pq.getResult(), false); done(); }); @@ -395,7 +396,7 @@ describe('error info', () => { assert.equal(err.dataTypeName, undefined); assert.equal(err.constraintName, undefined); assert.equal(err.sourceFile, "parse_target.c"); - assert(parseInt(err.sourceLine)); + assert(parseInt(err.sourceLine, 10)); assert.equal(err.sourceFunction, "transformAssignedExpr"); }); }); @@ -449,8 +450,8 @@ describe('connecting', () => { describe('many connections', () => { it('works', (done) => { - async.timesSeries(10, blink, done) - }) + async.timesSeries(10, blink, done); + }); }); describe('connectSync', () => { @@ -477,7 +478,7 @@ describe('connect async', () => { assert.ifError(err); count++; pq.startReader(); - if (count == total) { + if (count === total) { cb(); } }); @@ -497,7 +498,7 @@ describe('multiple queries', () => { const pq = new PQ(); before((done) => { - pq.connect(done) + pq.connect(done); }); it('first query works', (done) => { diff --git a/libpq/tslint.json b/libpq/tslint.json index 377cc837d4..f05741c59b 100644 --- a/libpq/tslint.json +++ b/libpq/tslint.json @@ -1 +1,6 @@ -{ "extends": "../tslint.json" } +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/localforage-cordovasqlitedriver/localforage-cordovasqlitedriver-tests.ts b/localforage-cordovasqlitedriver/localforage-cordovasqlitedriver-tests.ts index 37f7820888..0efb62c9ce 100644 --- a/localforage-cordovasqlitedriver/localforage-cordovasqlitedriver-tests.ts +++ b/localforage-cordovasqlitedriver/localforage-cordovasqlitedriver-tests.ts @@ -26,30 +26,30 @@ declare var cordovaSQLiteDriver: LocalForageDriver; var newValue: string = value; }); - cordovaSQLiteDriver.keys((err: any, keys: Array) => { + cordovaSQLiteDriver.keys((err: any, keys: string[]) => { var newError: any = err; - var newArray: Array = keys; + var newArray: string[] = keys; }); - cordovaSQLiteDriver.getItem("key",(err: any, str: string) => { + cordovaSQLiteDriver.getItem("key", (err: any, str: string) => { var newError: any = err; - var newStr: string = str + var newStr: string = str; }); cordovaSQLiteDriver.setItem("key", "value", (err: any, str: string) => { var newError: any = err; - var newStr: string = str + var newStr: string = str; }); cordovaSQLiteDriver.setItem("key", "value", (str: string) => { var newStr: string = str; }); - cordovaSQLiteDriver.removeItem("key",(err: any) => { + cordovaSQLiteDriver.removeItem("key", (err: any) => { var newError: any = err; }); cordovaSQLiteDriver.removeItem("key", (err: any) => { var newError: any = err; }); -} \ No newline at end of file +}; \ No newline at end of file diff --git a/localforage-cordovasqlitedriver/tslint.json b/localforage-cordovasqlitedriver/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/localforage-cordovasqlitedriver/tslint.json +++ b/localforage-cordovasqlitedriver/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash-es/tslint.json b/lodash-es/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/lodash-es/tslint.json +++ b/lodash-es/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash-webpack-plugin/tsconfig.json b/lodash-webpack-plugin/tsconfig.json index 03e491ef78..34ca502764 100644 --- a/lodash-webpack-plugin/tsconfig.json +++ b/lodash-webpack-plugin/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, diff --git a/lodash.add/tslint.json b/lodash.add/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.add/tslint.json +++ b/lodash.add/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.after/tslint.json b/lodash.after/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.after/tslint.json +++ b/lodash.after/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.ary/tslint.json b/lodash.ary/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.ary/tslint.json +++ b/lodash.ary/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.assign/tslint.json b/lodash.assign/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.assign/tslint.json +++ b/lodash.assign/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.assignin/tslint.json b/lodash.assignin/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.assignin/tslint.json +++ b/lodash.assignin/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.assigninwith/tslint.json b/lodash.assigninwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.assigninwith/tslint.json +++ b/lodash.assigninwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.assignwith/tslint.json b/lodash.assignwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.assignwith/tslint.json +++ b/lodash.assignwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.at/tslint.json b/lodash.at/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.at/tslint.json +++ b/lodash.at/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.attempt/tslint.json b/lodash.attempt/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.attempt/tslint.json +++ b/lodash.attempt/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.before/tslint.json b/lodash.before/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.before/tslint.json +++ b/lodash.before/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.bind/tslint.json b/lodash.bind/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.bind/tslint.json +++ b/lodash.bind/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.bindall/tslint.json b/lodash.bindall/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.bindall/tslint.json +++ b/lodash.bindall/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.bindkey/tslint.json b/lodash.bindkey/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.bindkey/tslint.json +++ b/lodash.bindkey/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.camelcase/tslint.json b/lodash.camelcase/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.camelcase/tslint.json +++ b/lodash.camelcase/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.capitalize/tslint.json b/lodash.capitalize/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.capitalize/tslint.json +++ b/lodash.capitalize/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.castarray/tslint.json b/lodash.castarray/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.castarray/tslint.json +++ b/lodash.castarray/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.ceil/tslint.json b/lodash.ceil/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.ceil/tslint.json +++ b/lodash.ceil/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.chunk/tslint.json b/lodash.chunk/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.chunk/tslint.json +++ b/lodash.chunk/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.clamp/tslint.json b/lodash.clamp/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.clamp/tslint.json +++ b/lodash.clamp/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.clone/tslint.json b/lodash.clone/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.clone/tslint.json +++ b/lodash.clone/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.clonedeep/tslint.json b/lodash.clonedeep/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.clonedeep/tslint.json +++ b/lodash.clonedeep/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.clonedeepwith/tslint.json b/lodash.clonedeepwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.clonedeepwith/tslint.json +++ b/lodash.clonedeepwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.clonewith/tslint.json b/lodash.clonewith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.clonewith/tslint.json +++ b/lodash.clonewith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.compact/tslint.json b/lodash.compact/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.compact/tslint.json +++ b/lodash.compact/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.concat/tslint.json b/lodash.concat/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.concat/tslint.json +++ b/lodash.concat/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.constant/tslint.json b/lodash.constant/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.constant/tslint.json +++ b/lodash.constant/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.countby/tslint.json b/lodash.countby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.countby/tslint.json +++ b/lodash.countby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.create/tslint.json b/lodash.create/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.create/tslint.json +++ b/lodash.create/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.curry/tslint.json b/lodash.curry/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.curry/tslint.json +++ b/lodash.curry/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.curryright/tslint.json b/lodash.curryright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.curryright/tslint.json +++ b/lodash.curryright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.debounce/tslint.json b/lodash.debounce/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.debounce/tslint.json +++ b/lodash.debounce/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.deburr/tslint.json b/lodash.deburr/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.deburr/tslint.json +++ b/lodash.deburr/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.defaults/tslint.json b/lodash.defaults/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.defaults/tslint.json +++ b/lodash.defaults/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.defaultsdeep/tslint.json b/lodash.defaultsdeep/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.defaultsdeep/tslint.json +++ b/lodash.defaultsdeep/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.defer/tslint.json b/lodash.defer/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.defer/tslint.json +++ b/lodash.defer/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.delay/tslint.json b/lodash.delay/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.delay/tslint.json +++ b/lodash.delay/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.difference/tslint.json b/lodash.difference/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.difference/tslint.json +++ b/lodash.difference/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.differenceby/tslint.json b/lodash.differenceby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.differenceby/tslint.json +++ b/lodash.differenceby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.differencewith/tslint.json b/lodash.differencewith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.differencewith/tslint.json +++ b/lodash.differencewith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.drop/tslint.json b/lodash.drop/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.drop/tslint.json +++ b/lodash.drop/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.dropright/tslint.json b/lodash.dropright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.dropright/tslint.json +++ b/lodash.dropright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.droprightwhile/tslint.json b/lodash.droprightwhile/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.droprightwhile/tslint.json +++ b/lodash.droprightwhile/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.dropwhile/tslint.json b/lodash.dropwhile/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.dropwhile/tslint.json +++ b/lodash.dropwhile/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.endswith/tslint.json b/lodash.endswith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.endswith/tslint.json +++ b/lodash.endswith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.eq/tslint.json b/lodash.eq/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.eq/tslint.json +++ b/lodash.eq/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.escape/tslint.json b/lodash.escape/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.escape/tslint.json +++ b/lodash.escape/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.escaperegexp/tslint.json b/lodash.escaperegexp/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.escaperegexp/tslint.json +++ b/lodash.escaperegexp/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.every/tslint.json b/lodash.every/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.every/tslint.json +++ b/lodash.every/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.fill/tslint.json b/lodash.fill/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.fill/tslint.json +++ b/lodash.fill/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.filter/tslint.json b/lodash.filter/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.filter/tslint.json +++ b/lodash.filter/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.find/tslint.json b/lodash.find/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.find/tslint.json +++ b/lodash.find/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.findindex/tslint.json b/lodash.findindex/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.findindex/tslint.json +++ b/lodash.findindex/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.findkey/tslint.json b/lodash.findkey/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.findkey/tslint.json +++ b/lodash.findkey/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.findlast/tslint.json b/lodash.findlast/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.findlast/tslint.json +++ b/lodash.findlast/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.findlastindex/tslint.json b/lodash.findlastindex/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.findlastindex/tslint.json +++ b/lodash.findlastindex/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.findlastkey/tslint.json b/lodash.findlastkey/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.findlastkey/tslint.json +++ b/lodash.findlastkey/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.first/tslint.json b/lodash.first/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.first/tslint.json +++ b/lodash.first/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.flatmap/tslint.json b/lodash.flatmap/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.flatmap/tslint.json +++ b/lodash.flatmap/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.flatten/tslint.json b/lodash.flatten/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.flatten/tslint.json +++ b/lodash.flatten/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.flattendeep/tslint.json b/lodash.flattendeep/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.flattendeep/tslint.json +++ b/lodash.flattendeep/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.flattendepth/tslint.json b/lodash.flattendepth/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.flattendepth/tslint.json +++ b/lodash.flattendepth/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.flip/tslint.json b/lodash.flip/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.flip/tslint.json +++ b/lodash.flip/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.floor/tslint.json b/lodash.floor/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.floor/tslint.json +++ b/lodash.floor/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.flow/tslint.json b/lodash.flow/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.flow/tslint.json +++ b/lodash.flow/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.flowright/tslint.json b/lodash.flowright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.flowright/tslint.json +++ b/lodash.flowright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.foreach/tslint.json b/lodash.foreach/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.foreach/tslint.json +++ b/lodash.foreach/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.foreachright/tslint.json b/lodash.foreachright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.foreachright/tslint.json +++ b/lodash.foreachright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.forin/tslint.json b/lodash.forin/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.forin/tslint.json +++ b/lodash.forin/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.forinright/tslint.json b/lodash.forinright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.forinright/tslint.json +++ b/lodash.forinright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.forown/tslint.json b/lodash.forown/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.forown/tslint.json +++ b/lodash.forown/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.forownright/tslint.json b/lodash.forownright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.forownright/tslint.json +++ b/lodash.forownright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.frompairs/tslint.json b/lodash.frompairs/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.frompairs/tslint.json +++ b/lodash.frompairs/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.functions/tslint.json b/lodash.functions/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.functions/tslint.json +++ b/lodash.functions/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.functionsin/tslint.json b/lodash.functionsin/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.functionsin/tslint.json +++ b/lodash.functionsin/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.get/tslint.json b/lodash.get/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.get/tslint.json +++ b/lodash.get/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.groupby/tslint.json b/lodash.groupby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.groupby/tslint.json +++ b/lodash.groupby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.gt/tslint.json b/lodash.gt/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.gt/tslint.json +++ b/lodash.gt/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.gte/tslint.json b/lodash.gte/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.gte/tslint.json +++ b/lodash.gte/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.has/tslint.json b/lodash.has/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.has/tslint.json +++ b/lodash.has/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.hasin/tslint.json b/lodash.hasin/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.hasin/tslint.json +++ b/lodash.hasin/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.head/tslint.json b/lodash.head/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.head/tslint.json +++ b/lodash.head/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.identity/tslint.json b/lodash.identity/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.identity/tslint.json +++ b/lodash.identity/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.includes/tslint.json b/lodash.includes/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.includes/tslint.json +++ b/lodash.includes/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.indexof/tslint.json b/lodash.indexof/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.indexof/tslint.json +++ b/lodash.indexof/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.initial/tslint.json b/lodash.initial/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.initial/tslint.json +++ b/lodash.initial/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.inrange/tslint.json b/lodash.inrange/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.inrange/tslint.json +++ b/lodash.inrange/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.intersection/tslint.json b/lodash.intersection/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.intersection/tslint.json +++ b/lodash.intersection/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.intersectionby/tslint.json b/lodash.intersectionby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.intersectionby/tslint.json +++ b/lodash.intersectionby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.intersectionwith/tslint.json b/lodash.intersectionwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.intersectionwith/tslint.json +++ b/lodash.intersectionwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.invert/tslint.json b/lodash.invert/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.invert/tslint.json +++ b/lodash.invert/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.invertby/tslint.json b/lodash.invertby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.invertby/tslint.json +++ b/lodash.invertby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.invoke/tslint.json b/lodash.invoke/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.invoke/tslint.json +++ b/lodash.invoke/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.invokemap/tslint.json b/lodash.invokemap/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.invokemap/tslint.json +++ b/lodash.invokemap/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isarguments/tslint.json b/lodash.isarguments/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isarguments/tslint.json +++ b/lodash.isarguments/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isarray/tslint.json b/lodash.isarray/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isarray/tslint.json +++ b/lodash.isarray/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isarraybuffer/tslint.json b/lodash.isarraybuffer/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isarraybuffer/tslint.json +++ b/lodash.isarraybuffer/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isarraylike/tslint.json b/lodash.isarraylike/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isarraylike/tslint.json +++ b/lodash.isarraylike/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isarraylikeobject/tslint.json b/lodash.isarraylikeobject/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isarraylikeobject/tslint.json +++ b/lodash.isarraylikeobject/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isboolean/tslint.json b/lodash.isboolean/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isboolean/tslint.json +++ b/lodash.isboolean/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isbuffer/tslint.json b/lodash.isbuffer/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isbuffer/tslint.json +++ b/lodash.isbuffer/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isdate/tslint.json b/lodash.isdate/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isdate/tslint.json +++ b/lodash.isdate/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.iselement/tslint.json b/lodash.iselement/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.iselement/tslint.json +++ b/lodash.iselement/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isempty/tslint.json b/lodash.isempty/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isempty/tslint.json +++ b/lodash.isempty/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isequal/tslint.json b/lodash.isequal/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isequal/tslint.json +++ b/lodash.isequal/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isequalwith/tslint.json b/lodash.isequalwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isequalwith/tslint.json +++ b/lodash.isequalwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.iserror/tslint.json b/lodash.iserror/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.iserror/tslint.json +++ b/lodash.iserror/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isfinite/tslint.json b/lodash.isfinite/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isfinite/tslint.json +++ b/lodash.isfinite/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isfunction/tslint.json b/lodash.isfunction/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isfunction/tslint.json +++ b/lodash.isfunction/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isinteger/tslint.json b/lodash.isinteger/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isinteger/tslint.json +++ b/lodash.isinteger/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.islength/tslint.json b/lodash.islength/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.islength/tslint.json +++ b/lodash.islength/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.ismap/tslint.json b/lodash.ismap/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.ismap/tslint.json +++ b/lodash.ismap/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.ismatch/tslint.json b/lodash.ismatch/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.ismatch/tslint.json +++ b/lodash.ismatch/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.ismatchwith/tslint.json b/lodash.ismatchwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.ismatchwith/tslint.json +++ b/lodash.ismatchwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isnan/tslint.json b/lodash.isnan/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isnan/tslint.json +++ b/lodash.isnan/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isnative/tslint.json b/lodash.isnative/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isnative/tslint.json +++ b/lodash.isnative/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isnil/tslint.json b/lodash.isnil/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isnil/tslint.json +++ b/lodash.isnil/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isnull/tslint.json b/lodash.isnull/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isnull/tslint.json +++ b/lodash.isnull/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isnumber/tslint.json b/lodash.isnumber/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isnumber/tslint.json +++ b/lodash.isnumber/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isobject/tslint.json b/lodash.isobject/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isobject/tslint.json +++ b/lodash.isobject/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isobjectlike/tslint.json b/lodash.isobjectlike/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isobjectlike/tslint.json +++ b/lodash.isobjectlike/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isplainobject/tslint.json b/lodash.isplainobject/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isplainobject/tslint.json +++ b/lodash.isplainobject/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isregexp/tslint.json b/lodash.isregexp/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isregexp/tslint.json +++ b/lodash.isregexp/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.issafeinteger/tslint.json b/lodash.issafeinteger/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.issafeinteger/tslint.json +++ b/lodash.issafeinteger/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isset/tslint.json b/lodash.isset/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isset/tslint.json +++ b/lodash.isset/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isstring/tslint.json b/lodash.isstring/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isstring/tslint.json +++ b/lodash.isstring/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.issymbol/tslint.json b/lodash.issymbol/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.issymbol/tslint.json +++ b/lodash.issymbol/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.istypedarray/tslint.json b/lodash.istypedarray/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.istypedarray/tslint.json +++ b/lodash.istypedarray/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isundefined/tslint.json b/lodash.isundefined/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isundefined/tslint.json +++ b/lodash.isundefined/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isweakmap/tslint.json b/lodash.isweakmap/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isweakmap/tslint.json +++ b/lodash.isweakmap/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isweakset/tslint.json b/lodash.isweakset/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isweakset/tslint.json +++ b/lodash.isweakset/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.iteratee/tslint.json b/lodash.iteratee/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.iteratee/tslint.json +++ b/lodash.iteratee/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.join/tslint.json b/lodash.join/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.join/tslint.json +++ b/lodash.join/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.kebabcase/tslint.json b/lodash.kebabcase/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.kebabcase/tslint.json +++ b/lodash.kebabcase/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.keyby/tslint.json b/lodash.keyby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.keyby/tslint.json +++ b/lodash.keyby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.keys/tslint.json b/lodash.keys/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.keys/tslint.json +++ b/lodash.keys/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.keysin/tslint.json b/lodash.keysin/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.keysin/tslint.json +++ b/lodash.keysin/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.last/tslint.json b/lodash.last/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.last/tslint.json +++ b/lodash.last/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.lastindexof/tslint.json b/lodash.lastindexof/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.lastindexof/tslint.json +++ b/lodash.lastindexof/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.lowercase/tslint.json b/lodash.lowercase/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.lowercase/tslint.json +++ b/lodash.lowercase/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.lowerfirst/tslint.json b/lodash.lowerfirst/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.lowerfirst/tslint.json +++ b/lodash.lowerfirst/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.lt/tslint.json b/lodash.lt/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.lt/tslint.json +++ b/lodash.lt/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.lte/tslint.json b/lodash.lte/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.lte/tslint.json +++ b/lodash.lte/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.mapkeys/tslint.json b/lodash.mapkeys/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.mapkeys/tslint.json +++ b/lodash.mapkeys/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.mapvalues/tslint.json b/lodash.mapvalues/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.mapvalues/tslint.json +++ b/lodash.mapvalues/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.matches/tslint.json b/lodash.matches/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.matches/tslint.json +++ b/lodash.matches/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.matchesproperty/tslint.json b/lodash.matchesproperty/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.matchesproperty/tslint.json +++ b/lodash.matchesproperty/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.max/tslint.json b/lodash.max/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.max/tslint.json +++ b/lodash.max/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.maxby/tslint.json b/lodash.maxby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.maxby/tslint.json +++ b/lodash.maxby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.mean/tslint.json b/lodash.mean/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.mean/tslint.json +++ b/lodash.mean/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.meanby/tsconfig.json b/lodash.meanby/tsconfig.json index 5692e5627e..92ebbc6458 100644 --- a/lodash.meanby/tsconfig.json +++ b/lodash.meanby/tsconfig.json @@ -4,7 +4,9 @@ ], "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, diff --git a/lodash.meanby/tslint.json b/lodash.meanby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.meanby/tslint.json +++ b/lodash.meanby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.memoize/tslint.json b/lodash.memoize/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.memoize/tslint.json +++ b/lodash.memoize/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.merge/tslint.json b/lodash.merge/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.merge/tslint.json +++ b/lodash.merge/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.mergewith/tslint.json b/lodash.mergewith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.mergewith/tslint.json +++ b/lodash.mergewith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.method/tslint.json b/lodash.method/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.method/tslint.json +++ b/lodash.method/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.methodof/tslint.json b/lodash.methodof/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.methodof/tslint.json +++ b/lodash.methodof/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.min/tslint.json b/lodash.min/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.min/tslint.json +++ b/lodash.min/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.minby/tslint.json b/lodash.minby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.minby/tslint.json +++ b/lodash.minby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.mixin/tslint.json b/lodash.mixin/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.mixin/tslint.json +++ b/lodash.mixin/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.negate/tslint.json b/lodash.negate/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.negate/tslint.json +++ b/lodash.negate/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.noop/tslint.json b/lodash.noop/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.noop/tslint.json +++ b/lodash.noop/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.now/tslint.json b/lodash.now/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.now/tslint.json +++ b/lodash.now/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.ntharg/tslint.json b/lodash.ntharg/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.ntharg/tslint.json +++ b/lodash.ntharg/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.omit/tslint.json b/lodash.omit/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.omit/tslint.json +++ b/lodash.omit/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.omitby/tslint.json b/lodash.omitby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.omitby/tslint.json +++ b/lodash.omitby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.once/tslint.json b/lodash.once/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.once/tslint.json +++ b/lodash.once/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.orderby/tslint.json b/lodash.orderby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.orderby/tslint.json +++ b/lodash.orderby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.over/tslint.json b/lodash.over/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.over/tslint.json +++ b/lodash.over/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.overargs/tslint.json b/lodash.overargs/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.overargs/tslint.json +++ b/lodash.overargs/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.overevery/tslint.json b/lodash.overevery/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.overevery/tslint.json +++ b/lodash.overevery/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.oversome/tslint.json b/lodash.oversome/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.oversome/tslint.json +++ b/lodash.oversome/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.pad/tslint.json b/lodash.pad/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.pad/tslint.json +++ b/lodash.pad/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.padend/tslint.json b/lodash.padend/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.padend/tslint.json +++ b/lodash.padend/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.padstart/tslint.json b/lodash.padstart/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.padstart/tslint.json +++ b/lodash.padstart/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.parseint/tslint.json b/lodash.parseint/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.parseint/tslint.json +++ b/lodash.parseint/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.partial/tslint.json b/lodash.partial/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.partial/tslint.json +++ b/lodash.partial/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.partialright/tslint.json b/lodash.partialright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.partialright/tslint.json +++ b/lodash.partialright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.partition/tslint.json b/lodash.partition/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.partition/tslint.json +++ b/lodash.partition/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.pick/tslint.json b/lodash.pick/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.pick/tslint.json +++ b/lodash.pick/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.pickby/tslint.json b/lodash.pickby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.pickby/tslint.json +++ b/lodash.pickby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.property/tslint.json b/lodash.property/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.property/tslint.json +++ b/lodash.property/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.propertyof/tslint.json b/lodash.propertyof/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.propertyof/tslint.json +++ b/lodash.propertyof/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.pull/tslint.json b/lodash.pull/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.pull/tslint.json +++ b/lodash.pull/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.pullall/tslint.json b/lodash.pullall/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.pullall/tslint.json +++ b/lodash.pullall/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.pullallby/tslint.json b/lodash.pullallby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.pullallby/tslint.json +++ b/lodash.pullallby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.pullat/tslint.json b/lodash.pullat/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.pullat/tslint.json +++ b/lodash.pullat/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.random/tslint.json b/lodash.random/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.random/tslint.json +++ b/lodash.random/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.range/tslint.json b/lodash.range/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.range/tslint.json +++ b/lodash.range/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.rangeright/tslint.json b/lodash.rangeright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.rangeright/tslint.json +++ b/lodash.rangeright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.rearg/tslint.json b/lodash.rearg/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.rearg/tslint.json +++ b/lodash.rearg/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.reduce/tslint.json b/lodash.reduce/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.reduce/tslint.json +++ b/lodash.reduce/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.reduceright/tslint.json b/lodash.reduceright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.reduceright/tslint.json +++ b/lodash.reduceright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.reject/tslint.json b/lodash.reject/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.reject/tslint.json +++ b/lodash.reject/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.remove/tslint.json b/lodash.remove/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.remove/tslint.json +++ b/lodash.remove/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.repeat/tslint.json b/lodash.repeat/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.repeat/tslint.json +++ b/lodash.repeat/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.replace/tslint.json b/lodash.replace/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.replace/tslint.json +++ b/lodash.replace/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.rest/tslint.json b/lodash.rest/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.rest/tslint.json +++ b/lodash.rest/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.result/tslint.json b/lodash.result/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.result/tslint.json +++ b/lodash.result/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.reverse/tslint.json b/lodash.reverse/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.reverse/tslint.json +++ b/lodash.reverse/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.round/tslint.json b/lodash.round/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.round/tslint.json +++ b/lodash.round/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sample/tslint.json b/lodash.sample/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sample/tslint.json +++ b/lodash.sample/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.samplesize/tslint.json b/lodash.samplesize/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.samplesize/tslint.json +++ b/lodash.samplesize/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.set/tslint.json b/lodash.set/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.set/tslint.json +++ b/lodash.set/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.setwith/tslint.json b/lodash.setwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.setwith/tslint.json +++ b/lodash.setwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.shuffle/tslint.json b/lodash.shuffle/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.shuffle/tslint.json +++ b/lodash.shuffle/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.size/tslint.json b/lodash.size/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.size/tslint.json +++ b/lodash.size/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.slice/tslint.json b/lodash.slice/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.slice/tslint.json +++ b/lodash.slice/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.snakecase/tslint.json b/lodash.snakecase/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.snakecase/tslint.json +++ b/lodash.snakecase/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.some/tslint.json b/lodash.some/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.some/tslint.json +++ b/lodash.some/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sortby/tslint.json b/lodash.sortby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sortby/tslint.json +++ b/lodash.sortby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sortedindex/tslint.json b/lodash.sortedindex/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sortedindex/tslint.json +++ b/lodash.sortedindex/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sortedindexby/tslint.json b/lodash.sortedindexby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sortedindexby/tslint.json +++ b/lodash.sortedindexby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sortedindexof/tslint.json b/lodash.sortedindexof/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sortedindexof/tslint.json +++ b/lodash.sortedindexof/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sortedlastindex/tslint.json b/lodash.sortedlastindex/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sortedlastindex/tslint.json +++ b/lodash.sortedlastindex/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sortedlastindexby/tslint.json b/lodash.sortedlastindexby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sortedlastindexby/tslint.json +++ b/lodash.sortedlastindexby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sortedlastindexof/tslint.json b/lodash.sortedlastindexof/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sortedlastindexof/tslint.json +++ b/lodash.sortedlastindexof/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sorteduniq/tslint.json b/lodash.sorteduniq/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sorteduniq/tslint.json +++ b/lodash.sorteduniq/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sorteduniqby/tslint.json b/lodash.sorteduniqby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sorteduniqby/tslint.json +++ b/lodash.sorteduniqby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.split/tslint.json b/lodash.split/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.split/tslint.json +++ b/lodash.split/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.spread/tslint.json b/lodash.spread/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.spread/tslint.json +++ b/lodash.spread/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.startcase/tslint.json b/lodash.startcase/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.startcase/tslint.json +++ b/lodash.startcase/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.startswith/tslint.json b/lodash.startswith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.startswith/tslint.json +++ b/lodash.startswith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.subtract/tslint.json b/lodash.subtract/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.subtract/tslint.json +++ b/lodash.subtract/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sum/tslint.json b/lodash.sum/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sum/tslint.json +++ b/lodash.sum/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sumby/tslint.json b/lodash.sumby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sumby/tslint.json +++ b/lodash.sumby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.tail/tslint.json b/lodash.tail/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.tail/tslint.json +++ b/lodash.tail/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.take/tslint.json b/lodash.take/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.take/tslint.json +++ b/lodash.take/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.takeright/tslint.json b/lodash.takeright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.takeright/tslint.json +++ b/lodash.takeright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.takerightwhile/tslint.json b/lodash.takerightwhile/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.takerightwhile/tslint.json +++ b/lodash.takerightwhile/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.takewhile/tslint.json b/lodash.takewhile/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.takewhile/tslint.json +++ b/lodash.takewhile/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.template/tslint.json b/lodash.template/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.template/tslint.json +++ b/lodash.template/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.throttle/tslint.json b/lodash.throttle/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.throttle/tslint.json +++ b/lodash.throttle/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.times/tslint.json b/lodash.times/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.times/tslint.json +++ b/lodash.times/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.toarray/tslint.json b/lodash.toarray/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.toarray/tslint.json +++ b/lodash.toarray/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.tointeger/tslint.json b/lodash.tointeger/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.tointeger/tslint.json +++ b/lodash.tointeger/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.tolength/tslint.json b/lodash.tolength/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.tolength/tslint.json +++ b/lodash.tolength/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.tolower/tslint.json b/lodash.tolower/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.tolower/tslint.json +++ b/lodash.tolower/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.tonumber/tslint.json b/lodash.tonumber/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.tonumber/tslint.json +++ b/lodash.tonumber/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.topairs/tslint.json b/lodash.topairs/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.topairs/tslint.json +++ b/lodash.topairs/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.topairsin/tslint.json b/lodash.topairsin/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.topairsin/tslint.json +++ b/lodash.topairsin/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.topath/tslint.json b/lodash.topath/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.topath/tslint.json +++ b/lodash.topath/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.toplainobject/tslint.json b/lodash.toplainobject/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.toplainobject/tslint.json +++ b/lodash.toplainobject/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.tosafeinteger/tslint.json b/lodash.tosafeinteger/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.tosafeinteger/tslint.json +++ b/lodash.tosafeinteger/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.tostring/tslint.json b/lodash.tostring/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.tostring/tslint.json +++ b/lodash.tostring/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.toupper/tslint.json b/lodash.toupper/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.toupper/tslint.json +++ b/lodash.toupper/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.transform/tslint.json b/lodash.transform/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.transform/tslint.json +++ b/lodash.transform/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.trim/tslint.json b/lodash.trim/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.trim/tslint.json +++ b/lodash.trim/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.trimend/tslint.json b/lodash.trimend/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.trimend/tslint.json +++ b/lodash.trimend/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.trimstart/tslint.json b/lodash.trimstart/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.trimstart/tslint.json +++ b/lodash.trimstart/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.truncate/tslint.json b/lodash.truncate/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.truncate/tslint.json +++ b/lodash.truncate/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.unary/tslint.json b/lodash.unary/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.unary/tslint.json +++ b/lodash.unary/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.unescape/tslint.json b/lodash.unescape/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.unescape/tslint.json +++ b/lodash.unescape/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.union/tslint.json b/lodash.union/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.union/tslint.json +++ b/lodash.union/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.unionby/tslint.json b/lodash.unionby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.unionby/tslint.json +++ b/lodash.unionby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.unionwith/tslint.json b/lodash.unionwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.unionwith/tslint.json +++ b/lodash.unionwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.uniq/tslint.json b/lodash.uniq/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.uniq/tslint.json +++ b/lodash.uniq/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.uniqby/tslint.json b/lodash.uniqby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.uniqby/tslint.json +++ b/lodash.uniqby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.uniqueid/tslint.json b/lodash.uniqueid/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.uniqueid/tslint.json +++ b/lodash.uniqueid/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.uniqwith/tslint.json b/lodash.uniqwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.uniqwith/tslint.json +++ b/lodash.uniqwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.unset/tslint.json b/lodash.unset/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.unset/tslint.json +++ b/lodash.unset/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.unzip/tslint.json b/lodash.unzip/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.unzip/tslint.json +++ b/lodash.unzip/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.unzipwith/tslint.json b/lodash.unzipwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.unzipwith/tslint.json +++ b/lodash.unzipwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.update/tslint.json b/lodash.update/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.update/tslint.json +++ b/lodash.update/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.uppercase/tslint.json b/lodash.uppercase/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.uppercase/tslint.json +++ b/lodash.uppercase/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.upperfirst/tslint.json b/lodash.upperfirst/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.upperfirst/tslint.json +++ b/lodash.upperfirst/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.values/tslint.json b/lodash.values/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.values/tslint.json +++ b/lodash.values/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.valuesin/tslint.json b/lodash.valuesin/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.valuesin/tslint.json +++ b/lodash.valuesin/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.without/tslint.json b/lodash.without/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.without/tslint.json +++ b/lodash.without/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.words/tslint.json b/lodash.words/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.words/tslint.json +++ b/lodash.words/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.wrap/tslint.json b/lodash.wrap/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.wrap/tslint.json +++ b/lodash.wrap/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.xor/tslint.json b/lodash.xor/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.xor/tslint.json +++ b/lodash.xor/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.xorby/tslint.json b/lodash.xorby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.xorby/tslint.json +++ b/lodash.xorby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.xorwith/tslint.json b/lodash.xorwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.xorwith/tslint.json +++ b/lodash.xorwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.zip/tslint.json b/lodash.zip/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.zip/tslint.json +++ b/lodash.zip/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.zipobject/tslint.json b/lodash.zipobject/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.zipobject/tslint.json +++ b/lodash.zipobject/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.zipwith/tslint.json b/lodash.zipwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.zipwith/tslint.json +++ b/lodash.zipwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash/index.d.ts b/lodash/index.d.ts index 00de563bbb..e473545d33 100644 --- a/lodash/index.d.ts +++ b/lodash/index.d.ts @@ -10387,6 +10387,13 @@ declare namespace _ { * @param funcs Functions to invoke. * @return Returns the new function. */ + // 0-argument first function + flow(f1: () => R1, f2: (a: R1) => R2): () => R2; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): () => R3; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): () => R4; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): () => R5; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): () => R6; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): () => R7; // 1-argument first function flow(f1: (a1: A1) => R1, f2: (a: R1) => R2): (a1: A1) => R2; flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1) => R3; @@ -12701,7 +12708,7 @@ declare namespace _ { * @param value The value to check. * @returns Returns true if value is correctly classified, else false. */ - isWeakMap(value?: any): value is WeakMap; + isWeakMap(value?: any): boolean; } interface LoDashImplicitWrapperBase { @@ -19446,5 +19453,4 @@ declare global { interface Set { } interface Map { } interface WeakSet { } - interface WeakMap { } } diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 7d4105df70..8ccd742a0e 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -80,7 +80,7 @@ var keys: IKey[] = [ class Dog { constructor(public name: string) { } - public bark() { + bark() { console.log('Woof, woof!'); } } @@ -3741,17 +3741,13 @@ namespace TestFind { result = _(dictionary).find({a: 42}, 1); } -result = _.findLast([1, 2, 3, 4], function (num) { - return num % 2 == 0; -}); +result = _.findLast([1, 2, 3, 4], num => num % 2 == 0); result = _.findLast(foodsCombined, { 'type': 'vegetable' }); result = _.findLast(foodsCombined, 'organic'); result = _.findLast(foodsCombined, 'organic', 1); -result = _([1, 2, 3, 4]).findLast(function (num) { - return num % 2 == 0; -}); +result = _([1, 2, 3, 4]).findLast(num => num % 2 == 0); result = _(foodsCombined).findLast({ 'type': 'vegetable' }); result = _(foodsCombined).findLast('organic'); @@ -4711,29 +4707,23 @@ namespace TestReduce { c: number; } - result = _.reduce([1, 2, 3], function (sum: number, num: number) { - return sum + num; - }); + result = _.reduce([1, 2, 3], (sum: number, num: number) => sum + num); // chained - result = _.chain([1, 2 ,3]).reduce(function (sum: number, num: number) { - return sum + num; - }).value(); + result = _.chain([1, 2 ,3]).reduce((sum: number, num: number) => sum + num).value(); - result = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function (r: ABC, num: number, key: string) { + result = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, (r: ABC, num: number, key: string) => { r[key] = num * 3; return r; }, {}); - result = _([1, 2, 3]).reduce(function (sum: number, num: number) { - return sum + num; - }); - result = _({ 'a': 1, 'b': 2, 'c': 3 }).reduce(function (r: ABC, num: number, key: string) { + result = _([1, 2, 3]).reduce((sum: number, num: number) => sum + num); + result = _({ 'a': 1, 'b': 2, 'c': 3 }).reduce((r: ABC, num: number, key: string) => { r[key] = num * 3; return r; }, {}); - result = _.reduceRight([[0, 1], [2, 3], [4, 5]], function (a: number[], b: number[]) { return a.concat(b); }, []); + result = _.reduceRight([[0, 1], [2, 3], [4, 5]], (a: number[], b: number[]) => a.concat(b), []); } // _.reject namespace TestReject { @@ -5173,9 +5163,9 @@ namespace TestSortBy { } } -result = _.sortBy(stoogesAges, function(stooge) { return Math.sin(stooge.age); }, function(stooge) { return stooge.name.slice(1); }); +result = _.sortBy(stoogesAges, stooge => Math.sin(stooge.age), stooge => stooge.name.slice(1)); result = _.sortBy(stoogesAges, ['name', 'age']); -result = _.sortBy(stoogesAges, 'name', function(stooge) { return Math.sin(stooge.age); }); +result = _.sortBy(stoogesAges, 'name', stooge => Math.sin(stooge.age)); result = _(foodsOrganic).sortBy('organic', (food) => food.name, { organic: true }).value(); @@ -6017,7 +6007,7 @@ namespace TestOnce { } } -var greetPartial = function (greeting: string, name: string) { return greeting + ' ' + name; }; +var greetPartial = (greeting: string, name: string) => greeting + ' ' + name; var hi = _.partial(greetPartial, 'hi'); hi('moe'); @@ -7445,17 +7435,6 @@ namespace TestIsUndefined { // _.isWeakMap namespace TestIsWeakMap { - { - let value: number|WeakMap; - - if (_.isWeakMap(value)) { - let result: WeakMap = value; - } - else { - let result: number = value; - } - } - { let result: boolean; @@ -7475,7 +7454,7 @@ namespace TestIsWeakMap { } // _.isWeakSet -module TestIsWeakSet { +namespace TestIsWeakSet { { let value: number|WeakSet; @@ -8620,7 +8599,7 @@ namespace TestDefaults { let s5: S5; { - let result: Obj; + let result: Obj; result = _.defaults(obj); } @@ -10496,7 +10475,7 @@ namespace TestValuesIn { let result: TResult[]; // Without this type hint, this will fail to compile, as expected. - result = _.valuesIn(new Object); + result = _.valuesIn({}); } { @@ -11705,7 +11684,7 @@ namespace TestNoConflict { // _.noop namespace TestNoop { { - let result: void; + let result: void; // tslint:disable-line:void-return result = _.noop(); result = _.noop(1); diff --git a/lodash/tslint.json b/lodash/tslint.json index 8bcd32b3b1..62d13dc883 100644 --- a/lodash/tslint.json +++ b/lodash/tslint.json @@ -1,8 +1,21 @@ { "extends": "../tslint.json", "rules": { + "array-type": false, + "callable-types": false, + "comment-format": false, "forbidden-types": false, + "interface-name": false, + "interface-over-type-literal": false, + "max-line-length": false, "no-empty-interface": false, - "unified-signatures": false + "object-literal-key-quotes": false, + "one-line": false, + "prefer-const": false, + "semicolon": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "whitespace": false } -} \ No newline at end of file +} diff --git a/loopback-boot/index.d.ts b/loopback-boot/index.d.ts index 4c66af5ef8..93e912363e 100644 --- a/loopback-boot/index.d.ts +++ b/loopback-boot/index.d.ts @@ -17,35 +17,35 @@ import * as loopback from "loopback"; * ``` * var loopback= require('loopback'); * var boot = require('loopback-boot'); - * + * * var app = module.exports = loopback(); - * + * * boot(app, __dirname); - * + * * ``` - * + * * Initialize an application from an options object or a set of JSON and JavaScript files. - * - * NOTE: This module is primarily intended for use with LoopBack 2.0. It does work with LoopBack 1.x applications, + * + * NOTE: This module is primarily intended for use with LoopBack 2.0. It does work with LoopBack 1.x applications, * but none of the LoopBack 1.x examples or generated code (scaffolding) use it. - * + * * This function takes an optional argument that is either a string or an object. - * + * * If the argument is a string, then it sets the application root directory based on the string value. Then it: * Creates DataSources from the datasources.json file in the application root directory. - * + * * Configures Models from the model-config.json file in the application root directory. - * - * Configures the LoopBack Application object from the config.json file in the application root directory. + * + * Configures the LoopBack Application object from the config.json file in the application root directory. * These properties can be accessed using app.get('propname'). - * + * * If the argument is an object, then it looks for models, dataSources, 'config', modelsRootDir, dsRootDir, * appConfigRootDir and appRootDir properties of the object. - * + * * If the object has no appRootDir property then it sets the current working directory as the application root directory. - * + * * The execution environment, {env}, is established from, in order, - * + * * options.env * process.env.NODE_ENV, * the literal development. @@ -64,20 +64,21 @@ import * as loopback from "loopback"; * config.json, * config.local.js or config.local.json (only one), * config.{env}.js or config.{env}.json (only one) - * + * * in the directory designated by 'options.appConfigRootDir', if present, or the application root directory. * It merges the properties from the files found. - * - * In both cases, the function loads JavaScript files in the /boot subdirectory of the application root directory + * + * In both cases, the function loads JavaScript files in the /boot subdirectory of the application root directory * with require(). - * + * * NOTE: The version 2.0 of loopback-boot changed the way how models are created. - * The model-config.json file contains only configuration options like dataSource and extra relations. + * The model-config.json file contains only configuration options like dataSource and extra relations. * To define a model, create a per-model JSON file in models/ directory. - * - * NOTE: Mixing bootLoopBackApp(app, bootConfig) and app.model(name, modelConfig) in multiple files may result in models being undefined due to race conditions. To avoid this when using bootLoopBackApp() make sure all models are passed as part of the models definition. + * + * NOTE: Mixing bootLoopBackApp(app, bootConfig) and app.model(name, modelConfig) in multiple files may result in models being undefined due to race conditions. + * To avoid this when using bootLoopBackApp() make sure all models are passed as part of the models definition. * Throws an error if the config object is not valid or if boot fails. - * + * * @param {Loopback.LoopbackApplication} app LoopBack application created by loopback(). * @param {string|OptionsLB} options Boot options; If String, this is the application root directory; if object, has below properties. * @param {() => void} callback @@ -87,13 +88,13 @@ declare function lb(app: loopback.LoopBackApplication, options: string|OptionsLB interface OptionsLB { /** - * Directory to use when loading JSON and JavaScript files. + * Directory to use when loading JSON and JavaScript files. * Defaults to the current directory (process.cwd()). */ appRootDir: string; /** - * Directory to use when loading config.json. Defaults to appRootDir. + * Directory to use when loading config.json. Defaults to appRootDir. */ appConfigRootDir: string; @@ -103,7 +104,7 @@ interface OptionsLB { models: any; /** - * List of model definitions to use. When options.modelDefinitions is provided, + * List of model definitions to use. When options.modelDefinitions is provided, * loopback-boot does not search filesystem and use only the models provided in this argument. */ modelDefinitions: any[]; @@ -134,8 +135,8 @@ interface OptionsLB { componentRootDir: string; /** - * Environment type, defaults to process.env.NODE_ENV or development. - * Common values are development, staging and production; + * Environment type, defaults to process.env.NODE_ENV or development. + * Common values are development, staging and production; * however the applications are free to use any names. */ env: string; @@ -156,7 +157,7 @@ interface OptionsLB { components: any; /** - * List of directories where to look for files containing model mixin definitions. + * List of directories where to look for files containing model mixin definitions. * All files (mixins) found in these directory are loaded. */ mixinDirs: string[]; @@ -187,7 +188,7 @@ declare namespace lb { /** * compileToBrowserify - * + * * Compile boot instructions and add them to a browserify bundler. * @param {string|any} options as described in bootLoopBackApp above. * @param {any} bundler A browserify bundler created by browserify(). @@ -198,7 +199,7 @@ declare namespace lb { class compileToBrowserify { /** - * Application identifier used to load the correct boot configuration when + * Application identifier used to load the correct boot configuration when * building multiple applications using browserify. */ appId: string; diff --git a/loopback-boot/loopback-boot-tests.ts b/loopback-boot/loopback-boot-tests.ts index 75a0bf2ca5..4885fca1d0 100644 --- a/loopback-boot/loopback-boot-tests.ts +++ b/loopback-boot/loopback-boot-tests.ts @@ -1,4 +1,3 @@ -/// import * as loopback from 'loopback'; import * as boot from 'loopback-boot'; import * as cookieParser from 'cookie-parser'; diff --git a/loopback-boot/tslint.json b/loopback-boot/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/loopback-boot/tslint.json +++ b/loopback-boot/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/loopback/index.d.ts b/loopback/index.d.ts index 64aac97c92..2d4af5caa9 100644 --- a/loopback/index.d.ts +++ b/loopback/index.d.ts @@ -88,7 +88,7 @@ declare namespace l { * @returns {any} http.Server A node `http.Server` with this application configured * as the request handle * listen(cb?: () => void):http.Serve - * + * */ // listen(port?: number, cb?: () => void): any; @@ -203,16 +203,16 @@ declare namespace l { /** * Register (new) middleware phases. - * + * * If all names are new, then the phases are added just before "routes" phase. * Otherwise the provided list of names is merged with the existing phases * in such way that the order of phases is preserved - * + * * **Examples* * ```js * // built-in phases: * // initial, session, auth, parse, routes, files, fina - * + * * app.defineMiddlewarePhases('custom'); * // new list of phases * // initial, session, auth, parse, custom, routes, files, fina @@ -245,7 +245,7 @@ declare namespace l { * @header app.middleware(name, handler */ - middleware(name: string, paths?: any[]|string|RegExp, handler?: () => void): any; + middleware(name: string, paths?: any[]|string|RegExp, handler?: core.Handler): any; } // interface CookieOptions extends core.CookieOptions { } @@ -340,7 +340,7 @@ declare namespace l { * In the second variant, the parameters `name`, `properties` and `options` * are provided in the config object. Any additional config entries are * interpreted as `options`, i.e. the following two configs are identical - * + * * ```js * { name: 'Customer', base: 'User' } * { name: 'Customer', options: { base: 'User' } } @@ -792,7 +792,7 @@ declare namespace l { * // => model with id 1 has been changed * }); * `` - * + * * #### Event: `deleted * Emitted after an individual model has been deleted. * Argument: `id`, model ID (number) @@ -803,7 +803,7 @@ declare namespace l { * }); * `` * #### Event: `deletedAll - * + * * Emitted after an individual model has been deleted. * Argument: `where` (optional), where filter, JSON object * ```js @@ -816,7 +816,7 @@ declare namespace l { * } * }); * `` - * + * * #### Event: `attached * Emitted after a `Model` has been attached to an `app` * #### Event: `dataSourceAttached @@ -830,7 +830,7 @@ declare namespace l { * // => model with id 1 has been changed * }); * `` - * + * * @param {any} data * @property {string} Model.modelName The name of the model. Static property. * @property {DataSource} Model.dataSource Data source to which the model is connected, if any. Static property. @@ -912,8 +912,15 @@ declare namespace l { * @param {any} SharedMethod object. See [here](apidocs.strongloop.com/strong-remoting/#sharedmethod). * @param {any} RelationDefinition object which includes relation `type`, `ModelConstructor` of `modelFrom`, `modelTo`, `keyFrom`, `keyTo` and more relation definitions */ - - static nestRemoting(relationName: string, pathName: string, filterMethod: string, paramName: string, getterName: string, hooks: boolean, options?: {}, filterCallback?: (SharedMethod: any, RelationDefinition: any) => void): void; + static nestRemoting( + relationName: string, + pathName: string, + filterMethod: string, + paramName: string, + getterName: string, + hooks: boolean, + options?: {}, + filterCallback?: (SharedMethod: any, RelationDefinition: any) => void): void; /** * Enable remote invocation for the specified method. @@ -943,12 +950,12 @@ declare namespace l { * SharedClass * Create a new SharedClass with the given options. * **NOTE** TODO : exported from another module type definition called strong-remoting - * + * * @param {string} name The SharedClass name * @param {() => void} constructor The constructor the SharedClass represents * @param {any} options Additional options. * @property {() => void } ctor The constructor - * @property {any} http The HTTP settings + * @property {any} http The HTTP settings */ class SharedClass { @@ -1013,7 +1020,7 @@ declare namespace l { /** * Get all shared methods belonging to this shared class. - * @param {any} options + * @param {any} options * @return {any[]} An array of shared methods SharedMethod[] */ @@ -1034,7 +1041,7 @@ declare namespace l { * cb(null, str); * } * ``` - * + * * @param {() => void} resolver The resolver function. */ @@ -1053,14 +1060,14 @@ declare namespace l { * **Change Event* * Listen for model changes using the `change` event * ```js - * MyPersistedModel.on('changed', function(obj) + * MyPersistedModel.on('changed', function(obj) * console.log(obj) // => the changed model * }); * ``` * @class PersistedModel */ - class PersistedModel { + class PersistedModel extends Model { /** * Apply an update list @@ -1116,10 +1123,10 @@ declare namespace l { static create(data?: any|any[], callback?: (err: Error, models: any) => void): void; - /** + /** * Create a change stream. See here for more info http://loopback.io/doc/en/lb2/Realtime-server-sent-events.html * @param {any} options Only changes to models matching this where filter will be included in the ChangeStream. - * @param {() => void} callback + * @param {() => void} callback */ static createChangeStream(options: {where: any}, callback: (err: Error, changes: any) => void): void; @@ -1150,7 +1157,7 @@ declare namespace l { * ``` *
See * [Where filter](docs.strongloop.com/display/LB/Where+filter#Wherefilter-Whereclauseforothermethods) - * + * * @callback {() => void} callback Optional callback function called with `(err, info)` arguments. * @param {Error} err Error object; see [Error object](docs.strongloop.com/display/LB/Error+object). * @param {any} info Additional information about the command outcome. @@ -1220,8 +1227,9 @@ declare namespace l { * @param {Error} err Error object; see [Error object](docs.strongloop.com/display/LB/Error+object). * @param {Array} models Model instances matching the filter, or null if none found */ - - static find(filter?: {fields?: string|any|any[]; include?: string|any|any[]; limit?: number; order?: string; skip?: number; where?: any; }, callback?: (err: Error, models: any[]) => void): void; + static find( + filter?: {fields?: string|any|any[]; include?: string|any|any[]; limit?: number; order?: string; skip?: number; where?: any; }, + callback?: (err: Error, models: any[]) => void): void; /** * Find object by ID with an optional filter for include/fields @@ -1262,7 +1270,7 @@ declare namespace l { * @param {Array} model First model instance that matches the filter or null if none found */ - static findOne(filter?: {fields: string|any|any[]; include: string|any|any[]; order: string; skip: number; where: any; }, callback?: (err: Error, model: any[]) => void): void; + static findOne(filter?: {fields?: string|any|any[]; include?: string|any|any[]; order?: string; skip?: number; where?: any; }, callback?: (err: Error, model: any) => void): void; /** * Finds one record matching the optional filter object. If not found, creates @@ -1270,7 +1278,7 @@ declare namespace l { * the same as `find`, but limited to one object. Returns an object, not * collection. If you don't provide the filter object argument, it tries to * locate an existing object that matches the `data` argument - * + * * @options {any} [filter] Optional Filter object; see below. * @property {string|any|Array} fields Identify fields to include in return result. *
See [Fields filter](docs.strongloop.com/display/LB/Fields+filter). @@ -1295,7 +1303,17 @@ declare namespace l { * @param {boolean} created True if the instance matching the `where` filter was created */ - static findOrCreate(data: any, filter?: {fields?: string|any|any[]; include?: string|any|any[]; limit?: number; order?: string; skip?: number; where?: any; }, callback?: (err: Error, instance: any, created: boolean) => void): void; + static findOrCreate( + data: any, + filter?: { + fields?: string | any | any[]; + include?: string | any | any[]; + limit?: number; + order?: string; + skip?: number; + where?: any; + }, + callback?: (err: Error, instance: any, created: boolean) => void): void; /** * Get the `Change` model. @@ -1627,7 +1645,7 @@ declare namespace l { function static(root: string, options: any): void; /** - * Return HTTP response with basic application status information: + * Return HTTP response with basic application status information: * date the application was started and uptime, in JSON format. For example: * ``` * { @@ -1651,7 +1669,7 @@ declare namespace l { * - `access_token` (params only) * - `X-Access-Token` (headers only) * - `authorization` (headers and cookies - * + * * It checks for these values in cookies, headers, and query string parameters _in addition_ to the items * specified in the options parameter * **NOTE:** This function only checks for [signed cookies](expressjs.com/api.html#req.signedCookies) @@ -1664,7 +1682,7 @@ declare namespace l { * params: ['foo-auth', 'foo_auth'] * })); * ``` - * + * * @options {any} [options] Each option Array is used to add additional keys to find an `accessToken` for a `request`. * @property {Array} [cookies] Array of cookie names. * @property {Array} [headers] Array of header names. @@ -1676,8 +1694,17 @@ declare namespace l { * @property {string} [currentUserLiteral] string literal for the current user. * @header loopback.token([options]) */ - - function token(options?: {cookies?: any[], headers?: any[], params?: any[], searchDefaultTokenKeys?: boolean, enableDoublecheck?: boolean, overwriteExistingToken?: boolean, model?: () => void|string, currentUserLiteral?: string}): void; + function token( + options?: { + cookies?: any[], + headers?: any[], + params?: any[], + searchDefaultTokenKeys?: boolean, + enableDoublecheck?: boolean, + overwriteExistingToken?: boolean, + model?: () => void|string, + currentUserLiteral?: string + }): void; /** * Convert any request not handled so far to a 404 error @@ -1714,7 +1741,7 @@ declare namespace l { created: Date; /** Extends the `Model.settings` object. */ - settings: { http: { path: string }; acls: ACL, accessTokenIdLength: number}; + settings: { http: { path: string }; acls: ACL[], accessTokenIdLength: number}; /** * Create a cryptographically random access token id @@ -1811,7 +1838,7 @@ declare namespace l { principalId: string; /** settings Extends the `Model.settings` object. */ - settings: { http: { path: string }; acls: ACL, defaultPermission: 'DENY'}; + settings: { http: { path: string }; acls: ACL[], defaultPermission: 'DENY'}; /** * Check if the request has the permission to access. @@ -1985,7 +2012,7 @@ declare namespace l { * pushSettings.apns.feedbackOptions.port (APNS). * pushSettings.apns.feedbackOptions.batchFeedback (APNS). * pushSettings.apns.feedbackOptions.interval (APNS). - * pushSettings.gcm.serverApiKey: Google Cloud Messaging API key. + * pushSettings.gcm.serverApiKey: Google Cloud Messaging API key. */ pushSetings: { apns: { @@ -2091,14 +2118,14 @@ declare namespace l { /** Model ID. */ modelId: string; - /** + /** * settings Extends the `Model.settings` object. * settings.hashAlgorithm Algorithm used to create cryptographic hash, used as argument * to [crypto.createHash](nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm).Default is sha1. * settings.ignoreErrors By default, when changes are rectified, an error will throw an exception. * However, if this setting is true, then errors will not throw exceptions. */ - settings: { http: { path: string }; acls: ACL; hashAlgorithm: string; ignoreErrors: boolean; }; + settings: { http: { path: string }; acls: ACL[]; hashAlgorithm: string; ignoreErrors: boolean; }; /** * Are both changes deletes? @@ -2260,7 +2287,7 @@ declare namespace l { /** * When two changes conflict a conflict is created * **Note**: call `conflict.fetch()` to get the `target` and `source` models - * + * * @param {*} modelId * @param {PersistedModel} SourceModel * @param {PersistedModel} TargetModel @@ -2337,7 +2364,7 @@ declare namespace l { * Return a new Conflict instance with swapped Source and Target models * This is useful when resolving a conflict in one-way * replication, where the source data must not be changed - * + * * ```js * conflict.swapParties().resolveUsingTarget(cb); * ``` @@ -2349,11 +2376,11 @@ declare namespace l { /** * Determine the conflict type * Possible results ar - * + * * - `Change.UPDATE`: Source and target models were updated * - `Change.DELETE`: Source and or target model was deleted. * - `Change.UNKNOWN`: the conflict type is uknown or due to an erro - * + * * @callback {() => void} callback * @param {Error} err * @param {string} type The conflict type @@ -2402,7 +2429,7 @@ declare namespace l { * } * `` * See github.com/andris9/Nodemailer for other supported options - * + * * @options {any} options See below * @prop {string} from Senders's email address * @prop {string} to List of one or more recipient email addresses (comma-delimited) @@ -2424,19 +2451,19 @@ declare namespace l { /** * Data model for key-value databases. - * @class + * @class */ class KeyValueModel { /** - * Set the TTL (time to live) in ms (milliseconds) for a given key. + * Set the TTL (time to live) in ms (milliseconds) for a given key. * TTL is the remaining time before a key-value pair is discarded from the database. - * - * Callback (Optional) Optional callback. + * + * Callback (Optional) Optional callback. * When the callback function is not provided, a promise is returned instead (see below). - * - * Promise - * this method supports both callback-based and promise-based invocation. + * + * Promise + * this method supports both callback-based and promise-based invocation. * Call this method with no callback argument to get back a promise instead. * @param {string} key Key to use when searching the database. * @param {number} ttl TTL in ms to set for the key. @@ -2448,14 +2475,14 @@ declare namespace l { /** * Return the value associated with a given key. - * + * * Callback (Optional) * Optional callback. When the callback function is not provided, a promise is returned instead (see below). - * + * * Promise - * This method supports both callback-based and promise-based invocation. + * This method supports both callback-based and promise-based invocation. * Call this method with no callback argument to get back a promise instead. - * + * * @param {string} key Key to use when searching the database. * @param {any} options * @param {() => void} callback @@ -2464,8 +2491,8 @@ declare namespace l { static get(key: string, option?: any, callback?: (err: Error, result: any) => void): PromiseLike; /** - * Asynchronously iterate all keys in the database. Similar to .keys() - * but instead allows for iteration over large data sets without having + * Asynchronously iterate all keys in the database. Similar to .keys() + * but instead allows for iteration over large data sets without having * to load everything into memory at once. * Callback example: * ``` @@ -2478,7 +2505,7 @@ declare namespace l { * }); * }); * ``` - * + * * Promise example: * ``` * // Given a model named `Color` with two keys `red` and `blue` @@ -2494,10 +2521,10 @@ declare namespace l { * // key contains `blue` * }); * ``` - * + * * @param {any} filter An optional filter object with the following * @param {string} filter.match Glob string to use to filter returned keys (i.e. userid.*). - * All connectors are required to support * and ?. + * All connectors are required to support * and ?. * They may also support additional special characters that are specific to the backing database. * @param {any} filter.options * @return {any} result AsyncIterator An Object implementing next(cb) -> Promise function that can be used to iterate all keys. @@ -2509,33 +2536,33 @@ declare namespace l { * Return all keys in the database. * WARNING: This method is not suitable for large data sets as all key-values pairs * are loaded into memory at once. For large data sets, use iterateKeys() instead. - * - * This method supports both callback-based and promise-based invocation. + * + * This method supports both callback-based and promise-based invocation. * Call this method with no callback argument to get back a promise instead - * + * * WARNING: this promise implementation will not resolve according to the callback function. - * + * * @param {any} filter An optional filter object with the following - * @param {string} filter.match Glob string used to filter returned keys (i.e. userid.*). - * All connectors are required to support * and ?, but may also support additional special + * @param {string} filter.match Glob string used to filter returned keys (i.e. userid.*). + * All connectors are required to support * and ?, but may also support additional special * characters specific to the database. - * @param {any} filter.options + * @param {any} filter.options * @param {() => void} callback - * @return {PromiseLike} + * @return {PromiseLike} */ static keys(filter: {match: string; options: any}, callback: () => void): PromiseLike; /** * Persist a value and associate it with the given key. - * + * * Callback (Optional) * Optional callback. When the callback function is not provided, a promise is returned instead (see below). - * + * * Promise - * This method supports both callback-based and promise-based invocation. + * This method supports both callback-based and promise-based invocation. * Call this method with no callback argument to get back a promise instead. - * + * * @param {string} key Key to associate with the given value. * @param {any} value Value to persist. * @param {number|any} Optional settings for the key-value pair. If a Number is provided, it is set as the TTL (time to live) in ms (milliseconds) for the key-value pair. @@ -2545,15 +2572,15 @@ declare namespace l { static set(key: string, value: any, options?: number|any, callback?: (err: Error) => void): PromiseLike; /** - * Return the TTL (time to live) for a given key. + * Return the TTL (time to live) for a given key. * TTL is the remaining time before a key-value pair is discarded from the database. - * + * * Callback (Optional) - * Optional callback. When the callback function is not provided, + * Optional callback. When the callback function is not provided, * a promise is returned instead (see below). - * + * * @param {string} key Key to use when searching the database. - * @param {any} options + * @param {any} options * @param {() => void} callback */ @@ -2702,7 +2729,7 @@ declare namespace l { * - ALLOW EVERYONE `logout` * - ALLOW OWNER `findById` * - ALLOW OWNER `updateAttributes` - * + * * @property {string} username Must be unique. * @property {string} password Hidden from remote clients. * @property {string} email Must be valid email. @@ -2724,7 +2751,7 @@ declare namespace l { * @property {number} settings.resetPasswordTokenTTL Time to live for password reset `AccessToken`. Default is `900` (15 minutes). * @property {number} settings.saltWorkFactor The `bcrypt` salt work factor. Default is `10`. * @property {boolean} settings.caseSensitiveEmail Enable case sensitive email. - * + * * @class User * @inherits {PersistedModel} */ @@ -2771,7 +2798,18 @@ declare namespace l { * settings.saltWorkFactor The `bcrypt` salt work factor. Default is `10`. * settings.caseSensitiveEmail Enable case sensitive email. */ - settings: { http: { path: string }; acls: ACL; emailVerificationRequired: boolean; ttl: number; maxTTL: number; realmRequired: boolean; realmDelimiter: string; resetPasswordTokenTTL: number; saltWorkFactor: number; caseSensitiveEmail: boolean; }; + settings: { + http: { path: string }; + acls: ACL[]; + emailVerificationRequired: boolean; + ttl: number; + maxTTL: number; + realmRequired: boolean; + realmDelimiter: string; + resetPasswordTokenTTL: number; + saltWorkFactor: number; + caseSensitiveEmail: boolean; + }; /** * Confirm the user's identity @@ -2798,13 +2836,13 @@ declare namespace l { /** * Login a user by with the given `credentials` - * + * * ```js * User.login({username: 'foo', password: 'bar'}, function (err, token) { * console.log(token.id); * }); * ``` - * + * * @param {any} credentials username/password or email/password * @param {string[]|string} [include] Optionally set it to "user" to include * the user info @@ -2817,13 +2855,13 @@ declare namespace l { /** * Logout a user with the given accessToken id - * + * * ```js * User.logout('asd0a9f8dsj9s0s3223mk', function (err) { * console.log(err || 'Logged out'); * }); * ``` - * + * * @param {string} accessTokenID * @callback {() => void} callback * @param {Error} er @@ -2884,10 +2922,10 @@ declare namespace l { * redirect: '/', * tokenGenerator: function (user, cb) { cb("random-token"); } * }; - * + * * user.verify(options, next); * ``` - * + * * @options {any} options * @property {string} type Must be 'email'. * @property {string} to Email address to which verification email is sent. diff --git a/loopback/loopback-tests.ts b/loopback/loopback-tests.ts index 0c05a377df..b21bf8c759 100644 --- a/loopback/loopback-tests.ts +++ b/loopback/loopback-tests.ts @@ -1,4 +1,3 @@ -/// import * as loopback from 'loopback'; import * as cookieParser from 'cookie-parser'; @@ -13,7 +12,7 @@ class Server { this.app.use(cookieParser()); - this.app.start = function() { + this.app.start = () => { // start the web server }; } diff --git a/loopback/tslint.json b/loopback/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/loopback/tslint.json +++ b/loopback/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lorem-ipsum/tsconfig.json b/lorem-ipsum/tsconfig.json index 7e756f052b..e337082e32 100644 --- a/lorem-ipsum/tsconfig.json +++ b/lorem-ipsum/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "lorem-ipsum-tests.ts" ] -} +} \ No newline at end of file diff --git a/ltx/index.d.ts b/ltx/index.d.ts new file mode 100644 index 0000000000..c5794f12bb --- /dev/null +++ b/ltx/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for ltx 2.6 +// Project: github.com/node-xmpp/ltx/ +// Definitions by: PJakcson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export {Element} from './lib/Element' +export {nameEqual, attrsEqual, childrenEqual, equal} from './lib/equal'; +export {isNode, isElement, isText} from './lib/is'; +export {clone} from './lib/clone'; +export {createElement} from './lib/createElement'; +export {escapeXML, unescapeXML, escapeXMLText, unescapeXMLText} from './lib/escape'; +export {Parser} from './lib/Parser'; +export {parse} from './lib/parse'; +export {tag} from './lib/tag'; +export {tagString} from './lib/tagString'; +export {stringify} from './lib/stringify'; diff --git a/ltx/lib/Element.d.ts b/ltx/lib/Element.d.ts new file mode 100644 index 0000000000..d0f50ae783 --- /dev/null +++ b/ltx/lib/Element.d.ts @@ -0,0 +1,119 @@ +/** + * Element + * + * Attributes are in the element.attrs object. Children is a list of + * either other Elements or Strings for text content. + **/ +export declare class Element { + name: string; + parent: Element; + children: Element[]; + attrs: any; + + constructor(name: string, attrs?: any); + + /** + * if (element.is('message', 'jabber:client')) ... + **/ + is(name: string, xmlns?: any): boolean; + + /** + * without prefix. + */ + getName(): string; + + /** + * retrieves the namespace of the current element, upwards recursively + **/ + getNS(): any; + + /** + * find the namespace to the given prefix, upwards recursively + **/ + findNS(prefix: string): any; + + /** + * Recursiverly gets all xmlns defined, in the form of {url:prefix} + **/ + getXmlns(): any; + + setAttrs(attrs: any): void; + + /** + * xmlns can be null, returns the matching attribute. + **/ + getAttr(name: string, xmlns?: any): any; + + /** + * xmlns can be null + **/ + getChild(name: string, xmlns?: any): Element; + + /** + * xmlns can be null + **/ + getChildren(name: string, xmlns?: any): Element[]; + + /** + * xmlns and recursive can be null + **/ + getChildByAttr(attr: any, val: any, xmlns?: any, recursive?: any): Element; + + + /** + * xmlns and recursive can be null + **/ + getChildrenByAttr(attr: any, val: any, xmlns?: any, recursive?: any): Element[]; + + getText(): string; + + getChildText(name: string, xmlns: any): string; + + /** + * Return all direct descendents that are Elements. + * This differs from `getChildren` in that it will exclude text nodes, + * processing instructions, etc. + */ + getChildElements(): Element[]; + + /** returns uppermost parent */ + root(): Element; + + tree(): Element; + + /** just parent or itself */ + up(): Element; + + /** create child node and return it */ + c(name: string, attrs?: any): Element; + + /** add text node and return element */ + t(text: string): Element; + + /** + * Either: + * el.remove(childEl) + * el.remove('author', 'urn:...') + */ + remove(el: Element, xmlns?: any): Element; + + clone(): Element; + + text(val: string): string; + + attr(attr: any, val: any): any; + + toString(): string; + + toJSON(): any; + + write(writer: any): void; + + nameEquals(el: Element): boolean; + + attrsEquals(el: Element): boolean; + + childrenEquals(el: Element): boolean; + + equals(el: Element): boolean; +} diff --git a/ltx/lib/Parser.d.ts b/ltx/lib/Parser.d.ts new file mode 100644 index 0000000000..3af418d21f --- /dev/null +++ b/ltx/lib/Parser.d.ts @@ -0,0 +1,5 @@ +/// +import {EventEmitter} from 'events'; +export declare class Parser extends EventEmitter { + constructor(options?: any); +} diff --git a/ltx/lib/clone.d.ts b/ltx/lib/clone.d.ts new file mode 100644 index 0000000000..41193a3f40 --- /dev/null +++ b/ltx/lib/clone.d.ts @@ -0,0 +1 @@ +export declare function clone(el: any): any; diff --git a/ltx/lib/createElement.d.ts b/ltx/lib/createElement.d.ts new file mode 100644 index 0000000000..2deead1663 --- /dev/null +++ b/ltx/lib/createElement.d.ts @@ -0,0 +1,2 @@ +import {Element} from './Element'; +export declare function createElement(name: string, attrs: any): Element; diff --git a/ltx/lib/equal.d.ts b/ltx/lib/equal.d.ts new file mode 100644 index 0000000000..520555e098 --- /dev/null +++ b/ltx/lib/equal.d.ts @@ -0,0 +1,4 @@ +export declare function nameEqual(a: any, b: any): boolean; +export declare function attrsEqual(a: any, b: any): boolean; +export declare function childrenEqual(a: any, b: any): boolean; +export declare function equal(a: any, b: any): boolean; diff --git a/ltx/lib/escape.d.ts b/ltx/lib/escape.d.ts new file mode 100644 index 0000000000..4bc45c223a --- /dev/null +++ b/ltx/lib/escape.d.ts @@ -0,0 +1,4 @@ +export declare function escapeXML(s: string): string; +export declare function unescapeXML(s: string): string; +export declare function escapeXMLText(s: string): string; +export declare function unescapeXMLText(s: string): string; diff --git a/ltx/lib/is.d.ts b/ltx/lib/is.d.ts new file mode 100644 index 0000000000..6515d23f80 --- /dev/null +++ b/ltx/lib/is.d.ts @@ -0,0 +1,3 @@ +export declare function isNode(el: any): boolean; +export declare function isElement(el: any): boolean; +export declare function isText(el: any): boolean; diff --git a/ltx/lib/parse.d.ts b/ltx/lib/parse.d.ts new file mode 100644 index 0000000000..cc4073113a --- /dev/null +++ b/ltx/lib/parse.d.ts @@ -0,0 +1 @@ +export declare function parse(data: any, options?: any): any; diff --git a/ltx/lib/stringify.d.ts b/ltx/lib/stringify.d.ts new file mode 100644 index 0000000000..770f7d324f --- /dev/null +++ b/ltx/lib/stringify.d.ts @@ -0,0 +1 @@ +export declare function stringify(el: any, indent: any, level: any): string; diff --git a/ltx/lib/tag.d.ts b/ltx/lib/tag.d.ts new file mode 100644 index 0000000000..8bbcb6fe7b --- /dev/null +++ b/ltx/lib/tag.d.ts @@ -0,0 +1 @@ +export declare function tag(d: any): any; diff --git a/ltx/lib/tagString.d.ts b/ltx/lib/tagString.d.ts new file mode 100644 index 0000000000..44036ce037 --- /dev/null +++ b/ltx/lib/tagString.d.ts @@ -0,0 +1 @@ +export declare function tagString(d: any): string; diff --git a/ltx/ltx-tests.ts b/ltx/ltx-tests.ts new file mode 100644 index 0000000000..a207efb4b7 --- /dev/null +++ b/ltx/ltx-tests.ts @@ -0,0 +1,16 @@ +import * as ltx from './index'; + +ltx.parse(''); + +let p = new ltx.Parser(); + +p.on('tree', (ignored: any) => {}); + +p.on('error', (ignored: any) => {}); + +let el = new ltx.Element('root').c('children'); +el.c('child', {age: 5}).t('Hello').up() + .c('child', {age: 7}).t('Hello').up() + .c('child', {age: 99}).t('Hello').up(); + +el.root().toString(); diff --git a/gaea-model/tsconfig.json b/ltx/tsconfig.json similarity index 86% rename from gaea-model/tsconfig.json rename to ltx/tsconfig.json index 05d346427a..28beec26d4 100644 --- a/gaea-model/tsconfig.json +++ b/ltx/tsconfig.json @@ -1,10 +1,12 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, - "strictNullChecks": true, "noImplicitThis": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -15,6 +17,6 @@ }, "files": [ "index.d.ts", - "gaea-model-tests.ts" + "ltx-tests.ts" ] } diff --git a/ltx/tslint.json b/ltx/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/ltx/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/lz-string/tslint.json b/lz-string/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/lz-string/tslint.json +++ b/lz-string/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/magnet-uri/magnet-uri-tests.ts b/magnet-uri/magnet-uri-tests.ts index ee97fb3451..aba247b19c 100644 --- a/magnet-uri/magnet-uri-tests.ts +++ b/magnet-uri/magnet-uri-tests.ts @@ -1,6 +1,7 @@ import * as magnet from 'magnet-uri'; // "Leaves of Grass" by Walt Whitman +// tslint:disable-next-line:max-line-length const uri = 'magnet:?xt=urn:btih:d2474e86c95b19b8bcfdb92bc12c9d44667cfa36&dn=Leaves+of+Grass+by+Walt+Whitman.epub&tr=udp%3A%2F%2Ftracker.example4.com%3A80&tr=udp%3A%2F%2Ftracker.example5.com%3A80&tr=udp%3A%2F%2Ftracker.example3.com%3A6969&tr=udp%3A%2F%2Ftracker.example2.com%3A80&tr=udp%3A%2F%2Ftracker.example1.com%3A1337'; const parsed = magnet.decode(uri); diff --git a/magnet-uri/tslint.json b/magnet-uri/tslint.json index ec365f164b..377cc837d4 100644 --- a/magnet-uri/tslint.json +++ b/magnet-uri/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/mailgen/mailgen-tests.ts b/mailgen/mailgen-tests.ts index 87d04ee943..fd9429b770 100644 --- a/mailgen/mailgen-tests.ts +++ b/mailgen/mailgen-tests.ts @@ -1,4 +1,4 @@ -import * as Mailgen from "mailgen" +import * as Mailgen from "mailgen"; const generator: Mailgen = new Mailgen({ theme: "default", @@ -8,7 +8,7 @@ const generator: Mailgen = new Mailgen({ } }); -let content: Mailgen.Content = { +const content: Mailgen.Content = { body: { name: "Hi", intro: "test", diff --git a/maker.js/index.d.ts b/maker.js/index.d.ts index ad06d7eb91..ff6a7bd69e 100644 --- a/maker.js/index.d.ts +++ b/maker.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Maker.js 0.9.31 +// Type definitions for Maker.js 0.9.33 // Project: https://github.com/Microsoft/maker.js // Definitions by: Dan Marshall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -66,6 +66,17 @@ declare namespace MakerJs { * @returns String of the flattened array. */ function createRouteKey(route: string[]): string; + /** + * Travel along a route inside of a model to extract a specific node in its tree. + * + * @param modelContext Model to travel within. + * @param routeKeyOrRoute String of a flattened route, or a string array of route segments. + * @returns Model or Path object within the modelContext tree. + */ + function travel(modelContext: IModel, routeKeyOrRoute: string | string[]): { + path: IPath | IModel; + offset: IPoint; + }; /** * Clone an object. * @@ -139,6 +150,15 @@ declare namespace MakerJs { */ high: IPoint; } + /** + * A measurement of extents, with a center point. + */ + interface IMeasureWithCenter extends IMeasure { + /** + * The center point of the rectangle containing the item being measured. + */ + center: IPoint; + } /** * A map of measurements. */ @@ -926,7 +946,7 @@ declare namespace MakerJs.path { * * @param pathToMove The path to move. * @param origin The new origin for the path. - * @returns The original path (for chaining). + * @returns The original path (for cascading). */ function move(pathToMove: IPath, origin: IPoint): IPath; /** @@ -935,7 +955,7 @@ declare namespace MakerJs.path { * @param pathToMove The path to move. * @param delta The x & y adjustments as a point object. * @param subtract Optional boolean to subtract instead of add. - * @returns The original path (for chaining). + * @returns The original path (for cascading). */ function moveRelative(pathToMove: IPath, delta: IPoint, subtract?: boolean): IPath; /** @@ -952,7 +972,7 @@ declare namespace MakerJs.path { * @param pathToRotate The path to rotate. * @param angleInDegrees The amount of rotation, in degrees. * @param rotationOrigin The center point of rotation. - * @returns The original path (for chaining). + * @returns The original path (for cascading). */ function rotate(pathToRotate: IPath, angleInDegrees: number, rotationOrigin?: IPoint): IPath; /** @@ -960,7 +980,7 @@ declare namespace MakerJs.path { * * @param pathToScale The path to scale. * @param scaleValue The amount of scaling. - * @returns The original path (for chaining). + * @returns The original path (for cascading). */ function scale(pathToScale: IPath, scaleValue: number): IPath; /** @@ -1215,11 +1235,11 @@ declare namespace MakerJs.model { */ function mirror(modelToMirror: IModel, mirrorX: boolean, mirrorY: boolean): IModel; /** - * Move a model to an absolute point. Note that this is also accomplished by directly setting the origin property. This function exists for chaining. + * Move a model to an absolute point. Note that this is also accomplished by directly setting the origin property. This function exists for cascading. * * @param modelToMove The model to move. * @param origin The new position of the model. - * @returns The original model (for chaining). + * @returns The original model (for cascading). */ function move(modelToMove: IModel, origin: IPoint): IModel; /** @@ -1227,7 +1247,7 @@ declare namespace MakerJs.model { * * @param modelToMove The model to move. * @param delta The x & y adjustments as a point object. - * @returns The original model (for chaining). + * @returns The original model (for cascading). */ function moveRelative(modelToMove: IModel, delta: IPoint): IModel; /** @@ -1235,7 +1255,7 @@ declare namespace MakerJs.model { * * @param modelToPrefix The model to prefix. * @param prefix The prefix to prepend on paths ids. - * @returns The original model (for chaining). + * @returns The original model (for cascading). */ function prefixPathIds(modelToPrefix: IModel, prefix: string): IModel; /** @@ -1244,7 +1264,7 @@ declare namespace MakerJs.model { * @param modelToRotate The model to rotate. * @param angleInDegrees The amount of rotation, in degrees. * @param rotationOrigin The center point of rotation. - * @returns The original model (for chaining). + * @returns The original model (for cascading). */ function rotate(modelToRotate: IModel, angleInDegrees: number, rotationOrigin?: IPoint): IModel; /** @@ -1253,7 +1273,7 @@ declare namespace MakerJs.model { * @param modelToScale The model to scale. * @param scaleValue The amount of scaling. * @param scaleOrigin Optional boolean to scale the origin point. Typically false for the root model. - * @returns The original model (for chaining). + * @returns The original model (for cascading). */ function scale(modelToScale: IModel, scaleValue: number, scaleOrigin?: boolean): IModel; /** @@ -1261,7 +1281,7 @@ declare namespace MakerJs.model { * * @param modeltoConvert The model to convert. * @param destUnitType The unit system. - * @returns The scaled model (for chaining). + * @returns The scaled model (for cascading). */ function convertUnits(modeltoConvert: IModel, destUnitType: string): IModel; /** @@ -1373,7 +1393,7 @@ declare namespace MakerJs.model { * * @param modelContext The originated model to search for similar paths. * @param options Optional options object. - * @returns The simplified model (for chaining). + * @returns The simplified model (for cascading). */ function simplify(modelToSimplify: IModel, options?: ISimplifyOptions): IModel; } @@ -1478,7 +1498,7 @@ declare namespace MakerJs.measure { * @param baseMeasure The measurement to increase. * @param addMeasure The additional measurement. * @param addOffset Optional offset point of the additional measurement. - * @returns The increased original measurement (for chaining). + * @returns The increased original measurement (for cascading). */ function increase(baseMeasure: IMeasure, addMeasure: IMeasure): IMeasure; /** @@ -1583,7 +1603,7 @@ declare namespace MakerJs.measure { * @param atlas Optional atlas to save measurements. * @returns object with low and high points. */ - function modelExtents(modelToMeasure: IModel, atlas?: measure.Atlas): IMeasure; + function modelExtents(modelToMeasure: IModel, atlas?: measure.Atlas): IMeasureWithCenter; /** * A list of maps of measurements. * @@ -1612,6 +1632,22 @@ declare namespace MakerJs.measure { constructor(modelContext: IModel); measureModels(): void; } + /** + * A hexagon which surrounds a model. + */ + interface IBoundingHex extends IModel { + /** + * Radius of the hexagon, which is also the length of a side. + */ + radius: number; + } + /** + * Measures the minimum bounding hexagon surrounding a model. The hexagon is oriented such that the right and left sides are vertical, and the top and bottom are pointed. + * + * @param modelToMeasure The model to measure. + * @returns IBoundingHex object which is a hexagon model, with an additional radius property. + */ + function boundingHexagon(modelToMeasure: IModel): IBoundingHex; } declare namespace MakerJs.exporter { /** @@ -1787,6 +1823,29 @@ declare namespace MakerJs.model { function findChains(modelContext: IModel, callback: IChainCallback, options?: IFindChainsOptions): void; } declare namespace MakerJs.chain { + /** + * Shift the links of an endless chain. + * + * @param chainContext Chain to cycle through. Must be endless. + * @param amount Optional number of links to shift. May be negative to cycle backwards. + * @returns The chainContext for cascading. + */ + function cycle(chainContext: IChain, amount?: number): IChain; + /** + * Reverse the links of a chain. + * + * @param chainContext Chain to reverse. + * @returns The chainContext for cascading. + */ + function reverse(chainContext: IChain): IChain; + /** + * Set the beginning of an endless chain to a known routeKey of a path. + * + * @param chainContext Chain to cycle through. Must be endless. + * @param routeKey RouteKey of the desired path to start the chain with. + * @returns The chainContext for cascading. + */ + function startAt(chainContext: IChain, routeKey: string): IChain; /** * Get points along a chain of paths. * @@ -1825,7 +1884,7 @@ declare namespace MakerJs.model { * * @param modelContext The model to search for dead ends. * @param options Optional options object. - * @returns The input model (for chaining). + * @returns The input model (for cascading). */ function removeDeadEnds(modelContext: IModel, pointMatchingDistance?: any, keep?: IWalkPathBooleanCallback): IModel; } @@ -2123,6 +2182,18 @@ declare namespace MakerJs.models { * @param numericList String containing a list of numbers which can be delimited by spaces, commas, or anything non-numeric (Note: [exponential notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) is allowed). */ constructor(numericList: string); + /** + * Create a model by connecting points designated in a string. The model will be 'closed' - i.e. the last point will connect to the first point. + * + * Example: + * ``` + * var c = new makerjs.models.ConnectTheDots(false, '-10 0 10 0 0 20'); // 3 coordinates to form a polyline + * ``` + * + * @param isClosed Flag to specify if last point should connect to the first point. + * @param numericList String containing a list of numbers which can be delimited by spaces, commas, or anything non-numeric (Note: [exponential notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) is allowed). + */ + constructor(isClosed: boolean, numericList: string); /** * Create a model by connecting points designated in a numeric array. The model will be 'closed' - i.e. the last point will connect to the first point. * @@ -2134,6 +2205,18 @@ declare namespace MakerJs.models { * @param coords Array of coordinates. */ constructor(coords: number[]); + /** + * Create a model by connecting points designated in a numeric array. The model will be 'closed' - i.e. the last point will connect to the first point. + * + * Example: + * ``` + * var c = new makerjs.models.ConnectTheDots(false, [-10, 0, 10, 0, 0, 20]); // 3 coordinates to form a polyline + * ``` + * + * @param isClosed Flag to specify if last point should connect to the first point. + * @param coords Array of coordinates. + */ + constructor(isClosed: boolean, coords: number[]); /** * Create a model by connecting points designated in an array of points. The model may be closed, or left open. * diff --git a/maker.js/maker.js-tests.ts b/maker.js/maker.js-tests.ts index 4c7dbc25f0..f5f9d9db16 100644 --- a/maker.js/maker.js-tests.ts +++ b/maker.js/maker.js-tests.ts @@ -51,6 +51,7 @@ function test() { makerjs.isPoint([]); makerjs.pathType.Circle; makerjs.round(44.44444, .01); + makerjs.travel(model, ''); makerjs.unitType.Millimeter; new makerjs.Collector(); } @@ -105,6 +106,7 @@ function test() { } function testMeasure() { + makerjs.measure.boundingHexagon(model).radius; makerjs.measure.increase(mp, mm); makerjs.measure.isPointEqual(p1, p2); makerjs.measure.isPathEqual(paths.line, paths.circle, 4); @@ -123,6 +125,7 @@ function test() { makerjs.measure.pointDistance([0,0], [9,9]); new makerjs.measure.Atlas(model); mm.low[0]; + mm.center; mp.high[1]; var s = makerjs.measure.lineSlope(paths.line); makerjs.measure.isPointOnSlope([], s); @@ -172,6 +175,10 @@ function test() { new makerjs.models.BoltCircle(7, 7, 7, 7), new makerjs.models.BoltRectangle(2, 2, 2), new makerjs.models.ConnectTheDots(true, [ [0,0], [1,1] ]), + new makerjs.models.ConnectTheDots([0, 0, 1, 1]), + new makerjs.models.ConnectTheDots(true, [0, 0, 1, 1]), + new makerjs.models.ConnectTheDots(true, '0, 0, 1, 1'), + new makerjs.models.ConnectTheDots('0, 0, 1, 1'), new makerjs.models.Dogbone(1,1,1), new makerjs.models.Dome(5, 7), new makerjs.models.Ellipse(2,2), @@ -255,7 +262,10 @@ function test() { } function testChain() { + makerjs.chain.cycle(chain, 7); makerjs.chain.fillet(chain, 1); + makerjs.chain.reverse(chain); + makerjs.chain.startAt(chain, ''); makerjs.chain.toKeyPoints(chain); makerjs.chain.toPoints(chain, 1); } diff --git a/mapbox/mapbox-tests.ts b/mapbox/mapbox-tests.ts index aaa7dd1c5f..f336d66e1a 100644 --- a/mapbox/mapbox-tests.ts +++ b/mapbox/mapbox-tests.ts @@ -16,7 +16,7 @@ var marker = L.marker(new L.LatLng([0, 0]), { }).addTo(map); // every time the marker is dragged, update the coordinates container -marker.on('dragend', function() { +marker.on('dragend', () => { var m = marker.getLatLng(); coordinates.innerHTML = 'Latitude: ' + m.lat + '
Longitude: ' + m.lng; }); @@ -29,13 +29,13 @@ var marker2 = L.mapbox.featureLayer({ coordinates: [-73.9840, 40.7271] }, properties: { - title: 'Hello world!', + 'title': 'Hello world!', 'marker-color': '#f86767' } }).addTo(map); // Iterate over the featureLayer we've called "marker" // and open its popup instead of clicking to trigger it. -marker2.eachLayer(function(marker: L.Marker) { +marker2.eachLayer((marker: L.Marker) => { marker.openPopup(); }); \ No newline at end of file diff --git a/mapbox/tslint.json b/mapbox/tslint.json index 0f47deabb4..f05741c59b 100644 --- a/mapbox/tslint.json +++ b/mapbox/tslint.json @@ -3,4 +3,4 @@ "rules": { "forbidden-types": false } -} \ No newline at end of file +} diff --git a/material-ui/index.d.ts b/material-ui/index.d.ts index a2661455f8..41e4c55cc1 100644 --- a/material-ui/index.d.ts +++ b/material-ui/index.d.ts @@ -130,6 +130,7 @@ declare namespace __MaterialUI { accent2Color?: string; accent3Color?: string; textColor?: string; + secondaryTextColor?: string; alternateTextColor?: string; canvasColor?: string; borderColor?: string; @@ -532,7 +533,7 @@ declare namespace __MaterialUI { type cornersAndCenter = 'bottom-center' | 'bottom-left' | 'bottom-right' | 'top-center' | 'top-left' | 'top-right'; } - interface AutoCompleteProps { + interface AutoCompleteProps extends TextFieldProps { anchorOrigin?: propTypes.origin; animated?: boolean; animation?: React.ComponentClass; diff --git a/math3d/math3d-tests.ts b/math3d/math3d-tests.ts index d04ddbefb9..9647038565 100644 --- a/math3d/math3d-tests.ts +++ b/math3d/math3d-tests.ts @@ -1,7 +1,7 @@ import * as math3d from 'math3d'; const v = new math3d.Vector3(1, 2, 3); v.add(new math3d.Vector3(0, 0, 1)); -new math3d.Matrix4x4([1,1,1,1, - 2,2,2,2, - 3,3,3,3, - 4,4,4,4]); +new math3d.Matrix4x4([1, 1, 1, 1, + 2, 2, 2, 2, + 3, 3, 3, 3, + 4, 4, 4, 4]); diff --git a/mem/tslint.json b/mem/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/mem/tslint.json +++ b/mem/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/memoizee/memoizee-tests.ts b/memoizee/memoizee-tests.ts index e8e73a2d6a..c78c240ac9 100644 --- a/memoizee/memoizee-tests.ts +++ b/memoizee/memoizee-tests.ts @@ -1,6 +1,6 @@ import memoize = require('memoizee'); -var fn = function (one: string, two?: number, three?: any) { /* ... */ }; +var fn = (one: string, two?: number, three?: any) => { /* ... */ }; let memoized = memoize(fn); memoized('foo', 3, 'bar'); @@ -18,15 +18,15 @@ memoized('foo', 3, 13); memoized = memoize(fn, { primitive: true }); memoized('/path/one'); memoized('/path/one'); -memoized = memoize(fn, { dispose: function (value:number) { /*…*/ } }); +memoized = memoize(fn, { dispose(value: number) { /*…*/ } }); var foo3 = memoized('foo', 3); var bar7 = memoized('bar', 7); memoized.clear('foo', 3); // Dispose called with foo3 value memoized.clear('bar', 7); // Dispose called with bar7 value memoized.delete('foo', 0); -var mFn = memoize(function (hash:any) { +var mFn = memoize((hash: any) => { // body of memoized function -}, { normalizer: function (args:any) { +}, { normalizer: (args: any) => { // args is arguments object as accessible in memoized function return JSON.stringify(args[0]); } }); @@ -34,15 +34,15 @@ var mFn = memoize(function (hash:any) { mFn({ foo: 'bar' }); memoized = memoize(fn, { length: 2, resolvers: [String, Boolean] }); -memoized(String(12), [1,2,3].length); +memoized(String(12), [1, 2, 3].length); memoized("12", Number(true)); -memoized(String({ toString: function () { return "12"; } }), Number({})); +memoized(String({ toString() { return "12"; } }), Number({})); { - var afn = function (a:number, b:number) { - return new Promise(function (res) { res(a + b); }); + var afn = (a: number, b: number) => { + return new Promise(res => { res(a + b); }); }; - let memoized = memoize(afn, { promise: true }); + const memoized = memoize(afn, { promise: true }); memoized(3, 7); memoized(3, 7); } @@ -52,10 +52,10 @@ memoized = memoize(fn, { maxAge: 1000, preFetch: 0.6 }); memoized('foo', 3); memoized('foo', 3); -setTimeout(function () { +setTimeout(() => { memoized('foo', 3); }, 500); -setTimeout(function () { +setTimeout(() => { memoized('foo', 3); }, 1300); diff --git a/memoizee/tslint.json b/memoizee/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/memoizee/tslint.json +++ b/memoizee/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/meow/tslint.json b/meow/tslint.json index f9e30021f4..377cc837d4 100644 --- a/meow/tslint.json +++ b/meow/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/merge-descriptors/index.d.ts b/merge-descriptors/index.d.ts index d9ccc201a1..82ded472b0 100644 --- a/merge-descriptors/index.d.ts +++ b/merge-descriptors/index.d.ts @@ -1,12 +1,7 @@ -// Type definitions for merge-descriptors +// Type definitions for merge-descriptors 1.0 // Project: https://github.com/component/merge-descriptors // Definitions by: Zhiyuan Wang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -declare function merge(destination: Object, source: Object): Object; - -declare function merge(destination: Object, source: Object, redefine: boolean): Object; - +declare function merge(destination: Object, source: Object, redefine?: boolean): Object; export = merge; diff --git a/merge-descriptors/merge-descriptors-tests.ts b/merge-descriptors/merge-descriptors-tests.ts index ca2e326f3b..df8f444fa9 100644 --- a/merge-descriptors/merge-descriptors-tests.ts +++ b/merge-descriptors/merge-descriptors-tests.ts @@ -6,7 +6,7 @@ function testAssertion(condition: boolean, errorMessage: string) { } } -interface IMergedObject { +interface MergedObject { InSrc?: string; name: string; InTarget: string; @@ -17,9 +17,9 @@ var src = { get name(): string { return 'from src name'; } -} +}; -var target: IMergedObject = { name: 'my target name', InTarget: 'target' }; +var target: MergedObject = { name: 'my target name', InTarget: 'target' }; var target2 = mixin(target, src, true); @@ -30,5 +30,5 @@ testAssertion(target.name === 'from src name', "[redfine]=true, source member wi testAssertion(target.InTarget === 'target', "overwrite do not affect members only in [destination]"); testAssertion(target['InSrc'] === 'src', "members from [source] must be copied to [destination]"); -var nameProperty:PropertyDescriptor = Object.getOwnPropertyDescriptor(target, "name"); +var nameProperty: PropertyDescriptor = Object.getOwnPropertyDescriptor(target, "name"); testAssertion(nameProperty.set === undefined, "member descriptor must be overwritten"); \ No newline at end of file diff --git a/merge-descriptors/tsconfig.json b/merge-descriptors/tsconfig.json index 50246ffb88..4e224b187b 100644 --- a/merge-descriptors/tsconfig.json +++ b/merge-descriptors/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/merge-descriptors/tslint.json b/merge-descriptors/tslint.json new file mode 100644 index 0000000000..f05741c59b --- /dev/null +++ b/merge-descriptors/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/meteor-collection-hooks/meteor-collection-hooks-tests.ts b/meteor-collection-hooks/meteor-collection-hooks-tests.ts index 43efa16e3e..b8c0c63247 100644 --- a/meteor-collection-hooks/meteor-collection-hooks-tests.ts +++ b/meteor-collection-hooks/meteor-collection-hooks-tests.ts @@ -15,38 +15,38 @@ const selector = { limit: 5, fields: { createdAt: 1 }, reacrive: true, - transform: function () {} + transform: () => {} }; -Collection.before.find(function (userId: string, selector: Mongo.Selector, options: { multi?: boolean; upsert?: boolean; }): void {}); -Collection.before.findOne(function (userId: string, selector: Mongo.Selector, options: { multi?: boolean; upsert?: boolean; }): void {}); -Collection.before.insert(function (userId: string, doc: Model): void {}); -Collection.before.remove(function (userId: string, doc: Model): void {}); -Collection.before.update(function (userId: string, doc: Model, fieldNames: string[], modifier: Mongo.Modifier, options: { multi?: boolean; upsert?: boolean; }): void {}); -Collection.before.upsert(function (userId: string, doc: Model, selector: Mongo.Selector, modifier: Mongo.Modifier, options: { multi?: boolean; upsert?: boolean; }): void {}); +Collection.before.find((userId: string, selector: Mongo.Selector, options: { multi?: boolean; upsert?: boolean; }) => {}); +Collection.before.findOne((userId: string, selector: Mongo.Selector, options: { multi?: boolean; upsert?: boolean; }) => {}); +Collection.before.insert((userId: string, doc: Model) => {}); +Collection.before.remove((userId: string, doc: Model) => {}); +Collection.before.update((userId: string, doc: Model, fieldNames: string[], modifier: Mongo.Modifier, options: { multi?: boolean; upsert?: boolean; }) => {}); +Collection.before.upsert((userId: string, doc: Model, selector: Mongo.Selector, modifier: Mongo.Modifier, options: { multi?: boolean; upsert?: boolean; }) => {}); -Collection.after.find(function (userId: string, selector: Mongo.Selector, options: { multi?: boolean; upsert?: boolean; }, cursor: Mongo.Cursor): void {}); -Collection.after.findOne(function (userId: string, selector: Mongo.Selector, options: { multi?: boolean; upsert?: boolean; }, doc: Model): void {}); -Collection.after.insert(function (userId: string, doc: Model): void {}); -Collection.after.remove(function (userId: string, doc: Model): void {}); -Collection.after.update(function (userId: string, doc: Model, fieldNames: string[], modifier: Mongo.Modifier, options: { multi?: boolean; upsert?: boolean; }): void {}, { fetchPrevious: true }); -Collection.after.upsert(function (userId: string, doc: Model, selector: Mongo.Selector, modifier: Mongo.Modifier, options: { multi?: boolean; upsert?: boolean; }): void {}); +Collection.after.find((userId: string, selector: Mongo.Selector, options: { multi?: boolean; upsert?: boolean; }, cursor: Mongo.Cursor) => {}); +Collection.after.findOne((userId: string, selector: Mongo.Selector, options: { multi?: boolean; upsert?: boolean; }, doc: Model) => {}); +Collection.after.insert((userId: string, doc: Model) => {}); +Collection.after.remove((userId: string, doc: Model) => {}); +Collection.after.update((userId: string, doc: Model, fieldNames: string[], modifier: Mongo.Modifier, options: { multi?: boolean; upsert?: boolean; }) => {}, { fetchPrevious: true }); +Collection.after.upsert((userId: string, doc: Model, selector: Mongo.Selector, modifier: Mongo.Modifier, options: { multi?: boolean; upsert?: boolean; }) => {}); -cursor = Collection.direct.find({ _id: doc._id }, { sort: { createdAt: -1 }, skip: 5, limit: 5, fields: { createdAt: 1 }, reactive: true, transform: function () {} }); -cursor = Collection.direct.find(doc._id, { sort: { createdAt: -1 }, skip: 5, limit: 5, fields: { createdAt: 1 }, reactive: true, transform: function () {} }); +cursor = Collection.direct.find({ _id: doc._id }, { sort: { createdAt: -1 }, skip: 5, limit: 5, fields: { createdAt: 1 }, reactive: true, transform: () => {} }); +cursor = Collection.direct.find(doc._id, { sort: { createdAt: -1 }, skip: 5, limit: 5, fields: { createdAt: 1 }, reactive: true, transform: () => {} }); -doc = Collection.direct.findOne({ _id: doc._id }, { sort: { createdAt: -1 }, skip: 5, fields: { createdAt: 1 }, reactive: true, transform: function () {} }); -doc = Collection.direct.findOne(doc._id, { sort: { createdAt: -1 }, skip: 5, fields: { createdAt: 1 }, reactive: true, transform: function () {} }); +doc = Collection.direct.findOne({ _id: doc._id }, { sort: { createdAt: -1 }, skip: 5, fields: { createdAt: 1 }, reactive: true, transform: () => {} }); +doc = Collection.direct.findOne(doc._id, { sort: { createdAt: -1 }, skip: 5, fields: { createdAt: 1 }, reactive: true, transform: () => {} }); -doc._id = Collection.direct.insert(doc, function () {}); +doc._id = Collection.direct.insert(doc, () => {}); -doc.value = Collection.direct.remove({ _id: doc._id }, function () {}); -doc.value = Collection.direct.remove(doc._id, function () {}); +doc.value = Collection.direct.remove({ _id: doc._id }, () => {}); +doc.value = Collection.direct.remove(doc._id, () => {}); -doc.value = Collection.direct.update({ _id: doc._id }, { $inc: { votes: 2 } }, { multi: true, upsert: true }, function () {}); -doc.value = Collection.direct.update(doc._id, { $inc: { votes: 2 } }, { multi: true, upsert: true }, function () {}); +doc.value = Collection.direct.update({ _id: doc._id }, { $inc: { votes: 2 } }, { multi: true, upsert: true }, () => {}); +doc.value = Collection.direct.update(doc._id, { $inc: { votes: 2 } }, { multi: true, upsert: true }, () => {}); -let { numberAffected, insertedId }: { numberAffected?: number; insertedId?: string; } = Collection.direct.upsert(doc._id, { $inc: { votes: 2 } }, { multi: true }, function () {}); +let { numberAffected, insertedId }: { numberAffected?: number; insertedId?: string; } = Collection.direct.upsert(doc._id, { $inc: { votes: 2 } }, { multi: true }, () => {}); Collection.hookOptions = { before: { diff --git a/meteor-collection-hooks/tslint.json b/meteor-collection-hooks/tslint.json index ff73494c7b..0b14fdec0d 100644 --- a/meteor-collection-hooks/tslint.json +++ b/meteor-collection-hooks/tslint.json @@ -1,6 +1,6 @@ { - "extends": "../tslint.json", - "rules": { - "no-single-declare-module": false - } -} \ No newline at end of file + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false + } +} diff --git a/meteor/index.d.ts b/meteor/index.d.ts index e411947122..7a2f85f72b 100644 --- a/meteor/index.d.ts +++ b/meteor/index.d.ts @@ -428,6 +428,7 @@ declare namespace Accounts { function onCreateUser(func: Function): void; function validateLoginAttempt(cb: (params: Accounts.IValidateLoginAttemptCbOpts) => boolean): { stop: () => void }; function validateNewUser(func: Function): boolean; + function _hashPassword(password: string): { digest: string; algorithm: string; }; } declare namespace App { @@ -604,7 +605,7 @@ declare namespace Meteor { function setTimeout(func: Function, delay: number): number; var settings: { public: {[id:string]: any}, private: {[id:string]: any}, [id:string]: any}; function startup(func: Function): void; - function status(): Meteor.StatusEnum; + function status(): DDP.DDPStatus; function subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; function user(): Meteor.User; function userId(): string; diff --git a/mobservable/index.d.ts b/mobservable/index.d.ts index 1fcd580045..719eddaf31 100644 --- a/mobservable/index.d.ts +++ b/mobservable/index.d.ts @@ -1,179 +1,170 @@ -// Type definitions for mobservable v0.6.10 +// Type definitions for mobservable 0.6 // Project: https://mweststrate.github.io/mobservable // Definitions by: Michel Weststrate // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -interface _IMobservableStatic { - /** - * Turns an object, array or function into a reactive structure. - * @param value the value which should become observable. - */ - makeReactive: IMakeReactive; - - /** - * Extends an object with reactive capabilities. - * @param target the object to which reactive properties should be added - * @param properties the properties that should be added and made reactive - * @returns targer - */ - extendReactive(target: Object, properties: Object):Object; - - /** - * Returns true if the provided value is reactive. - * @param value object, function or array - * @param propertyName if propertyName is specified, checkes whether value.propertyName is reactive. - */ - isReactive(value: any, propertyName?:string): boolean; - - /** - * Can be used in combination with makeReactive / extendReactive. - * Enforces that a reference to 'value' is stored as property, - * but that 'value' itself is not turned into something reactive. - * Future assignments to the same property will inherit this behavior. - * @param value initial value of the reactive property that is being defined. - */ - asReference(value: any):{value:T}; - - /** - * ES6 / Typescript decorator which can to make class properties and getter functions reactive. - */ - observable(target: Object, key: string):any; // decorator / annotation - - /** - * Creates a reactive view and keeps it alive, so that the view is always - * updated if one of the dependencies changes, even when the view is not further used by something else. - * @param func The reactive view - * @param scope (optional) - * @returns disposer function, which can be used to stop the view from being updated in the future. - */ - observe(func: Mobservable.Lambda, scope?: any): Mobservable.Lambda; - - /** - * Deprecated, use mobservable.observe instead. - */ - sideEffect(func: Mobservable.Lambda, scope?: any): Mobservable.Lambda; - - /** - * Similar to 'observer', observes the given predicate until it returns true. - * Once it returns true, the 'effect' function is invoked an the observation is cancelled. - * @param predicate - * @param effect - * @param scope (optional) - * @returns disposer function to prematurely end the observer. - */ - observeUntil(predicate: ()=>boolean, effect: Mobservable.Lambda, scope?: any): Mobservable.Lambda; - - /** - * During a transaction no views are updated until the end of the transaction. - * The transaction will be run synchronously nonetheless. - * @param action a function that updates some reactive state - * @returns any value that was returned by the 'action' parameter. - */ - transaction(action: ()=>T): T; - - /** - * Converts a reactive structure into a non-reactive structure. - * Basically a deep-clone. - */ - toJSON(value: T): T; - - /** - * Sets the reporting level Defaults to 1. Use 0 for production or 2 for increased verbosity. - */ - logLevel: number; // 0 = production, 1 = development, 2 = debugging - - extras: { - getDependencyTree(thing:any, property?:string): Mobservable.IDependencyTree; - - getObserverTree(thing:any, property?:string): Mobservable.IObserverTree; - - trackTransitions(extensive?:boolean, onReport?:(lines:Mobservable.ITransitionEvent) => void) : Mobservable.Lambda; - } -} - -interface IMakeReactive { - (value: T[], opts?: Mobservable.IMakeReactiveOptions): Mobservable.IObservableArray; - (value: ()=>T, opts?: Mobservable.IMakeReactiveOptions): Mobservable.IObservableValue; - (value: T, opts?: Mobservable.IMakeReactiveOptions): Mobservable.IObservableValue; - (value: Object, opts?: Mobservable.IMakeReactiveOptions): T; -} - -interface IMobservableStatic extends _IMobservableStatic, IMakeReactive { -} - declare namespace Mobservable { - interface IMakeReactiveOptions { - as?: string /* "auto" | "reference" | TODO: see #8 "structure" */ - scope?: Object, - context?: Object, - recurse?: boolean; + interface Static extends MakeReactive { + /** + * Turns an object, array or function into a reactive structure. + * @param value the value which should become observable. + */ + makeReactive: MakeReactive; + + /** + * Extends an object with reactive capabilities. + * @param target the object to which reactive properties should be added + * @param properties the properties that should be added and made reactive + * @returns targer + */ + extendReactive(target: Object, properties: Object): Object; + + /** + * Returns true if the provided value is reactive. + * @param value object, function or array + * @param propertyName if propertyName is specified, checkes whether value.propertyName is reactive. + */ + isReactive(value: any, propertyName?: string): boolean; + + /** + * Can be used in combination with makeReactive / extendReactive. + * Enforces that a reference to 'value' is stored as property, + * but that 'value' itself is not turned into something reactive. + * Future assignments to the same property will inherit this behavior. + * @param value initial value of the reactive property that is being defined. + */ + asReference(value: any): {value: T}; + + /** + * ES6 / Typescript decorator which can to make class properties and getter functions reactive. + */ + observable(target: Object, key: string): any; // decorator / annotation + + /** + * Creates a reactive view and keeps it alive, so that the view is always + * updated if one of the dependencies changes, even when the view is not further used by something else. + * @param func The reactive view + * @param scope (optional) + * @returns disposer function, which can be used to stop the view from being updated in the future. + */ + observe(func: Mobservable.Lambda, scope?: any): Mobservable.Lambda; + + /** + * Deprecated, use mobservable.observe instead. + */ + sideEffect(func: Mobservable.Lambda, scope?: any): Mobservable.Lambda; + + /** + * Similar to 'observer', observes the given predicate until it returns true. + * Once it returns true, the 'effect' function is invoked an the observation is cancelled. + * @param predicate + * @param effect + * @param scope (optional) + * @returns disposer function to prematurely end the observer. + */ + observeUntil(predicate: () => boolean, effect: Mobservable.Lambda, scope?: any): Mobservable.Lambda; + + /** + * During a transaction no views are updated until the end of the transaction. + * The transaction will be run synchronously nonetheless. + * @param action a function that updates some reactive state + * @returns any value that was returned by the 'action' parameter. + */ + transaction(action: () => T): T; + + /** + * Converts a reactive structure into a non-reactive structure. + * Basically a deep-clone. + */ + toJSON(value: T): T; + + /** + * Sets the reporting level Defaults to 1. Use 0 for production or 2 for increased verbosity. + */ + logLevel: number; // 0 = production, 1 = development, 2 = debugging + + extras: { + getDependencyTree(thing: any, property?: string): Mobservable.DependencyTree; + + getObserverTree(thing: any, property?: string): Mobservable.ObserverTree; + + trackTransitions(extensive?: boolean, onReport?: (lines: Mobservable.TransitionEvent) => void): Mobservable.Lambda; + }; + } + + interface MakeReactive { + (value: T[], opts?: Mobservable.MakeReactiveOptions): Mobservable.ObservableArray; + (value: () => T, opts?: Mobservable.MakeReactiveOptions): Mobservable.ObservableValue; + (value: T, opts?: Mobservable.MakeReactiveOptions): Mobservable.ObservableValue; + (value: Object, opts?: Mobservable.MakeReactiveOptions): T; + } + + interface MakeReactiveOptions { + as?: string; /* "auto" | "reference" | TODO: see #8 "structure" */ + scope?: Object; + context?: Object; + recurse?: boolean; name?: string; - // protected: boolean TODO: see #9 + // protected: boolean TODO: see #9 } - export interface IContextInfoStruct { - object: Object; - name: string; - } - - export type IContextInfo = IContextInfoStruct | string; + type ContextInfo = { object: Object; name: string } | string; interface Lambda { (): void; name?: string; } - interface IObservable { - observe(callback: (...args: any[])=>void, fireImmediately?: boolean): Lambda; + interface Observable { + observe(callback: (...args: any[]) => void, fireImmediately?: boolean): Lambda; } - interface IObservableValue extends IObservable { + interface ObservableValue extends Observable { (): T; - (value: T):void; - observe(callback: (newValue: T, oldValue: T)=>void, fireImmediately?: boolean): Lambda; + (value: T): void; + observe(callback: (newValue: T, oldValue: T) => void, fireImmediately?: boolean): Lambda; } - interface IObservableArray extends IObservable, Array { + interface ObservableArray extends Observable, Array { spliceWithArray(index: number, deleteCount?: number, newItems?: T[]): T[]; - observe(listener: (changeData: IArrayChange|IArraySplice)=>void, fireImmediately?: boolean): Lambda; + observe(listener: (changeData: ArrayChange|ArraySplice) => void, fireImmediately?: boolean): Lambda; clear(): T[]; replace(newItems: T[]): T[]; - find(predicate: (item: T,index: number,array: IObservableArray)=>boolean,thisArg?: any,fromIndex?: number): T; + find(predicate: (item: T, index: number, array: ObservableArray) => boolean, thisArg?: any, fromIndex?: number): T; remove(value: T): boolean; } - interface IArrayChange { - type: string; // Always: 'update' - object: IObservableArray; - index: number; - oldValue: T; + interface ArrayChange { + type: string; // Always: 'update' + object: ObservableArray; + index: number; + oldValue: T; } - interface IArraySplice { - type: string; // Always: 'splice' - object: IObservableArray; - index: number; - removed: T[]; - addedCount: number; + interface ArraySplice { + type: string; // Always: 'splice' + object: ObservableArray; + index: number; + removed: T[]; + addedCount: number; } - interface IDependencyTree { + interface DependencyTree { id: number; name: string; context: any; - dependencies?: IDependencyTree[]; + dependencies?: DependencyTree[]; } - interface IObserverTree { + interface ObserverTree { id: number; name: string; context: any; - observers?: IObserverTree[]; + observers?: ObserverTree[]; listeners?: number; // amount of functions manually attached using an .observe method } - interface ITransitionEvent { + interface TransitionEvent { id: number; name: string; context: Object; @@ -183,7 +174,5 @@ declare namespace Mobservable { } } -declare module "mobservable" { - var m : IMobservableStatic; - export = m; -} +declare const Mobservable: Mobservable.Static; +export = Mobservable; diff --git a/mobservable/mobservable-tests.ts b/mobservable/mobservable-tests.ts index 07088d5d87..060f0d14b3 100644 --- a/mobservable/mobservable-tests.ts +++ b/mobservable/mobservable-tests.ts @@ -4,12 +4,12 @@ import {observable} from "mobservable"; var v = mobservable(3); v.observe(() => {}); -var a = mobservable([1,2,3]); +var a = mobservable([1, 2, 3]); class Order { - @observable price:number = 3; - @observable amount:number = 2; - @observable orders:string[] = []; + @observable price: number = 3; + @observable amount: number = 2; + @observable orders: string[] = []; @observable get total() { return this.amount * this.price * (1 + this.orders.length); @@ -22,12 +22,12 @@ export function testObservable() { } export function testAnnotations() { - var order1totals:number[] = []; + var order1totals: number[] = []; var order1 = new Order(); var order2 = new Order(); var disposer = mobservable.observe(() => { - order1totals.push(order1.total) + order1totals.push(order1.total); }); order2.price = 4; @@ -35,22 +35,22 @@ export function testAnnotations() { order2.orders.push('bla'); - order1.orders.splice(0,0,'boe', 'hoi'); + order1.orders.splice(0, 0, 'boe', 'hoi'); disposer(); order1.orders.pop(); }; export function testTyping() { - var ar:Mobservable.IObservableArray = mobservable.makeReactive([1,2]); - ar.observe((d:Mobservable.IArrayChange|Mobservable.IArraySplice) => { + var ar: mobservable.ObservableArray = mobservable.makeReactive([1, 2]); + ar.observe((d: mobservable.ArrayChange | mobservable.ArraySplice) => { console.log(d.type); }); - var ar2:Mobservable.IObservableArray = mobservable([1,2]); - ar2.observe((d:Mobservable.IArrayChange|Mobservable.IArraySplice) => { + var ar2: mobservable.ObservableArray = mobservable([1, 2]); + ar2.observe((d: mobservable.ArrayChange | mobservable.ArraySplice) => { console.log(d.type); }); - var x:Mobservable.IObservableValue = mobservable(3); + var x: mobservable.ObservableValue = mobservable(3); } \ No newline at end of file diff --git a/mobservable/tsconfig.json b/mobservable/tsconfig.json index 26c2a7df47..cee6db4b01 100644 --- a/mobservable/tsconfig.json +++ b/mobservable/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/mobservable/tslint.json b/mobservable/tslint.json new file mode 100644 index 0000000000..f05741c59b --- /dev/null +++ b/mobservable/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/mock-raf/index.d.ts b/mock-raf/index.d.ts index 4d87655042..bbcbe5e444 100644 --- a/mock-raf/index.d.ts +++ b/mock-raf/index.d.ts @@ -17,7 +17,10 @@ declare namespace MockRaf { /** Creates a mockRaf instance, exposing the functions you'll use to interact with the mock. */ interface Creator { - /** Returns the current now value of the mock. Starts at 0 and increases with each step() taken. Useful for stubbing out performance.now() or a polyfill when using requestAnimationFrame with timers. */ + /** + * Returns the current now value of the mock. Starts at 0 and increases with each step() taken. + * Useful for stubbing out performance.now() or a polyfill when using requestAnimationFrame with timers. + */ now(): number; /** Replacement for requestAnimationFrame or a polyfill.Adds a callback to be fired on the next step. */ diff --git a/mock-raf/tsconfig.json b/mock-raf/tsconfig.json index d035910a65..7d4b6c5a8e 100644 --- a/mock-raf/tsconfig.json +++ b/mock-raf/tsconfig.json @@ -1,20 +1,23 @@ { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "mock-raf-tests.ts" - ] + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mock-raf-tests.ts" + ] } \ No newline at end of file diff --git a/mock-raf/tslint.json b/mock-raf/tslint.json index fdc7cdc370..377cc837d4 100644 --- a/mock-raf/tslint.json +++ b/mock-raf/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/modernizr/modernizr-tests.ts b/modernizr/modernizr-tests.ts index 1807a5f377..3e62ae478e 100644 --- a/modernizr/modernizr-tests.ts +++ b/modernizr/modernizr-tests.ts @@ -2,11 +2,11 @@ declare var $: any; -window.alert = function(thing?: string) { +window.alert = (thing?: string) => { $('#content').append('
' + thing + '
'); -} +}; -$(function () { +$(() => { var audio = new Audio(); audio.src = Modernizr.audio.ogg ? 'background.ogg' : Modernizr.audio.mp3 ? 'background.mp3' : @@ -30,15 +30,15 @@ $(function () { Modernizr.addTest('track', () => { var video = document.createElement('video'); - return typeof video.addTextTrack === 'function' + return typeof video.addTextTrack === 'function'; }); Modernizr.testStyles('#modernizr { width: 9px; color: papayawhip; }', (elem, rule) => { - Modernizr.addTest('width', elem.offsetWidth == 9); + Modernizr.addTest('width', elem.offsetWidth === 9); }); Modernizr.testStyles('#modernizr { width: 9px; color: papayawhip; }', (elem, rule) => { - Modernizr.addTest('width', elem.offsetWidth == 9); + Modernizr.addTest('width', elem.offsetWidth === 9); }, 2, ["video", "image"]); Modernizr.testProp('pointerEvents'); @@ -54,7 +54,7 @@ $(function () { }); -Modernizr.on('flash', function( result ) { +Modernizr.on('flash', result => { if (result) { // the browser has flash } else { @@ -62,7 +62,7 @@ Modernizr.on('flash', function( result ) { } }); -Modernizr.addTest('itsTuesday', function() { +Modernizr.addTest('itsTuesday', () => { var d = new Date(); return d.getDay() === 2; }); @@ -70,12 +70,12 @@ Modernizr.addTest('itsTuesday', function() { Modernizr.addTest('hasJquery', 'jQuery' in window); var detects = { - 'hasjquery': 'jQuery' in window, - 'itstuesday': function() { + hasjquery: 'jQuery' in window, + itstuesday: () => { var d = new Date(); return d.getDay() === 2; } -} +}; Modernizr.addTest(detects); var keyframes = Modernizr.atRule('@keyframes'); @@ -88,56 +88,56 @@ if (keyframes) { Modernizr._domPrefixes === [ "Moz", "O", "ms", "Webkit" ]; -Modernizr.hasEvent('blur') // true; +Modernizr.hasEvent('blur'); // true; -Modernizr.hasEvent('devicelight', window) // true; +Modernizr.hasEvent('devicelight', window); // true; var query = Modernizr.mq('(min-width: 900px)'); if (query) { // the browser window is larger than 900px } -Modernizr.prefixed('boxSizing') +Modernizr.prefixed('boxSizing'); var raf = Modernizr.prefixed('requestAnimationFrame', window); -raf(function() { +raf(() => { }); var rAFProp = Modernizr.prefixed('requestAnimationFrame', window, false); -rAFProp === 'WebkitRequestAnimationFrame' // in older webkit +rAFProp === 'WebkitRequestAnimationFrame'; // in older webkit -Modernizr.prefixedCSS('transition') // '-moz-transition' in old Firefox +Modernizr.prefixedCSS('transition'); // '-moz-transition' in old Firefox -Modernizr.prefixedCSSValue('background', 'linear-gradient(left, red, red)') +Modernizr.prefixedCSSValue('background', 'linear-gradient(left, red, red)'); var rule = Modernizr._prefixes.join('transform: rotate(20deg); '); -rule === 'transform: rotate(20deg); webkit-transform: rotate(20deg); moz-transform: rotate(20deg); o-transform: rotate(20deg); ms-transform: rotate(20deg);' +rule === 'transform: rotate(20deg); webkit-transform: rotate(20deg); moz-transform: rotate(20deg); o-transform: rotate(20deg); ms-transform: rotate(20deg);'; rule = 'display:' + Modernizr._prefixes.join('flex; display:') + 'flex'; -rule === 'display:flex; display:-webkit-flex; display:-moz-flex; display:-o-flex; display:-ms-flex; display:flex' +rule === 'display:flex; display:-webkit-flex; display:-moz-flex; display:-o-flex; display:-ms-flex; display:flex'; -Modernizr.testAllProps('boxSizing') // true -Modernizr.testAllProps('display', 'block') // true -Modernizr.testAllProps('display', 'penguin') // false +Modernizr.testAllProps('boxSizing'); // true +Modernizr.testAllProps('display', 'block'); // true +Modernizr.testAllProps('display', 'penguin'); // false Modernizr.testAllProps('shapeOutside', 'content-box', true); -Modernizr.testProp('pointerEvents') // true -Modernizr.testProp('pointerEvents', 'none') // true -Modernizr.testProp('pointerEvents', 'penguin') // false +Modernizr.testProp('pointerEvents'); // true +Modernizr.testProp('pointerEvents', 'none'); // true +Modernizr.testProp('pointerEvents', 'penguin'); // false -Modernizr.testStyles('#modernizr { width: 9px; color: papayawhip; }', function(elem, rule) { +Modernizr.testStyles('#modernizr { width: 9px; color: papayawhip; }', (elem, rule) => { // elem is the first DOM node in the page (by default #modernizr) // rule is the first argument you supplied - the CSS rule in string form - Modernizr.addTest('widthworks', elem.style.width === '9px') + Modernizr.addTest('widthworks', elem.style.width === '9px'); }); -Modernizr.testStyles('#modernizr {width: 1px}; #modernizr2 {width: 2px}', function(elem) { +Modernizr.testStyles('#modernizr {width: 1px}; #modernizr2 {width: 2px}', elem => { document.getElementById('modernizr').style.width === '1px'; // true document.getElementById('modernizr2').style.width === '2px'; // true elem.firstChild === document.getElementById('modernizr2'); // true }, 1); -Modernizr.testStyles('#modernizr {width: 1px}; #modernizr2 {width: 2px}', function(elem) { +Modernizr.testStyles('#modernizr {width: 1px}; #modernizr2 {width: 2px}', elem => { document.getElementById('modernizr').style.width === '1px'; // true document.getElementById('modernizr2').style.width === '2px'; // true elem.firstChild === document.getElementById('modernizr2'); // true diff --git a/modernizr/tslint.json b/modernizr/tslint.json index 8ba2515dc2..d8284f73b9 100644 --- a/modernizr/tslint.json +++ b/modernizr/tslint.json @@ -4,4 +4,4 @@ "no-single-declare-module": false, "no-empty-interface": false } -} \ No newline at end of file +} diff --git a/modesl/index.d.ts b/modesl/index.d.ts new file mode 100644 index 0000000000..6b1c532bd3 --- /dev/null +++ b/modesl/index.d.ts @@ -0,0 +1,107 @@ +// Type definitions for modesl 1.1 +// Project: https://github.com/englercj/node-esl +// Definitions by: Nischit Ranganath +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import EventEmitter = NodeJS.EventEmitter; +export class Connection extends EventEmitter { + constructor(...args: any[]); + + api(command: any, args: string[], cb?: () => void): void; + + auth(cb: () => void): void; + + bgapi(command: any, args: string[], jobid?: any, cb?: () => void): void; + + connected(): any; + + disconnect(): void; + + events(type: 'json' | 'plain' | 'xml', events: string, cb?: () => void): void; + + execute(app: any, arg?: string, uuid?: string, cb?: () => void): any; + + executeAsync(app: any, arg?: string, uuid?: string, cb?: () => void): any; + + filter(header: any, value: any, cb?: () => void): void; + + filterDelete(header: any, value: any, cb?: () => void): void; + + getInfo(): any; + + message(options: any, cb?: () => void): void; + + originate(options: any, cb?: () => void): void; + + recvEvent(cb?: () => void): void; + + recvEventTimed(ms: any, cb?: () => void): void; + + send(command: any, args: any): void; + + sendEvent(event: any, cb?: () => void): void; + + sendRecv(command: any, args: any, cb?: () => void): void; + + setAsyncExecute(value: any): void; + + setEventLock(value: any): void; + + show(item: any, format: any, cb?: () => void): void; + + socketDescriptor(): any; + + subscribe(events: any, cb?: () => void): void; +} + +export interface Header { + name: string; + + value: string; +} + +export class Event { + constructor(type: any, subclass: any); + + headers: Header[]; + + addBody(value: any): any; + + addHeader(name: any, value: any): any; + + delHeader(name: any): any; + + firstHeader(): any; + + getBody(): any; + + getHeader(name: any): string; + + getType(): any; + + nextHeader(): any; + + serialize(format: any): any; + + setPriority(priority: any): void; + + static readonly PRIORITY: { + HIGH: string; + LOW: string; + NORMAL: string; + }; +} +export class Parser { + constructor(socket: any); +} +export class Server extends EventEmitter { + constructor(opts: any, readycb?: () => void); + + close(callback: any): void; +} +export function eslSetLogLevel(level: any): void; + +export function setLogLevel(level: any): void; + diff --git a/modesl/modesl-tests.ts b/modesl/modesl-tests.ts new file mode 100644 index 0000000000..c3788833d0 --- /dev/null +++ b/modesl/modesl-tests.ts @@ -0,0 +1,34 @@ +import * as modesl from 'modesl'; + +const freeswitchListener = new modesl.Server(() => { + // console.log('Server listening on localhost at port 8022'); +}); + + +const freeswitchConnection = new modesl.Connection("freeswitch-host", 8021, 'password', () => { + // console.log('connection initialized'); + + freeswitchConnection.api('conference', ['confname', 'dial', 'user/1006']); + + freeswitchConnection.bgapi('conference', ['confname', 'dial', 'user/1006'], 'job-id', () => { + // console.log('action queued'); + }); + + freeswitchConnection.events('json', 'all'); + + freeswitchConnection.subscribe('all'); + + freeswitchConnection.on('esl::event::*::*', (event: modesl.Event) => { + const headerValue = event.getHeader('header'); + + const body = event.getBody(); + + const headers = event.headers; + + headers.forEach((header: modesl.Header) => { + const headerName = header.name; + const headerValue = header.value; + }); + }); +}); + diff --git a/modesl/tsconfig.json b/modesl/tsconfig.json new file mode 100644 index 0000000000..bf010625e0 --- /dev/null +++ b/modesl/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "modesl-tests.ts" + ] +} diff --git a/modesl/tslint.json b/modesl/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/modesl/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/moment-round/tsconfig.json b/moment-round/tsconfig.json index 7054df992f..f0a73e2ecd 100644 --- a/moment-round/tsconfig.json +++ b/moment-round/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "moment-round-tests.ts" ] -} +} \ No newline at end of file diff --git a/moment-timezone/tslint.json b/moment-timezone/tslint.json index 012ccb0889..68d10d72a6 100644 --- a/moment-timezone/tslint.json +++ b/moment-timezone/tslint.json @@ -3,4 +3,4 @@ "rules": { "unified-signatures": false } -} \ No newline at end of file +} diff --git a/mongodb/index.d.ts b/mongodb/index.d.ts index dbd96c83c0..c37bac86cd 100644 --- a/mongodb/index.d.ts +++ b/mongodb/index.d.ts @@ -1119,7 +1119,7 @@ export interface WriteOpResult { export type CursorResult = any | void | boolean; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html -export interface Cursor extends Readable { +export class Cursor extends Readable { sortValue: string; timeout: boolean; @@ -1223,7 +1223,7 @@ export interface EndCallback { //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#~resultCallback export type AggregationCursorResult = any | void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html -export interface AggregationCursor extends Readable { +export class AggregationCursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#batchSize batchSize(value: number): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#clone @@ -1275,7 +1275,7 @@ export interface AggregationCursor extends Readable { } //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html -export interface CommandCursor extends Readable { +export class CommandCursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#batchSize batchSize(value: number): CommandCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#clone diff --git a/mongoose/index.d.ts b/mongoose/index.d.ts index 40821b8968..25b0e177ea 100644 --- a/mongoose/index.d.ts +++ b/mongoose/index.d.ts @@ -385,6 +385,9 @@ declare module "mongoose" { * If connecting to multiple mongos servers, set the mongos option to true. */ mongos?: boolean; + + /** sets the underlying driver's promise library (see http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html) */ + promiseLibrary?: any; } interface ConnectionOptions extends @@ -720,6 +723,8 @@ declare module "mongoose" { validateBeforeSave?: boolean; /** defaults to "__v" */ versionKey?: string|boolean; + /** defaults to false */ + retainKeyOrder?: boolean; /** * skipVersioning allows excluding paths from * versioning (the internal revision will not be @@ -2163,6 +2168,11 @@ declare module "mongoose" { * @param fields the field(s) to unwind */ unwind(...fields: string[]): this; + /** + * Appends new custom $unwind operator(s) to this aggregate pipeline + * new in mongodb 3.2 + */ + unwind(...opts: { path: string, includeArrayIndex?: string, preserveNullAndEmptyArrays?: boolean }[]): this; } /* diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index c6dfe20fdc..dc170dccd9 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1016,7 +1016,41 @@ aggregate.sort('field -test'); aggregate.then(cb).catch(cb); aggregate.unwind("tags").unwind('tags'); aggregate.unwind("a", "b", "c").unwind('tag1', 'tag2'); - +aggregate.unwind( + { + path: "tags", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }) + .unwind({ + path: "tags", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }); +aggregate.unwind( + { + path: "a", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }, { + path: "b", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }, { + path: "c", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }) + .unwind({ + path: "tag1", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }, { + path: "tag2", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }); + /* * section schematype.js * http://mongoosejs.com/docs/api.html#schematype-js diff --git a/msgpack-lite/msgpack-lite-tests.ts b/msgpack-lite/msgpack-lite-tests.ts index 033fde060c..a03d86b679 100644 --- a/msgpack-lite/msgpack-lite-tests.ts +++ b/msgpack-lite/msgpack-lite-tests.ts @@ -3,7 +3,7 @@ import * as msgpack from 'msgpack-lite'; // https://github.com/kawanet/msgpack-lite#encoding-and-decoding-messagepack function encodingAndDecoding() { // encode from JS Object to MessagePack (Buffer) - var buffer = msgpack.encode({"foo": "bar"}); + var buffer = msgpack.encode({foo: "bar"}); // decode from MessagePack (Buffer) to JS Object var data = msgpack.decode(buffer); // => {"foo": "bar"} @@ -55,8 +55,8 @@ function customExtensionTypes() { codec.addExtUnpacker(0x3F, myVectorUnpacker); var data = new MyVector(1, 2); - var encoded = msgpack.encode(data, {codec: codec}); - var decoded = msgpack.decode(encoded, {codec: codec}); + var encoded = msgpack.encode(data, {codec}); + var decoded = msgpack.decode(encoded, {codec}); class MyVector { constructor(public x: number, public y: number) {} diff --git a/msgpack-lite/tslint.json b/msgpack-lite/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/msgpack-lite/tslint.json +++ b/msgpack-lite/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/nanomsg/nanomsg-tests.ts b/nanomsg/nanomsg-tests.ts index a731312890..22b9836db0 100644 --- a/nanomsg/nanomsg-tests.ts +++ b/nanomsg/nanomsg-tests.ts @@ -2,16 +2,16 @@ import { Socket, socket } from "nanomsg"; const pub: Socket = socket("pub"); const sub: Socket = socket("sub"); -const addr: string = "tcp://127.0.0.1:7789" +const addr: string = "tcp://127.0.0.1:7789"; pub.bind(addr); sub.connect(addr); -sub.on('data', function (buf) { +sub.on('data', buf => { console.log(String(buf)); pub.close(); sub.close(); }); -setTimeout(function () { +setTimeout(() => { pub.send("Hello from nanomsg!"); }, 100); diff --git a/nanomsg/tslint.json b/nanomsg/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/nanomsg/tslint.json +++ b/nanomsg/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/navigation-react/navigation-react-tests.tsx b/navigation-react/navigation-react-tests.tsx index 83a0c5f40a..7f2454e8b6 100644 --- a/navigation-react/navigation-react-tests.tsx +++ b/navigation-react/navigation-react-tests.tsx @@ -8,11 +8,9 @@ var stateNavigator = new StateNavigator([ ]); // Refresh Link -var RefreshLinkTest = function() { - return People; -} +var RefreshLinkTest = () => People; -RefreshLinkTest = function() { +RefreshLinkTest = () => { return ( true} + navigating= {(e: MouseEvent, domId: string, link: string) => true} stateNavigator={stateNavigator} target="_blank" aria-label="Go to the second page of people"> People ); -} +}; // Navigation Link -var NavigationLinkTest = function() { - return Person; -} +var NavigationLinkTest = () => Person; -NavigationLinkTest = function() { +NavigationLinkTest = () => { return ( true} + navigating= {(e: MouseEvent, domId: string, link: string) => true} stateNavigator={stateNavigator} target="_blank" aria-label="View the person's details"> Person ); -} +}; // Navigation Back Link -var NavigationBackLinkTest = function() { - return People; -} +var NavigationBackLinkTest = () => People; -NavigationBackLinkTest = function() { +NavigationBackLinkTest = () => { return ( true} + navigating= {(e: MouseEvent, domId: string, link: string) => true} stateNavigator={stateNavigator} target="_blank" aria-label="Go back to the list of people"> People ); -} - +}; diff --git a/navigation-react/tslint.json b/navigation-react/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/navigation-react/tslint.json +++ b/navigation-react/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/nblas/nblas-tests.ts b/nblas/nblas-tests.ts index 754c47560c..478a9cff78 100644 --- a/nblas/nblas-tests.ts +++ b/nblas/nblas-tests.ts @@ -4,7 +4,7 @@ const a = new Float32Array(0); const n = 1; let res: number; -function test () { +function test() { // BLAS Level 1 Routines and Functions res = nblas.asum(a); nblas.axpy(a, a, n); @@ -18,7 +18,7 @@ function test () { nblas.scal(a, n); nblas.swap(a, a); res = nblas.iamax(a); - //nblas.iamin(a); + // nblas.iamin(a); // BLAS Level 2 Routines nblas.gbmv(a, a, a, n, n, n, n, nblas.Trans); diff --git a/ng-file-upload/ng-file-upload-tests.ts b/ng-file-upload/ng-file-upload-tests.ts index 7252231661..08fbafdb6b 100644 --- a/ng-file-upload/ng-file-upload-tests.ts +++ b/ng-file-upload/ng-file-upload-tests.ts @@ -26,7 +26,7 @@ class UploadController { ngfValidateForce: true }); } - + onFileSelect(files: Array) { this.Upload @@ -44,11 +44,11 @@ class UploadController { }).progress((evt: angular.angularFileUpload.IFileProgressEvent) => { let percent = parseInt((100.0 * evt.loaded / evt.total).toString(), 10); console.log("upload progress: " + percent + "% for " + evt.config.data.media[0]); - }).error((data: any, status: number, response: any, headers: any) => { - console.error(data, status, response, headers); - }).success((data: any, status: number, headers: any, config: angular.angularFileUpload.IFileUploadConfigFile) => { + }).catch((response: ng.IHttpPromiseCallbackArg) => { + console.error(response.data, response.status, response.statusText, response.headers); + }).then((response: ng.IHttpPromiseCallbackArg) => { // file is uploaded successfully - console.log("Success!", data, status, headers, config); + console.log("Success!", response.data, response.status, response.headers, response.config); }); this.Upload @@ -72,16 +72,16 @@ class UploadController { this.Upload.isResizeSupported(); this.Upload.isResumeSupported(); this.Upload.isUploadInProgress(); - + let json = this.Upload.json({ test: true }), jsonBlob = this.Upload.jsonBlob({ test: true }), fileWithNewName = this.Upload.rename(files[0], "newName.jpg"); this.Upload - .resize(files[0], { + .resize(files[0], { height: 1024, width: 1024, - quality: 0.7, + quality: 0.7, ratio: 0.9, centerCrop: true, restoreExif: true, diff --git a/nock/index.d.ts b/nock/index.d.ts index 447c591803..180100a33f 100644 --- a/nock/index.d.ts +++ b/nock/index.d.ts @@ -34,7 +34,8 @@ declare namespace nock { type HttpHeaders = { [key: string]: string | { (req: any, res: any, body: string): any; }; }; type InterceptFunction = ( uri: string | RegExp | { (uri: string): boolean; }, - requestBody?: string | RegExp | { (body: any): boolean; } | any + requestBody?: string | RegExp | { (body: any): boolean; } | any, + interceptorOptions?: Options ) => Interceptor; export type ReplyCallback = (err: any, result: ReplyCallbackResult) => void; type ReplyCallbackResult = string | [number, string | any] | [number, string | any, HttpHeaders] | any; @@ -48,6 +49,7 @@ declare namespace nock { patch: InterceptFunction; merge: InterceptFunction; delete: InterceptFunction; + options: InterceptFunction; intercept: ( uri: string | RegExp | { (uri: string): boolean; }, diff --git a/nock/nock-tests.ts b/nock/nock-tests.ts index 0d1b11159f..8c2d48e736 100644 --- a/nock/nock-tests.ts +++ b/nock/nock-tests.ts @@ -21,29 +21,39 @@ inst = scope.head(str); inst = scope.get(str); inst = scope.get(str, data); +inst = scope.get(str, data, options); + +inst = scope.options(str); +inst = scope.options(str, data); +inst = scope.options(str, data, options); inst = scope.patch(str); inst = scope.patch(str, str); inst = scope.patch(str, obj); +inst = scope.patch(str, obj, options); inst = scope.patch(str, regex); inst = scope.post(str); inst = scope.post(str, data); +inst = scope.post(str, data, options); inst = scope.post(str, obj); inst = scope.post(str, regex); inst = scope.put(str); inst = scope.put(str, data); +inst = scope.put(str, data, options); inst = scope.put(str, obj); inst = scope.put(str, regex); inst = scope.delete(str); inst = scope.delete(str, data); +inst = scope.delete(str, data, options); inst = scope.delete(str, obj); inst = scope.delete(str, regex); inst = scope.merge(str); inst = scope.merge(str, data); +inst = scope.merge(str, data, options); inst = scope.merge(str, obj); inst = scope.merge(str, regex); diff --git a/node-emoji/node-emoji-tests.ts b/node-emoji/node-emoji-tests.ts index ebd71391fd..3bc883c6a4 100644 --- a/node-emoji/node-emoji-tests.ts +++ b/node-emoji/node-emoji-tests.ts @@ -1,12 +1,12 @@ import emoji = require('node-emoji'); -let coffee: string = emoji.get('coffee'); -let result: string = emoji.random(); +const coffee: string = emoji.get('coffee'); +const result: string = emoji.random(); -let cofee_name: string = emoji.which('☕️'); +const cofee_name: string = emoji.which('☕️'); -let emoji_string: string = emoji.emojify('I :heart: :coffee:! - :hushed::star::heart_eyes: ::: test : : :+1:+'); +const emoji_string: string = emoji.emojify('I :heart: :coffee:! - :hushed::star::heart_eyes: ::: test : : :+1:+'); -let emoji_string2: string = emoji.emojify('I :unknown_emoji: :star: :another_one:', (name: string) => name); +const emoji_string2: string = emoji.emojify('I :unknown_emoji: :star: :another_one:', (name: string) => name); -let emoji_direct: string = emoji.emoji.coffee; +const emoji_direct: string = emoji.emoji.coffee; diff --git a/node-forge/index.d.ts b/node-forge/index.d.ts index 8640f699d4..900fdfc2f9 100644 --- a/node-forge/index.d.ts +++ b/node-forge/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for node-forge 0.6.42 // Project: https://github.com/digitalbazaar/forge // Definitions by: Seth Westphal +// Kay Schecker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "node-forge" { @@ -23,6 +24,7 @@ declare module "node-forge" { function privateKeyToPem(key: Key, maxline?: number): PEM; function publicKeyToPem(key: Key, maxline?: number): PEM; + function certificateToPem(cert: Certificate, maxline?: number): PEM; interface oids { [key: string]: string; @@ -234,4 +236,40 @@ declare module "node-forge" { } } } + + namespace pkcs12 { + + interface BagsFilter { + localKeyId?: string; + localKeyIdHex?: string; + friendlyName?: string; + bagType?: string; + } + + interface Bag { + type: string; + attributes: any; + key?: pki.Key; + cert?: pki.Certificate; + asn1: asn1.Asn1 + } + + interface Pkcs12Pfx { + version: string; + safeContents: [{ + encrypted: boolean; + safeBags: Bag[]; + }]; + getBags: (filter: BagsFilter) => { + [key: string]: Bag[]; + localKeyId?: Bag[]; + friendlyName?: Bag[]; + }; + getBagsByFriendlyName: (fiendlyName: string, bagType: string) => Bag[] + getBagsByLocalKeyId: (localKeyId: string, bagType: string) => Bag[] + } + + function pkcs12FromAsn1(obj:any, strict?: boolean, password?: string) : Pkcs12Pfx; + function pkcs12FromAsn1(obj:any, password?: string) : Pkcs12Pfx; + } } diff --git a/node-hid/node-hid-tests.ts b/node-hid/node-hid-tests.ts index 15bc71b7d1..ef1f0c7e03 100644 --- a/node-hid/node-hid-tests.ts +++ b/node-hid/node-hid-tests.ts @@ -1,13 +1,13 @@ import HID = require('node-hid'); -var devices = HID.devices() +var devices = HID.devices(); var device = new HID.HID("path"); var device = new HID.HID(12, 22); -device.on("data", function (data) { }); -device.on("error", function (err) { }); +device.on("data", data => {}); +device.on("error", err => {}); device.write([0x00, 0x01, 0x01, 0x05, 0xff, 0xff]); \ No newline at end of file diff --git a/node-waves/tsconfig.json b/node-waves/tsconfig.json index c069824144..793f2d8de3 100644 --- a/node-waves/tsconfig.json +++ b/node-waves/tsconfig.json @@ -1,7 +1,10 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6", + "dom" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +20,4 @@ "index.d.ts", "node-waves-tests.ts" ] -} +} \ No newline at end of file diff --git a/node-wit/node-wit-tests.ts b/node-wit/node-wit-tests.ts index 2181383672..362595c4a9 100644 --- a/node-wit/node-wit-tests.ts +++ b/node-wit/node-wit-tests.ts @@ -4,7 +4,7 @@ var wit = new Wit({ accessToken: "", actions: { send(request: WitRequest, response: WitResponse) { - return new Promise(function(resolve, reject) { + return new Promise((resolve, reject) => { console.log(response.text); console.log(request.entities); return resolve(); diff --git a/node-xmpp-client/index.d.ts b/node-xmpp-client/index.d.ts new file mode 100644 index 0000000000..874df37de7 --- /dev/null +++ b/node-xmpp-client/index.d.ts @@ -0,0 +1,71 @@ +// Type definitions for node-xmpp-client 3.1 +// Project: https://github.com/node-xmpp/node-xmpp/tree/master/packages/node-xmpp-client/ +// Definitions by: PJakcson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export declare class Client { + static Stanza: Stanza; + + constructor(options: XmppOptions); + + connect(): void; + + disconnect(): void; + + on(event: string, c: (e: any, d: any) => any): void; + + send(stanza: any): void; +} + +interface Stanza extends Element { + // This has to be used for the static class initializer new Client.Stanza(..). If there is a better way feel free to + // contribute. + // tslint:disable-next-line + new(name: string, attr: any): Stanza; + from: string; + to: string; + id: string; + type: string; +} + +interface Element { + is(name: string, xmlns: string): boolean; + getName(): string; + getNS(): string; + findNS(prefix: string): string; + getXmlns(): string; + setAttrs(attrs: any): void; + getAttrs(): any; + + up(): Element; + c(name: string, attrs?: any): Element; + cnode(child: Element): Element; + t(text: string): Element; + remove(el: Element, xmnls: string): Element; + attr(attr: any, val: any): any; + + toString(): string; + toJSON(): any; +} + +interface XmppOptions { + jid: string; + password: string; + host?: string; + port?: number; + reconnect?: boolean; + autostart?: boolean; // if we start connecting to a given port + register?: boolean; // register account before authentication + legacySSL?: boolean; // connect to the legacy SSL port, requires at least the host to be specified + credentials?: any; // Dictionary (optional) - TLS or SSL key and certificate credentials + actAs?: string; // if admin user act on behalf of another user (just user) + disallowTLS?: boolean; // prevent upgrading the connection to a secure one via TLS + preferred?: string; // Preferred SASL mechanism to use + bosh?: Bosh; +} + +interface Bosh { + url?: string; + prebind?: (error: any, data: any) => void; +} diff --git a/node-xmpp-client/node-xmpp-client-tests.ts b/node-xmpp-client/node-xmpp-client-tests.ts new file mode 100644 index 0000000000..734067738e --- /dev/null +++ b/node-xmpp-client/node-xmpp-client-tests.ts @@ -0,0 +1,21 @@ +import {Client} from './index'; + +let client = new Client({ + jid: 'user@example.com', + password: 'password' +}); + +client.connect(); + +client.on('online', () => {}); + +client.on('stanza', stanza => { + let _ = stanza; +}); + +let stanza = new Client.Stanza('chat', {}) + .c('show').t('chat').up() + .c('status').t('message'); +client.send(stanza); + +client.disconnect(); diff --git a/node-xmpp-client/tsconfig.json b/node-xmpp-client/tsconfig.json new file mode 100644 index 0000000000..c76db9a985 --- /dev/null +++ b/node-xmpp-client/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "node-xmpp-client-tests.ts" + ] +} diff --git a/node-xmpp-client/tslint.json b/node-xmpp-client/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/node-xmpp-client/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/node-zookeeper-client/index.d.ts b/node-zookeeper-client/index.d.ts index 227ebd45ad..d88eab9fa5 100644 --- a/node-zookeeper-client/index.d.ts +++ b/node-zookeeper-client/index.d.ts @@ -86,7 +86,12 @@ interface Client extends EventEmitter { create(path: string, callback: (error: Error | Exception, path: string) => void): void; create(path: string, dataOrAclsOrmode1: Buffer | ACL[] | number, callback: (error: Error | Exception, path: string) => void): void; create(path: string, dataOrAclsOrmode1: Buffer | ACL[] | number, dataOrAclsOrmode2: Buffer | ACL[] | number, callback: (error: Error | Exception, path: string) => void): void; - create(path: string, dataOrAclsOrmode1: Buffer | ACL[] | number, dataOrAclsOrmode2: Buffer | ACL[] | number, dataOrAclsOrmode3: Buffer | ACL[] | number, callback: (error: Error | Exception, path: string) => void): void; + create( + path: string, + dataOrAclsOrmode1: Buffer | ACL[] | number, + dataOrAclsOrmode2: Buffer | ACL[] | number, + dataOrAclsOrmode3: Buffer | ACL[] | number, + callback: (error: Error | Exception, path: string) => void): void; remove(path: string, callback: (error: Error | Exception) => void): void; remove(path: string, version: number, callback: (error: Error | Exception) => void): void; exists(path: string, callback: (error: Error | Exception, stat: Stat) => void): void; @@ -104,7 +109,12 @@ interface Client extends EventEmitter { mkdirp(path: string, callback: (error: Error | Exception, path: string) => void): void; mkdirp(path: string, dataOrAclsOrmode1: Buffer | ACL[] | number, callback: (error: Error | Exception, path: string) => void): void; mkdirp(path: string, dataOrAclsOrmode1: Buffer | ACL[] | number, dataOrAclsOrmode2: Buffer | ACL[] | number, callback: (error: Error | Exception, path: string) => void): void; - mkdirp(path: string, dataOrAclsOrmode1: Buffer | ACL[] | number, dataOrAclsOrmode2: Buffer | ACL[] | number, dataOrAclsOrmode3: Buffer | ACL[] | number, callback: (error: Error | Exception, path: string) => void): void; + mkdirp( + path: string, + dataOrAclsOrmode1: Buffer | ACL[] | number, + dataOrAclsOrmode2: Buffer | ACL[] | number, + dataOrAclsOrmode3: Buffer | ACL[] | number, + callback: (error: Error | Exception, path: string) => void): void; addAuthInfo(scheme: string, auth: Buffer): void; getState(): State; getSessionId(): Buffer; diff --git a/node-zookeeper-client/node-zookeeper-client-tests.ts b/node-zookeeper-client/node-zookeeper-client-tests.ts index 71f2267878..b7e33a2762 100644 --- a/node-zookeeper-client/node-zookeeper-client-tests.ts +++ b/node-zookeeper-client/node-zookeeper-client-tests.ts @@ -4,10 +4,10 @@ import * as zookeeper from "node-zookeeper-client"; const client = zookeeper.createClient('localhost:2181'); const path = process.argv[2]; - client.once('connected', function () { + client.once('connected', () => { console.log('Connected to the server.'); - client.create(path, function (error) { + client.create(path, error => { if (error) { console.log('Failed to create node: %s due to: %s.', path, error); } else { @@ -24,11 +24,11 @@ import * as zookeeper from "node-zookeeper-client"; function listChildren(client: zookeeper.Client, path: string) { client.getChildren( path, - function (event) { + event => { console.log('Got watcher event: %s', event); listChildren(client, path); }, - function (error, children, stat) { + (error, children, stat) => { if (error) { console.log( 'Failed to list children of %s due to: %s.', @@ -47,7 +47,7 @@ function listChildren(client: zookeeper.Client, path: string) { const client = zookeeper.createClient('localhost:2181'); const path = process.argv[2]; - client.once('connected', function () { + client.once('connected', () => { console.log('Connected to ZooKeeper.'); listChildren(client, path); }); @@ -65,7 +65,7 @@ const client = zookeeper.createClient( '/test/demo', new Buffer('data'), zookeeper.CreateMode.EPHEMERAL, - function (error: Error, path) { + (error: Error, path) => { if (error) { console.log(error.stack); return; @@ -77,7 +77,7 @@ const client = zookeeper.createClient( } { - client.remove('/test/demo', -1, function (error: Error) { + client.remove('/test/demo', -1, (error: Error) => { if (error) { console.log(error.stack); return; @@ -88,7 +88,7 @@ const client = zookeeper.createClient( } { - client.exists('/test/demo', function (error: Error, stat) { + client.exists('/test/demo', (error: Error, stat) => { if (error) { console.log(error.stack); return; @@ -103,7 +103,7 @@ const client = zookeeper.createClient( } { - client.getChildren('/test/demo', function (error: Error, children, stats) { + client.getChildren('/test/demo', (error: Error, children, stats) => { if (error) { console.log(error.stack); return; @@ -116,10 +116,10 @@ const client = zookeeper.createClient( { client.getData( '/test/demo', - function (event) { + event => { console.log('Got event: %s.', event); }, - function (error: Error, data, stat) { + (error: Error, data, stat) => { if (error) { console.log(error.stack); return; @@ -131,7 +131,7 @@ const client = zookeeper.createClient( } { - client.setData('/test/demo', null, 2, function (error: Error, stat) { + client.setData('/test/demo', null, 2, (error: Error, stat) => { if (error) { console.log(error.stack); return; @@ -142,7 +142,7 @@ const client = zookeeper.createClient( } { - client.getACL('/test/demo', function (error: Error, acls, stat) { + client.getACL('/test/demo', (error: Error, acls, stat) => { if (error) { console.log(error.stack); return; @@ -161,7 +161,7 @@ const client = zookeeper.createClient( new zookeeper.Id('ip', '127.0.0.1') ) ], - function (error: Error, stat) { + (error: Error, stat) => { if (error) { console.log(error.stack); return; @@ -173,7 +173,7 @@ const client = zookeeper.createClient( } { - client.mkdirp('/test/demo/1/2/3', function (error: Error, path) { + client.mkdirp('/test/demo/1/2/3', (error: Error, path) => { if (error) { console.log(error.stack); return; @@ -201,10 +201,10 @@ const client = zookeeper.createClient( client.getSessionPassword(); client.getSessionTimeout(); - client.on('connected', function () { + client.on('connected', () => { console.log('Client state is changed to connected.'); }); - client.on('state', function (state) { + client.on('state', state => { if (state === zookeeper.State.SYNC_CONNECTED) { console.log('Client state is changed to connected.'); } @@ -212,7 +212,7 @@ const client = zookeeper.createClient( } { - client.once('connected', function () { + client.once('connected', () => { client.transaction(). create('/txn'). create('/txn/1', new Buffer('transaction')). @@ -220,7 +220,7 @@ const client = zookeeper.createClient( check('/txn/1'). remove('/txn/1', -1). remove('/txn'). - commit(function (error, results) { + commit((error, results) => { if (error) { console.log( 'Failed to execute the transaction: %s, results: %j', @@ -238,9 +238,9 @@ const client = zookeeper.createClient( } { - client.create('/test/demo', function (error, path) { + client.create('/test/demo', (error, path) => { if (error) { - if ((error as zookeeper.Exception).getCode() == zookeeper.Exception.NODE_EXISTS) { + if ((error as zookeeper.Exception).getCode() === zookeeper.Exception.NODE_EXISTS) { console.log('Node exists.'); } else { console.log((error as Error).stack); diff --git a/notNeededPackages.json b/notNeededPackages.json index 46509a1642..a7db12a6bf 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -299,6 +299,18 @@ "typingsPackageName": "axios", "sourceRepoURL": "https://github.com/mzabriskie/axios", "asOfVersion": "0.14.0" + }, + { + "libraryName": "gaea-model", + "typingsPackageName": "gaea-model", + "sourceRepoURL": "https://github.com/ascoders/gaea-model", + "asOfVersion": "0.0.0" + }, + { + "libraryName": "Raven JS", + "typingsPackageName": "raven-js", + "sourceRepoURL": "https://github.com/getsentry/raven-js", + "asOfVersion": "3.10.0" } ] -} +} \ No newline at end of file diff --git a/ns-api/ns-api-tests.ts b/ns-api/ns-api-tests.ts index 8a3b8c5bb6..129e54d6b9 100644 --- a/ns-api/ns-api-tests.ts +++ b/ns-api/ns-api-tests.ts @@ -1,13 +1,15 @@ import * as NsApi from "ns-api"; -let ns: NsApi = NsApi({ +declare var console: { log(msg: any): string }; + +const ns: NsApi = NsApi({ username: "", password: "", timeout: 1500 }); -ns.vertrektijden("", (err: any, data: Object) => { - if(err) { +ns.vertrektijden("", (err, data) => { + if (err) { console.log(err); } else { console.log(data); @@ -15,40 +17,40 @@ ns.vertrektijden("", (err: any, data: Object) => { }); // Get travel advise -ns.reisadvies ({}, (err: any, data: Object) => { - if(err) { +ns.reisadvies ({}, (err, data) => { + if (err) { console.log(err); } else { console.log(data); } }); -ns.prijzen({}, (err: any, data: Object) => { - if(err) { +ns.prijzen({}, (err, data) => { + if (err) { console.log(err); } else { console.log(data); } }); -ns.stations("code", (err: any, data: Object) => { - if(err) { +ns.stations("code", (err, data) => { + if (err) { console.log(err); } else { console.log(data); } }); -ns.stations((err: any, data: Object) => { - if(err) { +ns.stations((err, data) => { + if (err) { console.log(err); } else { console.log(data); } }); -ns.storingen({}, (err: any, data: Object) => { - if(err) { +ns.storingen({}, (err, data) => { + if (err) { console.log(err); } else { console.log(data); diff --git a/ns-api/tsconfig.json b/ns-api/tsconfig.json index fae5845b2d..4c5703ed8c 100644 --- a/ns-api/tsconfig.json +++ b/ns-api/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "ns-api-tests.ts" ] -} +} \ No newline at end of file diff --git a/nvd3/index.d.ts b/nvd3/index.d.ts index 45e933eb82..de2bbddefe 100644 --- a/nvd3/index.d.ts +++ b/nvd3/index.d.ts @@ -1355,6 +1355,12 @@ id(value: number|string): this; valueFormatter(func: (d: any) => string): this; } + interface SankeyNodeStyleOptions { + title?: any; + fillColor?: any; + strokeColor?: any; + } + //#endregion //#region Charts @@ -3274,6 +3280,58 @@ id(value: number|string): this; } + interface SankeyChart extends Chart { + /*Y-position of the middle of a node.*/ + center(): number; + /*Y-position of the middle of a node.*/ + center(value: (d: any) => any): this; + + /*Formatting settings for nodes. */ + format(): string; + /*Formatting settings for nodes. */ + format(formatter: (d: any) => string): this; + + /*The height the graph or component created inside the SVG should be made*/ + height(): number; + /*The height the graph or component created inside the SVG should be made.*/ + height(value: number): this; + + /*Format annotation on links. */ + linkTitle(): string; + /*Format annotation on links. */ + linkTitle(formatter: (d: any) => string): this; + + /* The padding of nodes.*/ + nodePadding(): number; + /*The padding of nodes.*/ + nodePadding(value: number): this; + + /*Styling options for nodes. */ + margin(): Margin; + /*Styling options for nodes. */ + margin(value: Margin): this; + + /* The width of nodes.*/ + nodeWidth(): number; + /*The width of nodes.*/ + nodeWidth(value: number): this; + + /*Styling options for nodes. */ + nodeStyle(): SankeyNodeStyleOptions; + /*Styling options for nodes. */ + nodeStyle(value: SankeyNodeStyleOptions): this; + + /* The width the graph or component created inside the SVG should be made*/ + width(): number; + /*The width the graph or component created inside the SVG should be made.*/ + width(value: number): this; + + /*Units to be used. */ + units(): string + /*Units to be used. */ + units(value: string): this; + } + interface StackedAreaChart extends StackedArea, Chart { stacked: StackedArea; legend: Legend; @@ -3378,6 +3436,7 @@ id(value: number|string): this; parallelCoordinatesChart(): ParallelCoordinatesChart; pie(): Pie; pieChart(): PieChart; + sankeyChart(): SankeyChart; scatter(): Scatter; scatterChart(): ScatterChart; sparkline(): SparkLine; diff --git a/opener/tsconfig.json b/opener/tsconfig.json index 963f0f48b5..c607aac672 100644 --- a/opener/tsconfig.json +++ b/opener/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "opener-tests.ts" ] -} +} \ No newline at end of file diff --git a/openfin/index.d.ts b/openfin/index.d.ts index 2c1cfd648e..0b9f3e16ac 100644 --- a/openfin/index.d.ts +++ b/openfin/index.d.ts @@ -63,7 +63,7 @@ declare namespace fin { */ close(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; /** - * Retrieves an array of wrapped fin.desktop.Windows for each of the application’s child windows. + * Retrieves an array of wrapped fin.desktop.Windows for each of the application�s child windows. */ getChildWindows(callback?: (children: OpenFinWindow[]) => void, errorCallback?: (reason: string) => void): void; /** @@ -95,7 +95,7 @@ declare namespace fin { */ removeEventListener(type: OpenFinApplicationEventType, previouslyRegisteredListener: (event: ApplicationBaseEvent | TrayIconClickedEvent | WindowEvent | WindowAlertRequestedEvent | WindowAuthRequested | WindowNavigationRejectedEvent | WindowEndLoadEvent) => any, callback?: () => void, errorCallback?: (reason: string) => void): void; /** - * Removes the application’s icon from the tray. + * Removes the application�s icon from the tray. */ removeTrayIcon(callback?: () => void, errorCallback?: (reason: string) => void): void; /** @@ -288,8 +288,8 @@ declare namespace fin { size?: number; /** * The size in pixels of an additional - * square resizable region located at the - * bottom right corner of a + * square resizable region located at the + * bottom right corner of a * frameless window. (Default: 4) */ bottomRightCorner?: number; @@ -922,11 +922,11 @@ declare namespace fin { interface OpenFinWindowStatic { /** * Class: Window - * + * * new Window(options, callbackopt, errorCallbackopt) - * + * * Creates a new OpenFin Window - * + * * A basic window that wraps a native HTML window. Provides more fine-grained control over the window state such as the ability to minimize, maximize, restore, etc. By default a window does not show upon instantiation; instead the window's show() method must be invoked manually. The new window appears in the same process as the parent window. * @param {any} options - The options of the window * @param {Function} [callback] - Called if the window creation was successful @@ -963,7 +963,7 @@ declare namespace fin { * @returns {OpenFinApplication} Parent application */ getParentApplication(): OpenFinApplication; - /** + /** * Gets the parent window. */ getParentWindow(): OpenFinWindow; @@ -989,7 +989,7 @@ declare namespace fin { bringToFront(callback?: () => void, errorCallback?: (reason: string) => void): void; /** * Closes the window. - * @param {force} Close will be prevented from closing when force is false and ‘close-requested’ has been subscribed to for application’s main window. + * @param {force} Close will be prevented from closing when force is false and �close-requested� has been subscribed to for application�s main window. */ close(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; /** @@ -1009,7 +1009,7 @@ declare namespace fin { */ enableFrame(callback?: () => void, errorCallback?: (reason: string) => void): void; /** - * Flashes the window’s frame and taskbar icon until the window is activated. + * Flashes the window�s frame and taskbar icon until the window is activated. */ flash(options?: any, callback?: () => void, errorCallback?: (reason: string) => void): void; /** @@ -1106,7 +1106,7 @@ declare namespace fin { setZoomLevel(level: number, callback?: () => void, errorCallback?: (reason: string) => void): void; /** * Shows the window if it is hidden. - * @param {force} Show will be prevented from closing when force is false and ‘show-requested’ has been subscribed to for application’s main window. + * @param {force} Show will be prevented from closing when force is false and �show-requested� has been subscribed to for application�s main window. */ show(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; /** diff --git a/openfin/openfin-tests.ts b/openfin/openfin-tests.ts index 81ac24f937..63a53f7cb5 100644 --- a/openfin/openfin-tests.ts +++ b/openfin/openfin-tests.ts @@ -13,10 +13,10 @@ defaultLeft: 300, autoShow: true } - }, function (successObj) { + }, successObj => { console.log("Application successfully created, HTTP response code:", successObj); application.run(); - }, function (error) { + }, error => { console.log("Error creating application:", error); }); // getCurrent @@ -26,84 +26,84 @@ // getWindow application.getWindow(); // addEventListener - application.addEventListener("closed", function (event) { + application.addEventListener("closed", event => { console.log("The application has closed"); - }, function () { + }, () => { console.log("The registration was successful"); - }, function (reason) { + }, reason => { console.log("failure: " + reason); }); // close application.close(); // getChildWindows - application.getChildWindows(function (children) { - children.forEach(function (childWindow) { + application.getChildWindows(children => { + children.forEach(childWindow => { console.log("Showing child: " + childWindow.name); childWindow.show(); }); }); // getGroups - application.getGroups(function (allGroups) { + application.getGroups(allGroups => { console.log("There are a total of " + allGroups.length + " groups."); var groupCounter = 1; - allGroups.forEach(function (windowGroup) { + allGroups.forEach(windowGroup => { console.log("Group " + groupCounter + " contains " + windowGroup.length + " windows."); ++groupCounter; }); }); // getManifest - application.getManifest(function (manifest) { + application.getManifest(manifest => { console.log("Application manifest:"); console.log(manifest); }); // getParentUuid - application.getParentUuid(function (parentUuid) { + application.getParentUuid(parentUuid => { console.log("UUID of parent application:"); console.log(parentUuid); }); // getShortcuts - application.getShortcuts(function (config) { + application.getShortcuts(config => { console.log("Desktop shortcut is enabled: ", config.desktop); console.log("Start Menu shortcut is enabled: ", config.startMenu); console.log("System Startup shortcut is enabled: ", config.systemStartup); }); // isRunning - application.isRunning(function (running) { + application.isRunning(running => { console.log("the application is", running ? "running" : "not running"); }); // registerCustomData application.registerCustomData({ someData: "this is custom" - }, function () { + }, () => { console.log("You will not read this."); - }, function (err) { + }, err => { console.log("failure:", err); }); // removeEventListener - let previousCallback = function (event: fin.WindowEvent) { }; - application.removeEventListener("closed", previousCallback, function () { + const previousCallback = (event: fin.WindowEvent) => { }; + application.removeEventListener("closed", previousCallback, () => { console.log("The unregistration was successful"); - }, function (err) { + }, err => { console.log("failure:", err); }); // removeTrayIcon - application.removeTrayIcon(function () { + application.removeTrayIcon(() => { console.log("Removed the tray icon."); - }, function (err) { + }, err => { console.log("failure:", err); }); // restart - application.restart(function () { + application.restart(() => { console.log("You will not read this."); - }, function (err) { + }, err => { console.log("failure:", err); }); // schedule restart - application.scheduleRestart(function () { + application.scheduleRestart(() => { console.log("You will not read this."); - }, function (err) { + }, err => { console.log("failure:", err); }); // setShortcuts @@ -111,19 +111,19 @@ desktop: true, startMenu: false, systemStartup: true - }, function () { + }, () => { console.log("Successfully set new shortcut states"); - }, function (error) { + }, error => { console.log("Failed to set new shortcut states. Error: ", error); }); // setTrayIcon - application.setTrayIcon("https://developer.openf.in/download/openfin.png", function (clickInfo) { + application.setTrayIcon("https://developer.openf.in/download/openfin.png", clickInfo => { console.log("The mouse has clicked at (" + clickInfo.x + "," + clickInfo.y + ")"); }); // terminate application.terminate(); // wait - application.addEventListener("not-responding", function () { + application.addEventListener("not-responding", () => { console.log("waiting for hung application"); application.wait(); }); @@ -142,7 +142,7 @@ function test_external_application() { console.log(`Error Message: ${err.message} Error Stack: ${err.stack}`); }); // removeEventListener - let previousCallback = function () { }; + const previousCallback = () => { }; externalApp.removeEventListener('connected', previousCallback, () => { console.log('The unregistration was successful'); }, (reason, err) => { @@ -152,15 +152,15 @@ function test_external_application() { function test_inter_application_bus() { // addSubscribeListener - fin.desktop.InterApplicationBus.addSubscribeListener(function (uuid, topic, name) { + fin.desktop.InterApplicationBus.addSubscribeListener((uuid, topic, name) => { console.log("The application " + uuid + " has subscribed to " + topic); }); // addUnsubscribeListener - fin.desktop.InterApplicationBus.addUnsubscribeListener(function (uuid, topic, name) { + fin.desktop.InterApplicationBus.addUnsubscribeListener((uuid, topic, name) => { console.log("The application " + uuid + " has unsubscribed to " + topic); }); // removeSubscribeListener - let aRegisteredListener = function (uuid: string, topic: string, name: string) { }; + const aRegisteredListener = (uuid: string, topic: string, name: string) => { }; fin.desktop.InterApplicationBus.removeSubscribeListener(aRegisteredListener); // removeUnsubscribeListener fin.desktop.InterApplicationBus.removeUnsubscribeListener(aRegisteredListener); @@ -175,11 +175,11 @@ function test_inter_application_bus() { field2: "value2" }); // subscribe - fin.desktop.InterApplicationBus.subscribe("*", "a topic", function (message, uuid, name) { + fin.desktop.InterApplicationBus.subscribe("*", "a topic", (message, uuid, name) => { console.log("The application " + uuid + " sent this message: " + message); }); // unsubscribe - let aRegisteredMessageListener = function (message: any, senderUuid: string) { + const aRegisteredMessageListener = (message: any, senderUuid: string) => { console.log(message, senderUuid); }; fin.desktop.InterApplicationBus.unsubscribe("*", "a topic", aRegisteredMessageListener); @@ -197,9 +197,9 @@ function test_notification() { url: "http://localhost:5000/Account/Register", message: "Hello", onShow: () => { }, - //onClose: () => { }, + // onClose: () => { }, onDismiss: () => { }, - //onClick: () => { }, + // onClick: () => { }, onMessage: () => { }, onError: () => { } }); @@ -209,11 +209,11 @@ function test_notification() { function test_system() { // addEventListener - fin.desktop.System.addEventListener('monitor-info-changed', function (event) { + fin.desktop.System.addEventListener('monitor-info-changed', event => { console.log("The monitor information has changed to: ", event); - }, function () { + }, () => { console.log("The registration was successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); // clearCache @@ -225,38 +225,38 @@ function test_system() { userData: true }); // deleteCacheOnExit - fin.desktop.System.deleteCacheOnExit(function () { + fin.desktop.System.deleteCacheOnExit(() => { console.log("successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); // downloadAsset - let dirAppAsset = { - 'src': 'http://local:8000/dir.zip', - 'alias': 'dirApp', - 'version': '1.23.24', - 'target': 'dir.bat', - 'args': '' + const dirAppAsset = { + src: 'http://local:8000/dir.zip', + alias: 'dirApp', + version: '1.23.24', + target: 'dir.bat', + args: '' }; fin.desktop.System.downloadAsset(dirAppAsset, progress => { - let downloadedPercent = Math.floor((progress.downloadedBytes / progress.totalBytes) * 100); + const downloadedPercent = Math.floor((progress.downloadedBytes / progress.totalBytes) * 100); console.log(`Downloaded ${downloadedPercent}%`); }, p => { console.log(`Downlod complete, can be found on ${p.path}`); - //lets launch our application asset. - //launchDirApp(); + // lets launch our application asset. + // launchDirApp(); }, (reason, err) => { console.log(reason, err); }); // exit - fin.desktop.System.exit(function () { + fin.desktop.System.exit(() => { console.log("successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); // getAllApplications - fin.desktop.System.getAllApplications(function (applicationInfoList) { - applicationInfoList.forEach(function (applicationInfo) { + fin.desktop.System.getAllApplications(applicationInfoList => { + applicationInfoList.forEach(applicationInfo => { console.log("Showing information for application with uuid: " + applicationInfo.uuid); console.log("isRunning: ", applicationInfo.isRunning); @@ -269,38 +269,38 @@ function test_system() { }); }); // getAllWindows - fin.desktop.System.getAllWindows(function (windowInfoList) { - windowInfoList.forEach(function (windowInfo) { + fin.desktop.System.getAllWindows(windowInfoList => { + windowInfoList.forEach(windowInfo => { console.log("Showing information for application with uuid: ", windowInfo.uuid); console.log("Main window: ", windowInfo.mainWindow); console.log("Child windows: ", windowInfo.childWindows); }); }); // getCommandLineArguments - fin.desktop.System.getCommandLineArguments(function (args) { + fin.desktop.System.getCommandLineArguments(args => { console.log("The command line arguments are " + args); }); // getDeviceId - fin.desktop.System.getDeviceId(function (id) { + fin.desktop.System.getDeviceId(id => { console.log("The id of the device is: " + id); }); // getEnvironmentVariable - fin.desktop.System.getEnvironmentVariable("APPDATA", function (variable) { + fin.desktop.System.getEnvironmentVariable("APPDATA", variable => { console.log("this is the APPDATA value", variable); }); // getHostSpecs - fin.desktop.System.getHostSpecs(function (info) { + fin.desktop.System.getHostSpecs(info => { console.log(info); - }, function (error) { + }, error => { console.log('There was an error:', error); }); // getLog - fin.desktop.System.getLog('debug-2015-01-08-22-27-53.log', function (log) { + fin.desktop.System.getLog('debug-2015-01-08-22-27-53.log', log => { console.log(log); }); // getLogList - fin.desktop.System.getLogList(function (logList) { - logList.forEach(function (logInfo) { + fin.desktop.System.getLogList(logList => { + logList.forEach(logInfo => { console.log("The filename of the log is " + logInfo.name + ", the size is " + logInfo.size + ", and the date of creation is " + @@ -308,70 +308,70 @@ function test_system() { }); }); // getMonitorInfo - fin.desktop.System.getMonitorInfo(function (monitorInfo) { + fin.desktop.System.getMonitorInfo(monitorInfo => { console.log("This object contains information about all monitors: ", monitorInfo); }); // getMousePosition - fin.desktop.System.getMousePosition(function (mousePosition) { + fin.desktop.System.getMousePosition(mousePosition => { console.log("The mouse is located at left: " + mousePosition.left + ", top: " + mousePosition.top); }); // getProcessList - fin.desktop.System.getProcessList(function (list) { - list.forEach(function (process) { + fin.desktop.System.getProcessList(list => { + list.forEach(process => { console.log("UUID: " + process.uuid + ", Application Name: " + process.name); }); }); // getProxySettings - fin.desktop.System.getProxySettings(function (proxy) { + fin.desktop.System.getProxySettings(proxy => { console.log(proxy); }); // getRvmInfo - fin.desktop.System.getRvmInfo(function (rvmInfoObject) { + fin.desktop.System.getRvmInfo(rvmInfoObject => { console.log("RVM version:", rvmInfoObject.version); console.log("RVM has been running since:", rvmInfoObject["start-time"]); - }, function (err) { + }, err => { console.log("Failed to get rvm info, error message:", err); }); // getVersion - fin.desktop.System.getVersion(function (version) { + fin.desktop.System.getVersion(version => { console.log("The version is " + version); }); // launchExternalProcess fin.desktop.System.launchExternalProcess({ path: "notepad", arguments: "", - listener: function (result) { + listener(result) { console.log('the exit code', result.exitCode); } - }, function (payload) { + }, payload => { console.log('Success:', payload.uuid); - }, function (error) { + }, error => { console.log('Error:', error); }); // fin.desktop.System.launchExternalProcess({ - //Additionally note that the executable found in the zip file specified in appAssets - //will default to the one mentioned by appAssets.target - //If the the path below refers to a specific path it will override this default + // Additionally note that the executable found in the zip file specified in appAssets + // will default to the one mentioned by appAssets.target + // If the the path below refers to a specific path it will override this default alias: "myApp", - listener: function (result) { + listener(result) { console.log('the exit code', result.exitCode); } - }, function (payload) { + }, payload => { console.log('Success:', payload.uuid); - }, function (error) { + }, error => { console.log('Error:', error); }); // fin.desktop.System.launchExternalProcess({ alias: "myApp", arguments: "e f g", - listener: function (result) { + listener(result) { console.log('the exit code', result.exitCode); } - }, function (payload) { + }, payload => { console.log('Success:', payload.uuid); - }, function (error) { + }, error => { console.log('Error:', error); }); // @@ -383,69 +383,69 @@ function test_system() { subject: 'O=OpenFin INC., L=New York, S=NY, C=US', thumbprint: '‎3c a5 28 19 83 05 fe 69 88 e6 8f 4b 3a af c5 c5 1b 07 80 5b' }, - listener: function (result) { + listener(result) { console.log('the exit code', result.exitCode); } - }, function (payload) { + }, payload => { console.log('Success:', payload.uuid); - }, function (error) { + }, error => { console.log('Error:', error); }); // log - fin.desktop.System.log("info", "An example log message", function () { + fin.desktop.System.log("info", "An example log message", () => { console.log("message successfully logged"); - }, function (err) { + }, err => { console.log(err); }); // monitorExternalProcess fin.desktop.System.monitorExternalProcess({ pid: 2508, - listener: function (result) { + listener(result) { console.log('the exit code', result.exitCode); } - }, function (payload) { + }, payload => { console.log("The process is now being monitored: ", payload.uuid); - }, function (error) { + }, error => { console.log("Error:", error); }); // openUrlWithBrowser - fin.desktop.System.openUrlWithBrowser("https://developer.openf.in/", function () { + fin.desktop.System.openUrlWithBrowser("https://developer.openf.in/", () => { console.log("successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); // registerExternalConnection - fin.desktop.System.registerExternalConnection("remote-connection-uuid", function () { - console.log(arguments); + fin.desktop.System.registerExternalConnection("remote-connection-uuid", (...args: any[]) => { + console.log(args); }); // releaseExternalProcess fin.desktop.System.launchExternalProcess({ path: "notepad", arguments: "", - listener: function (result) { + listener(result) { console.log("The exit code", result.exitCode); } - }, function (result) { + }, result => { console.log("Result UUID is " + result.uuid); - //release it. - fin.desktop.System.releaseExternalProcess(result.uuid, function () { + // release it. + fin.desktop.System.releaseExternalProcess(result.uuid, () => { console.log("Process has been unmapped!"); - }, function (reason) { + }, reason => { console.log("failure: " + reason); }); }); // removeEventListener - let aRegisteredListener = (event: fin.SystemBaseEvent) => { }; - fin.desktop.System.removeEventListener("monitor-info-changed", aRegisteredListener, function () { + const aRegisteredListener = (event: fin.SystemBaseEvent) => { }; + fin.desktop.System.removeEventListener("monitor-info-changed", aRegisteredListener, () => { console.log("successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); // showDeveloperTools - fin.desktop.System.showDeveloperTools("uuid", "name", function () { + fin.desktop.System.showDeveloperTools("uuid", "name", () => { console.log("successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); // terminateExternalProcess @@ -453,24 +453,24 @@ function test_system() { // notepad is in the system’s PATH path: "notepad", arguments: "", - listener: function (result) { + listener(result) { console.log("The exit code", result.exitCode); } - }, function (result) { + }, result => { console.log("Result UUID is " + result.uuid); // Attempt to close the process. Terminate after 4 seconds if it // has not done so. - fin.desktop.System.terminateExternalProcess(result.uuid, 4000, function (info) { + fin.desktop.System.terminateExternalProcess(result.uuid, 4000, info => { console.log("Termination result " + info.result); - }, function (reason) { + }, reason => { console.log("failure: " + reason); }); }); // updateProxySettings - fin.desktop.System.updateProxySettings("type", "proxyAddress", 8080, function () { + fin.desktop.System.updateProxySettings("type", "proxyAddress", 8080, () => { console.log('success'); - }, function (err) { + }, err => { console.log(err); }); } @@ -543,10 +543,10 @@ function test_window() { frame: false, resizable: false, state: "normal" - }, function () { + }, () => { var _win = finWindow.getNativeWindow(); - _win.addEventListener("DOMContentLoaded", function () { finWindow.show(); }); - }, function (error) { + _win.addEventListener("DOMContentLoaded", () => { finWindow.show(); }); + }, error => { console.log("Error creating window:", error); }); // getCurrent @@ -563,11 +563,11 @@ function test_window() { // wrap finWindow = fin.desktop.Window.wrap("uuid", "name"); // addEventListener - finWindow.addEventListener("bounds-changed", function (event) { + finWindow.addEventListener("bounds-changed", event => { console.log("The window has been moved or resized"); - }, function () { + }, () => { console.log("The registration was successful"); - }, function (reason) { + }, reason => { console.log("failure:" + reason); }); // animate @@ -583,7 +583,7 @@ function test_window() { } }, { interrupt: false - }, function (evt) { + }, evt => { // Callback will only fire after both "opacity" and "position" have finished animating. }); // authenticate @@ -607,34 +607,34 @@ function test_window() { // focus finWindow.focus(); // getBounds - finWindow.getBounds(function (bounds) { + finWindow.getBounds(bounds => { console.log("top: " + bounds.top + "left: " + bounds.left + "height: " + bounds.height + "width: " + bounds.width); }); // getOptions - finWindow.getOptions(function (options) { + finWindow.getOptions(options => { console.log(options); }); // getSnapshot - finWindow.getSnapshot(function (base64Snapshot) { + finWindow.getSnapshot(base64Snapshot => { console.log("data:image/png;base64," + base64Snapshot); }); // getState - finWindow.getState(function (state) { + finWindow.getState(state => { console.log("state: " + state); }); // getZoomLevel - finWindow.getZoomLevel(function (level) { + finWindow.getZoomLevel(level => { console.log("zoom level: " + level); - }, function (error) { + }, error => { console.log('error:', error); }); // hide finWindow.hide(); // isShowing - finWindow.isShowing(function (showing) { + finWindow.isShowing(showing => { console.log("the window is " + (showing ? "showing" : "hidden")); }); // joinGroup @@ -642,7 +642,7 @@ function test_window() { url: "http://www.openfin.co", name: "secondWindow", autoShow: true - }, function () { + }, () => { // When mainWindow moves or is moved, secondWindow moves by the same amount secondWindow.joinGroup(finWindow); }); @@ -651,10 +651,10 @@ function test_window() { url: "http://www.openfin.co", name: "secondWindow", autoShow: true - }, function () { + }, () => { // When finWindow moves or is moved, secondWindow moves by the same amount - secondWindow.joinGroup(finWindow, function () { - //once we are in the group, lets leave it. + secondWindow.joinGroup(finWindow, () => { + // once we are in the group, lets leave it. secondWindow.leaveGroup(); }); }); @@ -662,22 +662,22 @@ function test_window() { finWindow.maximize(); // mergeGroups { - let finWindowOne = new fin.desktop.Window({ + const finWindowOne = new fin.desktop.Window({ url: "http://www.openfin.co", name: "finWindowOne", autoShow: true }); - let finWindowTwo = new fin.desktop.Window({ + const finWindowTwo = new fin.desktop.Window({ url: "http://www.openfin.co", name: "finWindowTwo", autoShow: true }); - let finWindowThree = new fin.desktop.Window({ + const finWindowThree = new fin.desktop.Window({ url: "http://www.openfin.co", name: "finWindowThree", autoShow: true }); - let finWindowFour = new fin.desktop.Window({ + const finWindowFour = new fin.desktop.Window({ url: "http://www.openfin.co", name: "finWindowFour", autoShow: true @@ -696,7 +696,7 @@ function test_window() { // moveTo finWindow.moveTo(100, 200); // removeEventListener - let aRegisteredListener = (event: fin.WindowBaseEvent) => { }; + const aRegisteredListener = (event: fin.WindowBaseEvent) => { }; finWindow.removeEventListener("bounds-changed", aRegisteredListener); // resizeBy finWindow.resizeBy(10, 10, "top-right"); diff --git a/openfin/tslint.json b/openfin/tslint.json index 377cc837d4..e4f5db4fa0 100644 --- a/openfin/tslint.json +++ b/openfin/tslint.json @@ -1 +1,6 @@ -{ "extends": "../tslint.json" } +{ + "extends": "../tslint.json", + "rules": { + "max-line-length": false + } +} diff --git a/openfin/v15/index.d.ts b/openfin/v15/index.d.ts index 4350d1ac27..0abaaf61fe 100644 --- a/openfin/v15/index.d.ts +++ b/openfin/v15/index.d.ts @@ -64,7 +64,7 @@ declare namespace fin { */ close(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; /** - * Retrieves an array of wrapped fin.desktop.Windows for each of the application’s child windows. + * Retrieves an array of wrapped fin.desktop.Windows for each of the application's child windows. */ getChildWindows(callback?: (children: OpenFinWindow[]) => void, errorCallback?: (reason: string) => void): void; /** @@ -96,7 +96,7 @@ declare namespace fin { */ removeEventListener(type: OpenFinApplicationEventType, previouslyRegisteredListener: (event: ApplicationBaseEvent | TrayIconClickedEvent | WindowEvent | WindowAlertRequestedEvent | WindowAuthRequested | WindowNavigationRejectedEvent | WindowEndLoadEvent) => any, callback?: () => void, errorCallback?: (reason: string) => void): void; /** - * Removes the application’s icon from the tray. + * Removes the application's icon from the tray. */ removeTrayIcon(callback?: () => void, errorCallback?: (reason: string) => void): void; /** @@ -273,8 +273,8 @@ declare namespace fin { size?: number; /** * The size in pixels of an additional - * square resizable region located at the - * bottom right corner of a + * square resizable region located at the + * bottom right corner of a * frameless window. (Default: 4) */ bottomRightCorner?: number; @@ -845,11 +845,11 @@ declare namespace fin { interface OpenFinWindowStatic { /** * Class: Window - * + * * new Window(options, callbackopt, errorCallbackopt) - * + * * Creates a new OpenFin Window - * + * * A basic window that wraps a native HTML window. Provides more fine-grained control over the window state such as the ability to minimize, maximize, restore, etc. By default a window does not show upon instantiation; instead the window's show() method must be invoked manually. The new window appears in the same process as the parent window. * @param {any} options - The options of the window * @param {Function} [callback] - Called if the window creation was successful @@ -886,7 +886,7 @@ declare namespace fin { * @returns {OpenFinApplication} Parent application */ getParentApplication(): OpenFinApplication; - /** + /** * Gets the parent window. */ getParentWindow(): OpenFinWindow; @@ -912,7 +912,7 @@ declare namespace fin { bringToFront(callback?: () => void, errorCallback?: (reason: string) => void): void; /** * Closes the window. - * @param {force} Close will be prevented from closing when force is false and ‘close-requested’ has been subscribed to for application’s main window. + * @param {force} Close will be prevented from closing when force is false and 'close-requested' has been subscribed to for application's main window. */ close(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; /** @@ -932,7 +932,7 @@ declare namespace fin { */ enableFrame(callback?: () => void, errorCallback?: (reason: string) => void): void; /** - * Flashes the window’s frame and taskbar icon until the window is activated. + * Flashes the window's frame and taskbar icon until the window is activated. */ flash(options?: any, callback?: () => void, errorCallback?: (reason: string) => void): void; /** @@ -1029,7 +1029,7 @@ declare namespace fin { setZoomLevel(level: number, callback?: () => void, errorCallback?: (reason: string) => void): void; /** * Shows the window if it is hidden. - * @param {force} Show will be prevented from closing when force is false and ‘show-requested’ has been subscribed to for application’s main window. + * @param {force} Show will be prevented from closing when force is false and 'show-requested' has been subscribed to for application's main window. */ show(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; /** diff --git a/openfin/v15/openfin-tests.ts b/openfin/v15/openfin-tests.ts index 7aa2930089..69b024ce90 100644 --- a/openfin/v15/openfin-tests.ts +++ b/openfin/v15/openfin-tests.ts @@ -13,10 +13,10 @@ function test_application() { defaultLeft: 300, autoShow: true } - }, function (successObj) { + }, successObj => { console.log("Application successfully created, HTTP response code:", successObj); application.run(); - }, function (error) { + }, error => { console.log("Error creating application:", error); }); // getCurrent @@ -26,84 +26,84 @@ function test_application() { // getWindow application.getWindow(); // addEventListener - application.addEventListener("closed", function (event) { + application.addEventListener("closed", event => { console.log("The application has closed"); - }, function () { + }, () => { console.log("The registration was successful"); - }, function (reason) { + }, reason => { console.log("failure: " + reason); }); // close application.close(); // getChildWindows - application.getChildWindows(function (children) { - children.forEach(function (childWindow) { + application.getChildWindows(children => { + children.forEach(childWindow => { console.log("Showing child: " + childWindow.name); childWindow.show(); }); }); // getGroups - application.getGroups(function (allGroups) { + application.getGroups(allGroups => { console.log("There are a total of " + allGroups.length + " groups."); var groupCounter = 1; - allGroups.forEach(function (windowGroup) { + allGroups.forEach(windowGroup => { console.log("Group " + groupCounter + " contains " + windowGroup.length + " windows."); ++groupCounter; }); }); // getManifest - application.getManifest(function (manifest) { + application.getManifest(manifest => { console.log("Application manifest:"); console.log(manifest); }); // getParentUuid - application.getParentUuid(function (parentUuid) { + application.getParentUuid(parentUuid => { console.log("UUID of parent application:"); console.log(parentUuid); }); // getShortcuts - application.getShortcuts(function (config) { + application.getShortcuts(config => { console.log("Desktop shortcut is enabled: ", config.desktop); console.log("Start Menu shortcut is enabled: ", config.startMenu); console.log("System Startup shortcut is enabled: ", config.systemStartup); }); // isRunning - application.isRunning(function (running) { + application.isRunning(running => { console.log("the application is", running ? "running" : "not running"); }); // registerCustomData application.registerCustomData({ someData: "this is custom" - }, function () { + }, () => { console.log("You will not read this."); - }, function (err) { + }, err => { console.log("failure:", err); }); // removeEventListener - let previousCallback = function (event: fin.WindowEvent) { }; - application.removeEventListener("closed", previousCallback, function () { + const previousCallback = (event: fin.WindowEvent) => { }; + application.removeEventListener("closed", previousCallback, () => { console.log("The unregistration was successful"); - }, function (err) { + }, err => { console.log("failure:", err); }); // removeTrayIcon - application.removeTrayIcon(function () { + application.removeTrayIcon(() => { console.log("Removed the tray icon."); - }, function (err) { + }, err => { console.log("failure:", err); }); // restart - application.restart(function () { + application.restart(() => { console.log("You will not read this."); - }, function (err) { + }, err => { console.log("failure:", err); }); // schedule restart - application.scheduleRestart(function () { + application.scheduleRestart(() => { console.log("You will not read this."); - }, function (err) { + }, err => { console.log("failure:", err); }); // setShortcuts @@ -111,19 +111,19 @@ function test_application() { desktop: true, startMenu: false, systemStartup: true - }, function () { + }, () => { console.log("Successfully set new shortcut states"); - }, function (error) { + }, error => { console.log("Failed to set new shortcut states. Error: ", error); }); // setTrayIcon - application.setTrayIcon("https://developer.openf.in/download/openfin.png", function (clickInfo) { + application.setTrayIcon("https://developer.openf.in/download/openfin.png", clickInfo => { console.log("The mouse has clicked at (" + clickInfo.x + "," + clickInfo.y + ")"); }); // terminate application.terminate(); // wait - application.addEventListener("not-responding", function () { + application.addEventListener("not-responding", () => { console.log("waiting for hung application"); application.wait(); }); @@ -142,7 +142,7 @@ function test_external_application() { console.log(`Error Message: ${err.message} Error Stack: ${err.stack}`); }); // removeEventListener - let previousCallback = function () { }; + const previousCallback = () => { }; externalApp.removeEventListener('connected', previousCallback, () => { console.log('The unregistration was successful'); }, (reason, err) => { @@ -152,15 +152,15 @@ function test_external_application() { function test_inter_application_bus() { // addSubscribeListener - fin.desktop.InterApplicationBus.addSubscribeListener(function (uuid, topic, name) { + fin.desktop.InterApplicationBus.addSubscribeListener((uuid, topic, name) => { console.log("The application " + uuid + " has subscribed to " + topic); }); // addUnsubscribeListener - fin.desktop.InterApplicationBus.addUnsubscribeListener(function (uuid, topic, name) { + fin.desktop.InterApplicationBus.addUnsubscribeListener((uuid, topic, name) => { console.log("The application " + uuid + " has unsubscribed to " + topic); }); // removeSubscribeListener - let aRegisteredListener = function (uuid: string, topic: string, name: string) { }; + const aRegisteredListener = (uuid: string, topic: string, name: string) => { }; fin.desktop.InterApplicationBus.removeSubscribeListener(aRegisteredListener); // removeUnsubscribeListener fin.desktop.InterApplicationBus.removeUnsubscribeListener(aRegisteredListener); @@ -175,11 +175,11 @@ function test_inter_application_bus() { field2: "value2" }); // subscribe - fin.desktop.InterApplicationBus.subscribe("*", "a topic", function (message, uuid, name) { + fin.desktop.InterApplicationBus.subscribe("*", "a topic", (message, uuid, name) => { console.log("The application " + uuid + " sent this message: " + message); }); // unsubscribe - let aRegisteredMessageListener = function (message: any, senderUuid: string) { + const aRegisteredMessageListener = (message: any, senderUuid: string) => { console.log(message, senderUuid); }; fin.desktop.InterApplicationBus.unsubscribe("*", "a topic", aRegisteredMessageListener); @@ -197,9 +197,9 @@ function test_notification() { url: "http://localhost:5000/Account/Register", message: "Hello", onShow: () => { }, - //onClose: () => { }, + // onClose: () => { }, onDismiss: () => { }, - //onClick: () => { }, + // onClick: () => { }, onMessage: () => { }, onError: () => { } }); @@ -209,11 +209,11 @@ function test_notification() { function test_system() { // addEventListener - fin.desktop.System.addEventListener('monitor-info-changed', function (event) { + fin.desktop.System.addEventListener('monitor-info-changed', event => { console.log("The monitor information has changed to: ", event); - }, function () { + }, () => { console.log("The registration was successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); // clearCache @@ -225,38 +225,38 @@ function test_system() { userData: true }); // deleteCacheOnExit - fin.desktop.System.deleteCacheOnExit(function () { + fin.desktop.System.deleteCacheOnExit(() => { console.log("successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); // downloadAsset - let dirAppAsset = { - 'src': 'http://local:8000/dir.zip', - 'alias': 'dirApp', - 'version': '1.23.24', - 'target': 'dir.bat', - 'args': '' + const dirAppAsset = { + src: 'http://local:8000/dir.zip', + alias: 'dirApp', + version: '1.23.24', + target: 'dir.bat', + args: '' }; fin.desktop.System.downloadAsset(dirAppAsset, progress => { - let downloadedPercent = Math.floor((progress.downloadedBytes / progress.totalBytes) * 100); + const downloadedPercent = Math.floor((progress.downloadedBytes / progress.totalBytes) * 100); console.log(`Downloaded ${downloadedPercent}%`); }, p => { console.log(`Downlod complete, can be found on ${p.path}`); - //lets launch our application asset. - //launchDirApp(); + // lets launch our application asset. + // launchDirApp(); }, (reason, err) => { console.log(reason, err); }); // exit - fin.desktop.System.exit(function () { + fin.desktop.System.exit(() => { console.log("successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); // getAllApplications - fin.desktop.System.getAllApplications(function (applicationInfoList) { - applicationInfoList.forEach(function (applicationInfo) { + fin.desktop.System.getAllApplications(applicationInfoList => { + applicationInfoList.forEach(applicationInfo => { console.log("Showing information for application with uuid: " + applicationInfo.uuid); console.log("isRunning: ", applicationInfo.isRunning); @@ -269,32 +269,32 @@ function test_system() { }); }); // getAllWindows - fin.desktop.System.getAllWindows(function (windowInfoList) { - windowInfoList.forEach(function (windowInfo) { + fin.desktop.System.getAllWindows(windowInfoList => { + windowInfoList.forEach(windowInfo => { console.log("Showing information for application with uuid: ", windowInfo.uuid); console.log("Main window: ", windowInfo.mainWindow); console.log("Child windows: ", windowInfo.childWindows); }); }); // getCommandLineArguments - fin.desktop.System.getCommandLineArguments(function (args) { + fin.desktop.System.getCommandLineArguments(args => { console.log("The command line arguments are " + args); }); // getDeviceId - fin.desktop.System.getDeviceId(function (id) { + fin.desktop.System.getDeviceId(id => { console.log("The id of the device is: " + id); }); // getEnvironmentVariable - fin.desktop.System.getEnvironmentVariable("APPDATA", function (variable) { + fin.desktop.System.getEnvironmentVariable("APPDATA", variable => { console.log("this is the APPDATA value", variable); }); // getLog - fin.desktop.System.getLog('debug-2015-01-08-22-27-53.log', function (log) { + fin.desktop.System.getLog('debug-2015-01-08-22-27-53.log', log => { console.log(log); }); // getLogList - fin.desktop.System.getLogList(function (logList) { - logList.forEach(function (logInfo) { + fin.desktop.System.getLogList(logList => { + logList.forEach(logInfo => { console.log("The filename of the log is " + logInfo.name + ", the size is " + logInfo.size + ", and the date of creation is " + @@ -302,70 +302,70 @@ function test_system() { }); }); // getMonitorInfo - fin.desktop.System.getMonitorInfo(function (monitorInfo) { + fin.desktop.System.getMonitorInfo(monitorInfo => { console.log("This object contains information about all monitors: ", monitorInfo); }); // getMousePosition - fin.desktop.System.getMousePosition(function (mousePosition) { + fin.desktop.System.getMousePosition(mousePosition => { console.log("The mouse is located at left: " + mousePosition.left + ", top: " + mousePosition.top); }); // getProcessList - fin.desktop.System.getProcessList(function (list) { - list.forEach(function (process) { + fin.desktop.System.getProcessList(list => { + list.forEach(process => { console.log("UUID: " + process.uuid + ", Application Name: " + process.name); }); }); // getProxySettings - fin.desktop.System.getProxySettings(function (proxy) { + fin.desktop.System.getProxySettings(proxy => { console.log(proxy); }); // getRvmInfo - fin.desktop.System.getRvmInfo(function (rvmInfoObject) { + fin.desktop.System.getRvmInfo(rvmInfoObject => { console.log("RVM version:", rvmInfoObject.version); console.log("RVM has been running since:", rvmInfoObject["start-time"]); - }, function (err) { + }, err => { console.log("Failed to get rvm info, error message:", err); }); // getVersion - fin.desktop.System.getVersion(function (version) { + fin.desktop.System.getVersion(version => { console.log("The version is " + version); }); // launchExternalProcess fin.desktop.System.launchExternalProcess({ path: "notepad", arguments: "", - listener: function (result) { + listener(result) { console.log('the exit code', result.exitCode); } - }, function (payload) { + }, payload => { console.log('Success:', payload.uuid); - }, function (error) { + }, error => { console.log('Error:', error); }); // fin.desktop.System.launchExternalProcess({ - //Additionally note that the executable found in the zip file specified in appAssets - //will default to the one mentioned by appAssets.target - //If the the path below refers to a specific path it will override this default + // Additionally note that the executable found in the zip file specified in appAssets + // will default to the one mentioned by appAssets.target + // If the the path below refers to a specific path it will override this default alias: "myApp", - listener: function (result) { + listener(result) { console.log('the exit code', result.exitCode); } - }, function (payload) { + }, payload => { console.log('Success:', payload.uuid); - }, function (error) { + }, error => { console.log('Error:', error); }); // fin.desktop.System.launchExternalProcess({ alias: "myApp", arguments: "e f g", - listener: function (result) { + listener(result) { console.log('the exit code', result.exitCode); } - }, function (payload) { + }, payload => { console.log('Success:', payload.uuid); - }, function (error) { + }, error => { console.log('Error:', error); }); // @@ -377,94 +377,94 @@ function test_system() { subject: 'O=OpenFin INC., L=New York, S=NY, C=US', thumbprint: '‎3c a5 28 19 83 05 fe 69 88 e6 8f 4b 3a af c5 c5 1b 07 80 5b' }, - listener: function (result) { + listener(result) { console.log('the exit code', result.exitCode); } - }, function (payload) { + }, payload => { console.log('Success:', payload.uuid); - }, function (error) { + }, error => { console.log('Error:', error); }); // log - fin.desktop.System.log("info", "An example log message", function () { + fin.desktop.System.log("info", "An example log message", () => { console.log("message successfully logged"); - }, function (err) { + }, err => { console.log(err); }); // monitorExternalProcess fin.desktop.System.monitorExternalProcess({ pid: 2508, - listener: function (result) { + listener(result) { console.log('the exit code', result.exitCode); } - }, function (payload) { + }, payload => { console.log("The process is now being monitored: ", payload.uuid); - }, function (error) { + }, error => { console.log("Error:", error); }); // openUrlWithBrowser - fin.desktop.System.openUrlWithBrowser("https://developer.openf.in/", function () { + fin.desktop.System.openUrlWithBrowser("https://developer.openf.in/", () => { console.log("successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); // registerExternalConnection - fin.desktop.System.registerExternalConnection("remote-connection-uuid", function () { - console.log(arguments); + fin.desktop.System.registerExternalConnection("remote-connection-uuid", (...args: any[]) => { + console.log(args); }); // releaseExternalProcess fin.desktop.System.launchExternalProcess({ path: "notepad", arguments: "", - listener: function (result) { + listener(result) { console.log("The exit code", result.exitCode); } - }, function (result) { + }, result => { console.log("Result UUID is " + result.uuid); - //release it. - fin.desktop.System.releaseExternalProcess(result.uuid, function () { + // release it. + fin.desktop.System.releaseExternalProcess(result.uuid, () => { console.log("Process has been unmapped!"); - }, function (reason) { + }, reason => { console.log("failure: " + reason); }); }); // removeEventListener - let aRegisteredListener = (event: fin.SystemBaseEvent) => { }; - fin.desktop.System.removeEventListener("monitor-info-changed", aRegisteredListener, function () { + const aRegisteredListener = (event: fin.SystemBaseEvent) => { }; + fin.desktop.System.removeEventListener("monitor-info-changed", aRegisteredListener, () => { console.log("successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); // showDeveloperTools - fin.desktop.System.showDeveloperTools("uuid", "name", function () { + fin.desktop.System.showDeveloperTools("uuid", "name", () => { console.log("successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); - // terminateExternalProcess + // terminateExternalProcess fin.desktop.System.launchExternalProcess({ // notepad is in the system’s PATH path: "notepad", arguments: "", - listener: function (result) { + listener(result) { console.log("The exit code", result.exitCode); } - }, function (result) { + }, result => { console.log("Result UUID is " + result.uuid); // Attempt to close the process. Terminate after 4 seconds if it // has not done so. - fin.desktop.System.terminateExternalProcess(result.uuid, 4000, function (info) { + fin.desktop.System.terminateExternalProcess(result.uuid, 4000, info => { console.log("Termination result " + info.result); - }, function (reason) { + }, reason => { console.log("failure: " + reason); }); }); // updateProxySettings - fin.desktop.System.updateProxySettings("type", "proxyAddress", 8080, function () { + fin.desktop.System.updateProxySettings("type", "proxyAddress", 8080, () => { console.log('success'); - }, function (err) { + }, err => { console.log(err); }); } @@ -537,10 +537,10 @@ function test_window() { frame: false, resizable: false, state: "normal" - }, function () { + }, () => { var _win = finWindow.getNativeWindow(); - _win.addEventListener("DOMContentLoaded", function () { finWindow.show(); }); - }, function (error) { + _win.addEventListener("DOMContentLoaded", () => { finWindow.show(); }); + }, error => { console.log("Error creating window:", error); }); // getCurrent @@ -557,11 +557,11 @@ function test_window() { // wrap finWindow = fin.desktop.Window.wrap("uuid", "name"); // addEventListener - finWindow.addEventListener("bounds-changed", function (event) { + finWindow.addEventListener("bounds-changed", event => { console.log("The window has been moved or resized"); - }, function () { + }, () => { console.log("The registration was successful"); - }, function (reason) { + }, reason => { console.log("failure:" + reason); }); // animate @@ -577,7 +577,7 @@ function test_window() { } }, { interrupt: false - }, function (evt) { + }, evt => { // Callback will only fire after both "opacity" and "position" have finished animating. }); // authenticate @@ -601,34 +601,34 @@ function test_window() { // focus finWindow.focus(); // getBounds - finWindow.getBounds(function (bounds) { + finWindow.getBounds(bounds => { console.log("top: " + bounds.top + "left: " + bounds.left + "height: " + bounds.height + "width: " + bounds.width); }); // getOptions - finWindow.getOptions(function (options) { + finWindow.getOptions(options => { console.log(options); }); // getSnapshot - finWindow.getSnapshot(function (base64Snapshot) { + finWindow.getSnapshot(base64Snapshot => { console.log("data:image/png;base64," + base64Snapshot); }); // getState - finWindow.getState(function (state) { + finWindow.getState(state => { console.log("state: " + state); }); // getZoomLevel - finWindow.getZoomLevel(function (level) { + finWindow.getZoomLevel(level => { console.log("zoom level: " + level); - }, function (error) { + }, error => { console.log('error:', error); }); // hide finWindow.hide(); // isShowing - finWindow.isShowing(function (showing) { + finWindow.isShowing(showing => { console.log("the window is " + (showing ? "showing" : "hidden")); }); // joinGroup @@ -636,7 +636,7 @@ function test_window() { url: "http://www.openfin.co", name: "secondWindow", autoShow: true - }, function () { + }, () => { // When mainWindow moves or is moved, secondWindow moves by the same amount secondWindow.joinGroup(finWindow); }); @@ -645,10 +645,10 @@ function test_window() { url: "http://www.openfin.co", name: "secondWindow", autoShow: true - }, function () { + }, () => { // When finWindow moves or is moved, secondWindow moves by the same amount - secondWindow.joinGroup(finWindow, function () { - //once we are in the group, lets leave it. + secondWindow.joinGroup(finWindow, () => { + // once we are in the group, lets leave it. secondWindow.leaveGroup(); }); }); @@ -656,22 +656,22 @@ function test_window() { finWindow.maximize(); // mergeGroups { - let finWindowOne = new fin.desktop.Window({ + const finWindowOne = new fin.desktop.Window({ url: "http://www.openfin.co", name: "finWindowOne", autoShow: true }); - let finWindowTwo = new fin.desktop.Window({ + const finWindowTwo = new fin.desktop.Window({ url: "http://www.openfin.co", name: "finWindowTwo", autoShow: true }); - let finWindowThree = new fin.desktop.Window({ + const finWindowThree = new fin.desktop.Window({ url: "http://www.openfin.co", name: "finWindowThree", autoShow: true }); - let finWindowFour = new fin.desktop.Window({ + const finWindowFour = new fin.desktop.Window({ url: "http://www.openfin.co", name: "finWindowFour", autoShow: true @@ -690,7 +690,7 @@ function test_window() { // moveTo finWindow.moveTo(100, 200); // removeEventListener - let aRegisteredListener = (event: fin.WindowBaseEvent) => { }; + const aRegisteredListener = (event: fin.WindowBaseEvent) => { }; finWindow.removeEventListener("bounds-changed", aRegisteredListener); // resizeBy finWindow.resizeBy(10, 10, "top-right"); diff --git a/openfin/v15/tsconfig.json b/openfin/v15/tsconfig.json index 894da85738..6aee95c58a 100644 --- a/openfin/v15/tsconfig.json +++ b/openfin/v15/tsconfig.json @@ -1,25 +1,28 @@ { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../../", - "typeRoots": [ - "../../" - ], - "types": [], - "paths": { - "openfin": [ - "openfin/v15" - ] - }, - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "openfin-tests.ts" - ] -} + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "openfin": [ + "openfin/v15" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "openfin-tests.ts" + ] +} \ No newline at end of file diff --git a/openfin/v15/tslint.json b/openfin/v15/tslint.json index af53769b6b..e4f5db4fa0 100644 --- a/openfin/v15/tslint.json +++ b/openfin/v15/tslint.json @@ -1 +1,6 @@ -{ "extends": "../../tslint.json" } +{ + "extends": "../tslint.json", + "rules": { + "max-line-length": false + } +} diff --git a/optics-agent/optics-agent-tests.ts b/optics-agent/optics-agent-tests.ts index 75fafbd871..758b374efa 100644 --- a/optics-agent/optics-agent-tests.ts +++ b/optics-agent/optics-agent-tests.ts @@ -8,7 +8,6 @@ import OpticsAgent, { import { GraphQLSchema } from 'graphql'; import * as express from 'express'; import * as hapi from 'hapi'; -var OpticsAgentRequired = require('optics-agent'); const configOptions = { apiKey: "", @@ -20,18 +19,18 @@ const configOptions = { proxyUrl: "", reportIntervalMs: 1, }; -OpticsAgent.configureAgent(configOptions) +OpticsAgent.configureAgent(configOptions); -let expressServer = express(); +const expressServer = express(); expressServer.use(OpticsAgent.middleware()); -let hapiServer = new hapi.Server(); +const hapiServer = new hapi.Server(); OpticsAgent.instrumentHapiServer(hapiServer); -let req = {} as express.Request; +const req = {} as express.Request; OpticsAgent.context(req); const agent = new OpticsAgent.Agent({ apiKey: '1234' }); -let schema = {} as GraphQLSchema; +const schema = {} as GraphQLSchema; agent.instrumentSchema(schema); diff --git a/p-defer/tsconfig.json b/p-defer/tsconfig.json index c0e0daf1e6..ebf8e83a49 100644 --- a/p-defer/tsconfig.json +++ b/p-defer/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/package.json b/package.json index a9b9625069..1dad46394d 100644 --- a/package.json +++ b/package.json @@ -16,12 +16,13 @@ }, "scripts": { "compile-scripts": "tsc -p scripts", - "new-package": "node scripts/new-package.js", + "new-package": "dts-gen --dt", "not-needed": "node scripts/not-needed.js", "lint": "node scripts/lint.js", "test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed --nProcesses 1" }, "devDependencies": { - "types-publisher": "Microsoft/types-publisher#production" + "types-publisher": "Microsoft/types-publisher#production", + "dts-gen": "latest" } } diff --git a/pad/pad-tests.ts b/pad/pad-tests.ts index c808d303df..ccba560703 100644 --- a/pad/pad-tests.ts +++ b/pad/pad-tests.ts @@ -1,6 +1,6 @@ import pad = require('pad'); -pad('pad', 5) // "pad " -pad(5, 'pad') // " pad" -pad('pad', 5, '+') // "pad++" -pad(5, 'pad', '+') // "++pad" \ No newline at end of file +pad('pad', 5); // "pad " +pad(5, 'pad'); // " pad" +pad('pad', 5, '+'); // "pad++" +pad(5, 'pad', '+'); // "++pad" \ No newline at end of file diff --git a/pako/index.d.ts b/pako/index.d.ts index 2838272dbf..7f9b31f2b9 100644 --- a/pako/index.d.ts +++ b/pako/index.d.ts @@ -1,61 +1,84 @@ -// Type definitions for pako 0.2.8 +// Type definitions for pako 1.0.4 // Project: https://github.com/nodeca/pako -// Definitions by: Denis Cappellin +// Definitions by: Denis Cappellin , Caleb Eggensperger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = Pako; export as namespace pako; declare namespace Pako { + export interface DeflateOptions { + level?: number; + windowBits?: number; + memLevel?: number; + strategy?: number; + dictionary?: any; + raw?: boolean; + to?: 'string'; + } + + export interface InflateOptions { + windowBits?: number; + raw?: boolean; + to?: 'string'; + } + + export type Data = Uint8Array | Array | string; + /** * Compress data with deflate algorithm and options. */ - export function deflate( data: Uint8Array | Array | string, options?: any ): string; + export function deflate( data: Data, options: DeflateOptions & {to: 'string'} ): string; + export function deflate( data: Data, options?: DeflateOptions ): Uint8Array; + /** * The same as deflate, but creates raw data, without wrapper (header and adler32 crc). */ - export function deflateRaw( data: Uint8Array | Array | string, options?: any ): string; + export function deflateRaw( data: Data, options: DeflateOptions & {to: 'string'} ): string; + export function deflateRaw( data: Data, options?: DeflateOptions ): Uint8Array; + /** * The same as deflate, but create gzip wrapper instead of deflate one. */ - export function gzip( data: Uint8Array | Array | string, options?: any ): string; + export function gzip( data: Data, options: DeflateOptions & {to: 'string'} ): string; + export function gzip( data: Data, options?: DeflateOptions ): Uint8Array; + /** * Decompress data with inflate/ungzip and options. Autodetect format via wrapper header * by default. That's why we don't provide separate ungzip method. */ - export function inflate( data: Uint8Array | Array | string, options?: any ): Uint8Array; - export function inflate( data: Uint8Array | Array | string, options?: any ): Array; - export function inflate( data: Uint8Array | Array | string, options?: any ): String; + export function inflate( data: Data, options: InflateOptions & {to: 'string'} ): string; + export function inflate( data: Data, options?: InflateOptions ): Uint8Array; + /** * The same as inflate, but creates raw data, without wrapper (header and adler32 crc). */ - export function inflateRaw( data: Uint8Array | Array | string, options?: any ): Uint8Array; - export function inflateRaw( data: Uint8Array | Array | string, options?: any ): Array; - export function inflateRaw( data: Uint8Array | Array | string, options?: any ): string; + export function inflateRaw( data: Data, options: InflateOptions & {to: 'string'} ): string; + export function inflateRaw( data: Data, options?: InflateOptions ): Uint8Array; + /** * Just shortcut to inflate, because it autodetects format by header.content. Done for convenience. */ - export function ungzip( data: Uint8Array | Array | string, options?: any ): Uint8Array; - export function ungzip( data: Uint8Array | Array | string, options?: any ): Array; - export function ungzip( data: Uint8Array | Array | string, options?: any ): string; + export function ungzip( data: Data, options: InflateOptions & {to: 'string'} ): string; + export function ungzip( data: Data, options?: InflateOptions ): Uint8Array; export class Deflate { - constructor( options?: any ); + constructor( options?: DeflateOptions ); err: number; msg: string; result: Uint8Array | Array; - onData( chunk: Uint8Array | Array | string ): void; + onData( chunk: Data ): void; onEnd( status: number ): void; - push( data: Uint8Array | Array | ArrayBuffer | string, mode?: number | boolean ): boolean; + push( data: Data | ArrayBuffer, mode?: number | boolean ): boolean; } export class Inflate { - constructor( options?: any ); + constructor( options?: InflateOptions ); err: number; msg: string; - result: Uint8Array | Array | string; - onData( chunk: Uint8Array | Array | string ): void; + result: Data; + onData( chunk: Data ): void; onEnd( status: number ): void; - push( data: Uint8Array | Array | ArrayBuffer | string, mode?: number | boolean ): boolean; + push( data: Data | ArrayBuffer, mode?: number | boolean ): boolean; } } diff --git a/pako/pako-tests.ts b/pako/pako-tests.ts index e928fba9dc..5e5a6c3eef 100644 --- a/pako/pako-tests.ts +++ b/pako/pako-tests.ts @@ -5,13 +5,20 @@ import pako = require("pako"); var chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9]) var chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]); -var deflate = new pako.Deflate({ level: 3}); +var deflate = new pako.Deflate({ level: 3 }); deflate.push(chunk1, false); deflate.push(chunk2, true); // true -> last chunk -if (deflate.err) { - throw new Error( deflate.err.toString() ); +if (deflate.err) { + throw new Error( deflate.err.toString() ); } -console.log(deflate.result); \ No newline at end of file +console.log(deflate.result); + +let str: string = pako.deflate('1234', {to: 'string'}); +let arr: Uint8Array = pako.deflate('1234'); + +let str2: string = pako.inflate('1234', {to: 'string'}); +let arr2: Uint8Array = pako.inflate('1234'); + diff --git a/parse-torrent-file/tslint.json b/parse-torrent-file/tslint.json index ec365f164b..377cc837d4 100644 --- a/parse-torrent-file/tslint.json +++ b/parse-torrent-file/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/parse-torrent/parse-torrent-tests.ts b/parse-torrent/parse-torrent-tests.ts index dc20ff79e6..46d8b9e923 100644 --- a/parse-torrent/parse-torrent-tests.ts +++ b/parse-torrent/parse-torrent-tests.ts @@ -85,7 +85,7 @@ var buf = parseTorrent.toTorrentFile({ infoHash: 'd2474e86c95b19b8bcfdb92bc12c9d44667cfa36', }); -parseTorrent.remote('d2474e86c95b19b8bcfdb92bc12c9d44667cfa36', function(err, parsedTorrent) { +parseTorrent.remote('d2474e86c95b19b8bcfdb92bc12c9d44667cfa36', (err, parsedTorrent) => { // if (err) throw err // console.log(parsedTorrent) }); diff --git a/parse-torrent/tslint.json b/parse-torrent/tslint.json index ec365f164b..377cc837d4 100644 --- a/parse-torrent/tslint.json +++ b/parse-torrent/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/parsimmon/index.d.ts b/parsimmon/index.d.ts index 417cd962b5..ee196dd1ff 100644 --- a/parsimmon/index.d.ts +++ b/parsimmon/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for Parsimmon 1.0 // Project: https://github.com/jneen/parsimmon -// Definitions by: Bart van der Schoor , Mizunashi Mana , Boris Cherny , Benny van Reeven +// Definitions by: Bart van der Schoor +// Mizunashi Mana +// Boris Cherny +// Benny van Reeven // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** diff --git a/parsimmon/tslint.json b/parsimmon/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/parsimmon/tslint.json +++ b/parsimmon/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/passport-anonymous/passport-anonymous-tests.ts b/passport-anonymous/passport-anonymous-tests.ts index 3daa2474cf..0bdd2dda3f 100644 --- a/passport-anonymous/passport-anonymous-tests.ts +++ b/passport-anonymous/passport-anonymous-tests.ts @@ -1,4 +1,4 @@ import * as passport from "passport"; -import { Strategy } from "passport-anonymous"; +import { Strategy } from "passport-anonymous"; passport.use(new Strategy()); diff --git a/passport-anonymous/tslint.json b/passport-anonymous/tslint.json index f9e30021f4..377cc837d4 100644 --- a/passport-anonymous/tslint.json +++ b/passport-anonymous/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/passport-facebook/index.d.ts b/passport-facebook/index.d.ts index 7b6cedeac5..320a2169ba 100644 --- a/passport-facebook/index.d.ts +++ b/passport-facebook/index.d.ts @@ -33,9 +33,29 @@ interface IStrategyOption { profileFields?: string[]; } +interface IStrategyOptionWithRequest { + clientID: string; + clientSecret: string; + callbackURL: string; + + scopeSeparator?: string; + enableProof?: boolean; + profileFields?: string[]; + passReqToCallback: boolean; +} + +interface VerifyFunction { + (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void): void; +} + +interface VerifyFunctionWithRequest { + (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void): void; +} + declare class Strategy implements passport.Strategy { - constructor(options: IStrategyOption, - verify: (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void); + constructor(options: IStrategyOptionWithRequest, verify: VerifyFunctionWithRequest); + constructor(options: IStrategyOption, verify: VerifyFunction); + name: string; authenticate: (req: express.Request, options?: Object) => void; } diff --git a/passport-google-oauth/index.d.ts b/passport-google-oauth/index.d.ts index be135e9682..0dd283001b 100644 --- a/passport-google-oauth/index.d.ts +++ b/passport-google-oauth/index.d.ts @@ -22,7 +22,7 @@ interface IOAuthStrategyOption { consumerSecret: string; callbackURL: string; - reguestTokenURL?: string; + requestTokenURL?: string; accessTokenURL?: string; userAuthorizationURL?: string; sessionKey?: string; diff --git a/path-is-absolute/path-is-absolute-tests.ts b/path-is-absolute/path-is-absolute-tests.ts index fe7d177cc2..6948e290fa 100644 --- a/path-is-absolute/path-is-absolute-tests.ts +++ b/path-is-absolute/path-is-absolute-tests.ts @@ -2,22 +2,22 @@ import pathIsAbsolute = require('path-is-absolute'); // Running on Linux pathIsAbsolute('/home/foo'); -//=> true +// => true pathIsAbsolute('C:/Users/foo'); -//=> false +// => false // Running on Windows pathIsAbsolute('C:/Users/foo'); -//=> true +// => true pathIsAbsolute('/home/foo'); -//=> false +// => false // Running on any OS pathIsAbsolute.posix('/home/foo'); -//=> true +// => true pathIsAbsolute.posix('C:/Users/foo'); -//=> false +// => false pathIsAbsolute.win32('C:/Users/foo'); -//=> true +// => true pathIsAbsolute.win32('/home/foo'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/payment/index.d.ts b/payment/index.d.ts index e635a19028..33edc3ebe3 100644 --- a/payment/index.d.ts +++ b/payment/index.d.ts @@ -37,7 +37,7 @@ interface Fns { * * laser * * unionpay * * elo - * + * * The function will return null if the card type can't be determined. */ cardType(cardNumber: string): string; diff --git a/payment/tsconfig.json b/payment/tsconfig.json index 0b2323bef2..c284d0d6a4 100644 --- a/payment/tsconfig.json +++ b/payment/tsconfig.json @@ -1,7 +1,10 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6", + "dom" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +20,4 @@ "index.d.ts", "payment-tests.ts" ] -} +} \ No newline at end of file diff --git a/pbf/pbf-tests.ts b/pbf/pbf-tests.ts index 533c183801..39c67602d8 100644 --- a/pbf/pbf-tests.ts +++ b/pbf/pbf-tests.ts @@ -7,17 +7,17 @@ pbf.pos; pbf.type; pbf.length; pbf.destroy(); -pbf.readFields(function (tag) {}); -pbf.readFields(function (tag, result) {}); -pbf.readFields(function (tag, result, pbf) {}); -pbf.readFields(function (tag) {}, {}, 1); -pbf.readMessage(function (tag) {}); -pbf.readMessage(function (tag, result) {}); -pbf.readMessage(function (tag, result, pbf) {}); +pbf.readFields(tag => {}); +pbf.readFields((tag, result) => {}); +pbf.readFields((tag, result, pbf) => {}); +pbf.readFields(tag => {}, {}, 1); +pbf.readMessage(tag => {}); +pbf.readMessage((tag, result) => {}); +pbf.readMessage((tag, result, pbf) => {}); pbf.readFixed32(); pbf.readSFixed32(); pbf.readFixed64(); -pbf.readSFixed64(); +pbf.readSFixed64(); pbf.readFloat(); pbf.readDouble(); pbf.readVarint(); @@ -28,7 +28,7 @@ pbf.readBoolean(); pbf.readString(); pbf.readBytes(); pbf.readPackedVarint(); -pbf.readPackedVarint([], true); +pbf.readPackedVarint([], true); pbf.readPackedSVarint(); pbf.readPackedSVarint([]); pbf.readPackedBoolean(); @@ -60,12 +60,12 @@ pbf.writeString(''); pbf.writeFloat(1); pbf.writeDouble(1); pbf.writeBytes(new Uint8Array(1)); -pbf.writeRawMessage(function (obj) {}); -pbf.writeRawMessage(function (obj, pbf) {}); -pbf.writeRawMessage(function (obj) {}, {}); -pbf.writeMessage(1, function (obj) {}); -pbf.writeMessage(1, function (obj, pbf) {}); -pbf.writeMessage(1, function (obj) {}, {}); +pbf.writeRawMessage(obj => {}); +pbf.writeRawMessage((obj, pbf) => {}); +pbf.writeRawMessage(obj => {}, {}); +pbf.writeMessage(1, obj => {}); +pbf.writeMessage(1, (obj, pbf) => {}); +pbf.writeMessage(1, obj => {}, {}); pbf.writePackedVarint(1, []); pbf.writePackedSVarint(1, []); pbf.writePackedBoolean(1, []); diff --git a/pem/pem-tests.ts b/pem/pem-tests.ts index fd4ce11f6e..689dc42ad9 100644 --- a/pem/pem-tests.ts +++ b/pem/pem-tests.ts @@ -55,7 +55,7 @@ const tests = { }, 'Create 2048bit Private key with Password': (test: any) => { - pem.createPrivateKey(2048,{cipher:'des',password:'TestMe'}, (error: any, data: any) => { + pem.createPrivateKey(2048, {cipher: 'des', password: 'TestMe'}, (error: any, data: any) => { var key = (data && data.key || '').toString(); test.ifError(error); test.ok(key); @@ -137,7 +137,7 @@ const tests = { 'Create CSR with own encrypted key': (test: any) => { var password = 'my:secure! "password\'s\nawesome'; - pem.createPrivateKey(2048, { cipher: 'des3', password: password }, (error: any, data: any) => { + pem.createPrivateKey(2048, { cipher: 'des3', password }, (error: any, data: any) => { var key = (data && data.key || '').toString(); pem.createCSR({ @@ -514,7 +514,7 @@ const tests = { selfSigned: true }, (error: any, csr: any) => { - pem.createPkcs12(csr.clientKey, csr.certificate, 'mypassword', function(err: any, pkcs12: any){ + pem.createPkcs12(csr.clientKey, csr.certificate, 'mypassword', (err: any, pkcs12: any) => { test.ifError(err); test.ok(pkcs12); @@ -525,7 +525,7 @@ const tests = { }); }, 'Create PKCS12 with key password': (test: any) => { - pem.createPrivateKey({cipher:'aes128',password:'xxx'}, (error: any, data: any) => { + pem.createPrivateKey({cipher: 'aes128', password: 'xxx'}, (error: any, data: any) => { var key = (data && data.key || '').toString(); pem.createCertificate({ @@ -533,7 +533,7 @@ const tests = { selfSigned: true }, (error: any, csr: any) => { - pem.createPkcs12(csr.clientKey, csr.certificate, 'mypassword', {cipher: 'aes256', clientKeyPassword: 'xxx'}, function(err: any, pkcs12: any){ + pem.createPkcs12(csr.clientKey, csr.certificate, 'mypassword', {cipher: 'aes256', clientKeyPassword: 'xxx'}, (err: any, pkcs12: any) => { test.ifError(err); test.ok(pkcs12); diff --git a/pg/index.d.ts b/pg/index.d.ts index 67ed0c355d..ca3d6c0105 100644 --- a/pg/index.d.ts +++ b/pg/index.d.ts @@ -41,6 +41,7 @@ export interface PoolConfig extends ClientConfig { idleTimeoutMillis?: number; reapIntervalMillis?: number; returnToHead?: boolean; + application_name?: string; } export interface QueryConfig { diff --git a/phonon/index.d.ts b/phonon/index.d.ts new file mode 100644 index 0000000000..bd41d448c8 --- /dev/null +++ b/phonon/index.d.ts @@ -0,0 +1,203 @@ +// Type definitions for phonon 1.4 +// Project: https://github.com/quark-dev/Phonon-Framework +// Definitions by: Kévin SERIN +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace Phonon { + /*** Main object ***/ + interface Phonon { + device: PhononDeviceObject; + browser: PhononBrowserObject; + event: PhononEventObject; + options(options: PhononOptions): void; + navigator(): PhononNavigator; + i18n(): PhononI18n; + updateLocale(language: string): void; + ajax(request: PhononAjaxObject): PhononAjaxReturnObject; + onReady(callback: () => void): void; + panel(id: string): PhononPanelComponent; + sidePanel(id: string): PhononSidePanelComponent; + alert(text: string, title?: string, cancelable?: boolean, textOk?: string): PhononDialogComponent; + confirm(text: string, title?: string, cancelable?: boolean, textOk?: string, textCancel?: string): PhononDialogComponent; + prompt(text: string, title?: string, cancelable?: boolean, textOk?: string, textCancel?: string): PhononDialogComponent; + indicator(title: string, cancelable?: boolean): PhononIndicatorComponent; + dialog(id: string): PhononCustomDialogComponent; + notif(textOrId: string, timeout?: number, showButton?: boolean, textButton?: string): PhononNotifComponent; + popover(id?: string): PhononPopoverComponent; + preloader(element: string | Element): PhononPreloaderComponent; + tab(): PhononTabComponent; + autocomplete(input: Element | HTMLElement | string, o?: AwesompleteOptions): Awesomplete; + } + interface PhononDeviceObject { + os: string; + osVersion: string; + ANDROID: string; + IOS: string; + } + interface PhononBrowserObject { + name: string; + version: string; + } + interface PhononEventObject { + animationEnd: string; + transitionEnd: string; + } + interface PhononCustomWindowEvent extends Event { + detail: PhononDetail; + } + interface PhononDetail { + page: string; + req: string[]; + } + + /*** Options ***/ + interface PhononOptions { + navigator?: PhononNavigatorOptions; + i18n?: PhononI18nOptions | null; + } + interface PhononNavigatorOptions { + defaultPage?: string; + hashPrefix?: string; + animatePages?: boolean; + enableBrowserBackButton?: boolean; + templateRootDirectory?: string; + defaultTemplateExtension?: string; + useHash?: boolean; + } + interface PhononI18nOptions { + directory?: string; + localeFallback?: string; + localePreferred?: string; + } + + /*** Navigation ***/ + interface PhononNavigator { + currentPage: string; + previousPage: string; + changePage(pageName: string, parameter?: string): void; + on(page: PhononPageObject, callback?: (activity: PhononActivity) => void): void; + onPage(page: string): PhononPageEventObject; + start(): void; + } + interface PhononActivity { + onCreate(callback?: () => void): void; + onReady(callback?: () => void): void; + onClose(callback?: (self: PhononOnCloseObject) => void): void; + onHidden(callback?: () => void): void; + onTransitionEnd(callback?: () => void): void; + onHashChanged(callback?: (...hash: string[]) => void): void; + onTabChanged(callback?: (tabNumber: number) => void): void; + } + interface PhononPageObject { + page: string; + content?: string | null; + preventClose?: boolean; + readyDelay?: number; + } + interface PhononOnCloseObject { + close(): void; + } + interface PhononPageEventObject { + addEvent(event: string, callback: (parameter?: any) => void): void; + } + + /*** Internationalization ***/ + interface PhononI18n { + bind(element?: Element, callback?: () => void): void; + bind(callback?: () => void): void; + getAll(callback: (json: any) => void): void; + get(key: string, callback: (value: any) => void): void; + get(key: string[], callback: (values: any) => void): void; + getPreference(): string; + setPreference(newLanguage: string): void; + getLocale(): string; + } + + /*** Ajax ***/ + type PhononAjaxErrorFlag = "NO_INTERNET_ACCESS" | "TIMEOUT_EXCEEDED" | "XMLHTTPREQUEST_UNAVAILABLE" | "JSON_MALFORMED" | "REQUEST_CANCELED"; + interface PhononAjaxObject { + method: string; + url: string; + crossDomain?: boolean; + dataType: string; + contentType?: string; + data?: any; + timeout?: number; + headers?: any; + success(res: any, xhr: XMLHttpRequest): void; + error?(res: any, flagError: PhononAjaxErrorFlag, xhr: XMLHttpRequest): void; + } + interface PhononAjaxReturnObject { + cancel(): void; + } + + /*** Components ***/ + type PhononColor = "positive" | "negative"; + type PhononPopoverDirection = "left" | "title-left" | "right" | "title"; + interface PhononPanelComponent { + open(): void; + close(): void; + } + interface PhononSidePanelComponent { + open(): void; + close(): void; + } + interface PhononDialogComponent { + on(event: string, callback: (value?: any) => void): PhononDialogComponent; + } + interface PhononCustomDialogComponent extends PhononDialogComponent { + open(): void; + close(): void; + } + interface PhononIndicatorComponent extends PhononDialogComponent { + open(): void; + close(): void; + } + interface PhononNotifComponent { + setColor(color: PhononColor): PhononNotifComponent; + show(): PhononNotifComponent; + hide(): PhononNotifComponent; + } + interface PhononPopoverItem { + text: string; + value: string; + } + interface PhononPopoverComponent { + setList(list: string[] | PhononPopoverItem[]): PhononPopoverComponent; + setList(list: any[], itemBuilder?: (item: any) => void): PhononPopoverComponent; + attachButton(element: string|Element, autoBind?: boolean): PhononPopoverComponent; + open(direction: PhononPopoverDirection): PhononPopoverComponent; + openFrom(element: string|Element): PhononPopoverComponent; + close(): void; + onItemChanged(callback: (data: PhononPopoverItem) => void): PhononPopoverComponent; + } + interface PhononPreloaderComponent { + show(): void; + hide(): void; + } + interface PhononTabComponent { + setCurrentTab(pageName: string, tabNumber: number): void; + init(page?: string): void; + } +} + +interface Document { + on(event: string, callback: (event: Phonon.PhononCustomWindowEvent) => void, useCapture?: boolean): void; + off(event: string, callback: (event: Phonon.PhononCustomWindowEvent) => void, useCapture?: boolean): void; +} +interface Window { + on(event: string, callback: (event: Phonon.PhononCustomWindowEvent) => void, useCapture?: boolean): void; + off(event: string, callback: (event: Phonon.PhononCustomWindowEvent) => void, useCapture?: boolean): void; +} +interface Element { + on(event: string, callback: (event: any) => void, useCapture?: boolean): void; + off(event: string, callback: (event: any) => void, useCapture?: boolean): void; +} +interface NodeList { + on(event: string, callback: (event: any) => void, useCapture?: boolean): void; + off(event: string, callback: (event: any) => void, useCapture?: boolean): void; +} + +declare const phonon: Phonon.Phonon; diff --git a/phonon/phonon-tests.ts b/phonon/phonon-tests.ts new file mode 100644 index 0000000000..0d5df50b4e --- /dev/null +++ b/phonon/phonon-tests.ts @@ -0,0 +1,562 @@ +/// + +// Code examples from http://phonon.quarkdev.com/docs/navigator +phonon.options({ + navigator: { + defaultPage: 'home', + hashPrefix: '!', + animatePages: true, + enableBrowserBackButton: true, + templateRootDirectory: '', + defaultTemplateExtension: 'html', + useHash: true + }, + i18n: { + directory: 'res/lang/', + localeFallback: 'en', + localePreferred: 'en-US' + } +}); + +phonon.navigator().on({ + page: 'pagename', + content: 'content.html', + preventClose: false, + readyDelay: 1 +}, function(activity) { + activity.onCreate(function() {}); + activity.onReady(function() {}); + activity.onTransitionEnd(function() {}); + activity.onClose(function(self) {}); + activity.onHidden(function() {}); + activity.onHashChanged(function(req1, req2) {}); + activity.onTabChanged(function() {}) +}); + +phonon.navigator().onPage('home').addEvent('create', function () { +}); +phonon.navigator().onPage('home').addEvent('close', function (api) { + api.close(); +}); + +phonon.navigator().start(); + +phonon.navigator().changePage('page-name', 'optional-parameter'); +let page: string = phonon.navigator().currentPage; +page = phonon.navigator().previousPage; + + +let ev = document.createEvent(''); +document.on('pagecreated', function(event) { + console.log('global state pagecreated: ' + event.detail.page) +}); +document.on('pagehash', function(event) { + console.log('global state pagehash: ' + event.detail.page) + console.log(event.detail.req[0]); + console.log(event.detail.req[1]); + console.log(event.detail.req[2]); +}); + +// Code examples from http://phonon.quarkdev.com/docs/i18n +let element = document.createElement(''); +phonon.i18n().bind(); +phonon.i18n().bind(function() {}); +phonon.i18n().bind(element); +phonon.i18n().bind(element, function() {}); + +phonon.i18n().getAll(function(json) {}); +phonon.i18n().get('my_key', function(value) {}); +phonon.i18n().get(['my_key_1', 'my_key_two'], function(values) {}); + +phonon.updateLocale('new-language'); +phonon.i18n().setPreference("fr"); +phonon.i18n().getPreference(); +phonon.i18n().getLocale(); + +// Code examples from http://phonon.quarkdev.com/docs/ajax +var req = phonon.ajax({ + method: 'GET', + url: 'http://mysite.com/api/', + crossDomain: true, + dataType: 'json', + contentType: 'application/json', + data: {key1: 'val1', key2: 'val2'}, + timeout: 5000, + headers: { + 'header-name1': 'value1', + 'header-name2': 'value2' + }, + success: function(res, xhr) { + console.log(res); + }, + error: function(res, flagError, xhr) { + console.error(flagError); + console.log(res); + } +}); + +req.cancel(); + +// Code examples from http://phonon.quarkdev.com/docs/device +let os: string = phonon.device.os; +let osVersion: string = phonon.device.osVersion; +let browsername: string = phonon.browser.name; +let browserVersion: string = phonon.browser.version; + +// Code examples from http://phonon.quarkdev.com/docs/events +element.on('tap', function() {}); +phonon.onReady(function() {}); +document.querySelectorAll('.elements').on('tap', function() {}); + +element.off('tap', function() {}); +document.querySelectorAll('.elements').off('tap', function() {}); + +document.on('pageopened', function(evt) { + console.log(evt.detail.page + ' is opened'); +}); + +let animationEnd: string = phonon.event.animationEnd; +let transitionEnd: string = phonon.event.transitionEnd; + +// Code examples from http://phonon.quarkdev.com/docs/panels +phonon.panel('#my-panel-id').open(); +phonon.panel('#my-panel-id').close(); + +// Code examples from http://phonon.quarkdev.com/docs/side-panels +phonon.sidePanel('#side-panel-id').open(); +phonon.sidePanel('#side-panel-id').close(); + +// Code examples from http://phonon.quarkdev.com/docs/dialogs +let pAlert = phonon.alert("text", "title", true, "textOk"); +pAlert.on('confirm', function() {}); + +var pconfirm = phonon.confirm("text", "title", true, "textOk", "textCancel"); +pconfirm.on('confirm', function() {}) +pconfirm.on('cancel', function() {}); + +let pPrompt = phonon.prompt("text", "title", true, "textOk", "textCancel"); +pPrompt.on('confirm', function(inputValue) {}) +pPrompt.on('cancel', function() {}); + +phonon.indicator("title", true); + +let myDialog = phonon.dialog('#my-dialog'); +myDialog.open(); +myDialog.close(); +myDialog.on('confirm', function() {}); + +// Code examples from http://phonon.quarkdev.com/docs/notifications +let notif = phonon.notif('Hello', 3000, true, 'CANCEL'); +notif.setColor('positive'); + +notif = phonon.notif("#id"); +notif.show(); +notif.hide(); + +// Code examples from http://phonon.quarkdev.com/docs/popovers +let popover = phonon.popover(); +popover = phonon.popover('#popover-id'); + +popover.setList(['a', 'b', 'c']); +popover.setList([ + { + text: 'a', + value: 'a' + }, + { + text: 'b', + value: 'tg' + } +]); +popover.setList(['a', 'b', 'c'], function (item) { + var text = typeof item === 'string' ? item : item.text; + var value = typeof item === 'string' ? item : item.value; + return '
  • ' + text + '
  • '; +}); + +popover.attachButton('.button-trigger-popover', true); + +popover.attachButton(element, true); +popover.openFrom('.button-for-popover'); +popover.openFrom(element); + +popover.onItemChanged(function (data) { + console.log('onItemChanged') + console.error(data) +}); +element.on('itemchanged', function(event) { + console.log(event.detail); +}); + +popover = phonon.popover() + .setList(['a', 'b', 'c']) + .attachButton('.my-button', true) + .onItemChanged(function (data) { + console.log(data); + }).openFrom('.my-button'); + +// Code examples from http://phonon.quarkdev.com/docs/preloaders +phonon.preloader('#my-preloader').show(); +phonon.preloader('#my-preloader').hide(); + + +// Code examples from http://phonon.quarkdev.com/docs/tabs +let tabNumber = 2; +phonon.tab().setCurrentTab('pageName', tabNumber); + +phonon.tab().init(); +phonon.tab().init('pagename'); + +// Example from +phonon.options({ + navigator: { + defaultPage: 'home', + animatePages: true, + enableBrowserBackButton: true, + templateRootDirectory: './tpl' + }, + i18n: null +}); + +let app = phonon.navigator(); +app.on({page: 'home', preventClose: false, content: null}); +app.on({page: 'pagetwo', preventClose: true, content: 'pagetwo.html', readyDelay: 1}, function(activity) { + let action: string | null = null; + var onAction = function(evt: any) { + var target = evt.target; + action = 'ok'; + if(target.getAttribute('data-order') === 'order') { + phonon.alert('Thank you for your order!', 'Dear customer'); + } else { + phonon.alert('Your order has been canceled.', 'Dear customer'); + } + }; + activity.onCreate(function() { + let order = document.querySelector('.order'); + if (order != null) { + order.on('tap', onAction); + } + let cancel = document.querySelector('.cancel'); + if (cancel != null) { + cancel.on('tap', onAction); + } + }); + activity.onClose(function(self) { + if(action !== null) { + self.close(); + } else { + phonon.alert('Before leaving this page, you must perform an action.', 'Action required'); + } + }); + activity.onHidden(function() { + action = null; + }); + activity.onHashChanged(function(pizza) { + let pizzaElt = document.querySelector('.pizza'); + if (pizzaElt != null) { + pizzaElt.textContent = pizza; + } + }); +}); +app.start(); + +// Code example from http://phonon.quarkdev.com/App/public/phonon/kitchen-sink/index.html +phonon.options({ + navigator: { + defaultPage: 'home', + animatePages: true, + templateRootDirectory: 'contents/', + enableBrowserBackButton: true // should be disabled on Cordova + }, + i18n: { + directory: 'lang/', + localeFallback: 'en', + localePreferred: 'en-US' + } +}); + +var app2 = phonon.navigator(); +app2.on({page: 'home', content: 'home.html'}); +app2.on({page: 'pagedialog', content: 'pagedialog.html'}, function(activity) { + activity.onCreate(function() { + let showAlert = document.querySelector('#show-alert'); + if (showAlert) { + showAlert.on('tap', function() { + phonon.alert('Example', 'Hello'); + }); + } + + let showConfirm = document.querySelector('#show-confirm'); + if (showConfirm) { + showConfirm.on('tap', function() { + let confirm = phonon.confirm('Example', 'Hello'); + confirm.on('confirm', function() { + phonon.alert('Confirmed!'); + }); + confirm.on('cancel', function(value) { + phonon.alert('Canceled!'); + }); + }); + } + + let showPrompt = document.querySelector('#show-prompt'); + if (showPrompt) { + showPrompt.on('tap', function() { + var prompt = phonon.prompt('Example', 'Hello'); + prompt.on('confirm', function(value) { + phonon.alert(value, 'Inserted Value'); + }); + prompt.on('cancel', function() { + phonon.alert('Prompt Canceled'); + }); + }); + } + + let showIndicator = document.querySelector('#show-indicator'); + if (showIndicator) { + showIndicator.on('tap', function() { + let indicator = phonon.indicator('Please wait 3 seconds', false); + window.setTimeout(function() { + indicator.close(); + }, 3000); + }); + } + }); +}); + +app2.on({page: 'pageform', content: 'pageform.html'}); +app2.on({page: 'pagefla', content: 'pagefla.html'}); +app2.on({page: 'pagegrid', content: 'pagegrid.html'}); + +app2.on({page: 'pagelist', content: 'pagelist.html'}); +app2.on({page: 'pageaccordion', content: 'pageaccordion.html'}); + +app2.on({page: 'pagenotif', content: 'pagenotif.html', readyDelay: 500}, function(activity) { + + activity.onCreate(function() { + let showAutoNotif = document.querySelector('#show-auto-notif'); + if (showAutoNotif) { + showAutoNotif.on('tap', function() { + phonon.notif('HELLO', 3000, false); + }); + } + + let showNotif = document.querySelector('#show-notif'); + if (showNotif) { + showNotif.on('tap', function() { + phonon.notif('#notif-example').show(); + }); + } + + let showNotifButton = document.querySelector('#show-notif-button'); + if (showNotifButton) { + showNotifButton.on('tap', function() { + phonon.notif('HELLO', 3000, true, 'Bye'); + }); + } + }); + + activity.onReady(function() { + phonon.notif('Welcome!', 3000, true); + + }); +}); + +app2.on({page: 'pagepanel', content: 'pagepanel.html'}); +app2.on({page: 'pagepopover', content: 'pagepopover.html'}); +app2.on({page: 'pagepreloader', content: 'pagepreloader.html'}, function(activity) { + + activity.onReady(function() { + let myCircle = document.querySelector('#my-circle'); + if (myCircle) { + phonon.preloader(myCircle).show(); + } + let myDeterminate = document.querySelector('#my-determinate'); + if (myDeterminate) { + phonon.preloader(myDeterminate).show(); + } + }); + + activity.onHidden(function() { + let myCircle = document.querySelector('#my-circle'); + if (myCircle) { + phonon.preloader(myCircle).hide(); + } + let myDeterminate = document.querySelector('#my-determinate'); + if (myDeterminate) { + phonon.preloader(myDeterminate).hide(); + } + }); +}); + +app2.on({page: 'pagesidepanel', content: 'pagesidepanel.html'}); +app2.on({page: 'pagetable', content: 'pagetable.html'}); +app2.on({page: 'pagetabs', content: 'pagetabs.html'}, function(activity) { + activity.onTabChanged(function(tabNumber) { + let tab = document.querySelector('.tab-number'); + if (tab) { + tab.innerHTML = tabNumber + ""; + } + }); +}); +app2.start(); + +// Example from http://phonon.quarkdev.com/App/public/phonon/examples/components/accordion-example/#!home +phonon.options({ + navigator: { + defaultPage: 'home' + }, + i18n: null +}); +phonon.navigator().start(); + +// Example from http://phonon.quarkdev.com/App/public/phonon/examples/components/autocomplete-example/#!home +phonon.options({ + navigator: { + defaultPage: 'home' + }, + i18n: null +}); +phonon.navigator().on({ page: 'home' }, function(activity) { + activity.onReady(function(){ + // input where user typed words to query + let input = document.querySelector( '#searchJS' ); + let list = ''; + // external autocomplete + var req = phonon.ajax({ + method: "GET", + url: 'https://restcountries.eu/rest/v1/lang/en', + dataType: "json", + success: function( res, xhr ){ + list = res.map( function(i: any){ + return i.name; + }); + // initialize autocomplete + if (input) { + phonon.autocomplete( input, {list:list} ); + } + }, + error: function( res, flagError, xhr ){ + console.error(flagError); + console.log(res); + } + }); + }); +}); +phonon.navigator().start(); + +// Example from http://phonon.quarkdev.com/App/public/phonon/examples/components/dialogs-example/#!home +phonon.options({ + navigator: { + defaultPage: 'home', + animatePages: true, + templateRootDirectory: 'contents/', + enableBrowserBackButton: true // should be disabled on Cordova + }, + i18n: null +}); + +let app3 = phonon.navigator(); +app3.on({page: 'home', content: null}, function(activity) { + activity.onCreate(function() { + let element = document.querySelector('#show-alert'); + if (element) { + element.on('tap', function() { + phonon.alert('Example', 'Hello'); + }); + } + + element = document.querySelector('#show-confirm'); + if (element) { + element.on('tap', function() { + var confirm = phonon.confirm('Example', 'Hello'); + confirm.on('confirm', function() { + phonon.alert('Confirmed!'); + }); + confirm.on('cancel', function(value) { + phonon.alert('Canceled!'); + }); + }); + } + + element = document.querySelector('#show-prompt'); + if (element) { + element.on('tap', function() { + var prompt = phonon.prompt('Example', 'Hello'); + prompt.on('confirm', function(value) { + phonon.alert(value, 'Inserted Value'); + }); + prompt.on('cancel', function() { + phonon.alert('Prompt Canceled'); + }); + }); + } + + element = document.querySelector('#show-indicator'); + if (element) { + element.on('tap', function() { + var indicator = phonon.indicator('Please wait 3 seconds', false); + window.setTimeout(function() { + indicator.close(); + },3000); + }); + } + }); +}); +app3.start(); + +// Example from http://phonon.quarkdev.com/App/public/phonon/examples/components/i18n-example/#!home +let elPrefLang = document.querySelector('.pref-lang'); +let elLang = document.querySelector('.locale-lang'); +let elDefault = document.querySelector('.default-lang'); +let elSetFr = document.querySelector('.set-fr'); +let elSetEnGlobal = document.querySelector('.set-en-global'); +let elSetEnUs = document.querySelector('.set-en-us'); + +let defaultLocale = 'fr'; + +function setupHTML() { + let pref = (phonon.i18n().getPreference() ? phonon.i18n().getPreference() : 'not used'); + if (elPrefLang) { + elPrefLang.textContent = 'Preferred language : ' + pref; + } + if (elLang) { + elLang.textContent = 'Locale language : ' + phonon.i18n().getLocale(); + } + if (elDefault) { + elDefault.textContent = 'Default language : ' + defaultLocale; + } + + // The parameter is optional, if you pass nothing, i18n will bind all the document + phonon.i18n().bind(); +} + +var setPreference = function (evt: any) { + var target = evt.target; + var lang = target.getAttribute('data-l'); + if(lang) { + phonon.updateLocale(lang); + } +}; + +if (elSetFr) { + elSetFr.on('click', setPreference); +} +if (elSetEnGlobal) { + elSetEnGlobal.on('click', setPreference); +} +if (elSetEnUs) { + elSetEnUs.on('click', setPreference); +} +phonon.options({ + navigator: { + defaultPage: 'home', + }, + i18n: { + directory: 'res/lang/', + localeFallback: defaultLocale, + localePreferred: 'en' + } +}); +setupHTML(); +phonon.navigator().start(); diff --git a/phonon/tsconfig.json b/phonon/tsconfig.json new file mode 100644 index 0000000000..4532a718b0 --- /dev/null +++ b/phonon/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "phonon-tests.ts" + ] +} diff --git a/phonon/tslint.json b/phonon/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/phonon/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/pikaday-time/pikaday-time-tests.ts b/pikaday-time/pikaday-time-tests.ts index d118639229..3dcaf17dcd 100644 --- a/pikaday-time/pikaday-time-tests.ts +++ b/pikaday-time/pikaday-time-tests.ts @@ -7,9 +7,9 @@ new Pikaday({field: document.getElementById('datepicker')}); new Pikaday({field: $('#datepicker')[0]}); (() => { - var field:HTMLInputElement = document.getElementById('datepicker'); + var field: HTMLInputElement = document.getElementById('datepicker'); var picker = new Pikaday({ - onSelect: function (date:Date) { + onSelect(date: Date) { field.value = picker.toString(); console.log(date.toISOString()); } @@ -21,7 +21,7 @@ new Pikaday({field: $('#datepicker')[0]}); var picker = new Pikaday({ field: document.getElementById('datepicker'), format: 'D MMM YYYY', - onSelect: function () { + onSelect() { console.log(this.getMoment().format('Do MMMM YYYY')); } }); @@ -38,10 +38,10 @@ new Pikaday({field: $('#datepicker')[0]}); picker.nextMonth(); picker.prevMonth(); picker.gotoYear(2015); - picker.setMinDate(new Date); - picker.setMaxDate(new Date); - picker.setStartRange(new Date); - picker.setEndRange(new Date); + picker.setMinDate(new Date()); + picker.setMaxDate(new Date()); + picker.setStartRange(new Date()); + picker.setEndRange(new Date()); picker.isVisible(); picker.show(); picker.adjustPosition(); diff --git a/pikaday-time/tslint.json b/pikaday-time/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/pikaday-time/tslint.json +++ b/pikaday-time/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/pixi-spine/index.d.ts b/pixi-spine/index.d.ts index c88c7baa2c..deb614c749 100644 --- a/pixi-spine/index.d.ts +++ b/pixi-spine/index.d.ts @@ -3,1037 +3,1040 @@ // Definitions by: Ivan Popelyshev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -declare module PIXI.spine.core { - class Animation { - name: string; - timelines: Array; - duration: number; - constructor(name: string, timelines: Array, duration: number); - apply(skeleton: Skeleton, lastTime: number, time: number, loop: boolean, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; - static binarySearch(values: ArrayLike, target: number, step?: number): number; - static linearSearch(values: ArrayLike, target: number, step: number): number; +import * as PPP from "pixi.js"; + +declare module "pixi.js" { + namespace spine.core { + class Animation { + name: string; + timelines: Timeline[]; + duration: number; + constructor(name: string, timelines: Timeline[], duration: number); + apply(skeleton: Skeleton, lastTime: number, time: number, loop: boolean, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + static binarySearch(values: ArrayLike, target: number, step?: number): number; + static linearSearch(values: ArrayLike, target: number, step: number): number; + } + interface Timeline { + apply(skeleton: Skeleton, lastTime: number, time: number, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + getPropertyId(): number; + } + enum TimelineType { + rotate = 0, + translate = 1, + scale = 2, + shear = 3, + attachment = 4, + color = 5, + deform = 6, + event = 7, + drawOrder = 8, + ikConstraint = 9, + transformConstraint = 10, + pathConstraintPosition = 11, + pathConstraintSpacing = 12, + pathConstraintMix = 13, + } + abstract class CurveTimeline implements Timeline { + static LINEAR: number; + static STEPPED: number; + static BEZIER: number; + static BEZIER_SIZE: number; + private curves; + abstract getPropertyId(): number; + constructor(frameCount: number); + getFrameCount(): number; + setLinear(frameIndex: number): void; + setStepped(frameIndex: number): void; + getCurveType(frameIndex: number): number; + setCurve(frameIndex: number, cx1: number, cy1: number, cx2: number, cy2: number): void; + getCurvePercent(frameIndex: number, percent: number): number; + abstract apply(skeleton: Skeleton, lastTime: number, time: number, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class RotateTimeline extends CurveTimeline { + static ENTRIES: number; + static PREV_TIME: number; + static PREV_ROTATION: number; + static ROTATION: number; + boneIndex: number; + frames: ArrayLike; + constructor(frameCount: number); + getPropertyId(): number; + setFrame(frameIndex: number, time: number, degrees: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class TranslateTimeline extends CurveTimeline { + static ENTRIES: number; + static PREV_TIME: number; + static PREV_X: number; + static PREV_Y: number; + static X: number; + static Y: number; + boneIndex: number; + frames: ArrayLike; + constructor(frameCount: number); + getPropertyId(): number; + setFrame(frameIndex: number, time: number, x: number, y: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class ScaleTimeline extends TranslateTimeline { + constructor(frameCount: number); + getPropertyId(): number; + apply(skeleton: Skeleton, lastTime: number, time: number, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class ShearTimeline extends TranslateTimeline { + constructor(frameCount: number); + getPropertyId(): number; + apply(skeleton: Skeleton, lastTime: number, time: number, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class ColorTimeline extends CurveTimeline { + static ENTRIES: number; + static PREV_TIME: number; + static PREV_R: number; + static PREV_G: number; + static PREV_B: number; + static PREV_A: number; + static R: number; + static G: number; + static B: number; + static A: number; + slotIndex: number; + frames: ArrayLike; + constructor(frameCount: number); + getPropertyId(): number; + setFrame(frameIndex: number, time: number, r: number, g: number, b: number, a: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class AttachmentTimeline implements Timeline { + slotIndex: number; + frames: ArrayLike; + attachmentNames: string[]; + constructor(frameCount: number); + getPropertyId(): number; + getFrameCount(): number; + setFrame(frameIndex: number, time: number, attachmentName: string): void; + apply(skeleton: Skeleton, lastTime: number, time: number, events: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class DeformTimeline extends CurveTimeline { + slotIndex: number; + attachment: VertexAttachment; + frames: ArrayLike; + frameVertices: Array>; + constructor(frameCount: number); + getPropertyId(): number; + setFrame(frameIndex: number, time: number, vertices: ArrayLike): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class EventTimeline implements Timeline { + frames: ArrayLike; + events: Event[]; + constructor(frameCount: number); + getPropertyId(): number; + getFrameCount(): number; + setFrame(frameIndex: number, event: Event): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class DrawOrderTimeline implements Timeline { + frames: ArrayLike; + drawOrders: number[][]; + constructor(frameCount: number); + getPropertyId(): number; + getFrameCount(): number; + setFrame(frameIndex: number, time: number, drawOrder: number[]): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class IkConstraintTimeline extends CurveTimeline { + static ENTRIES: number; + static PREV_TIME: number; + static PREV_MIX: number; + static PREV_BEND_DIRECTION: number; + static MIX: number; + static BEND_DIRECTION: number; + ikConstraintIndex: number; + frames: ArrayLike; + constructor(frameCount: number); + getPropertyId(): number; + setFrame(frameIndex: number, time: number, mix: number, bendDirection: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class TransformConstraintTimeline extends CurveTimeline { + static ENTRIES: number; + static PREV_TIME: number; + static PREV_ROTATE: number; + static PREV_TRANSLATE: number; + static PREV_SCALE: number; + static PREV_SHEAR: number; + static ROTATE: number; + static TRANSLATE: number; + static SCALE: number; + static SHEAR: number; + transformConstraintIndex: number; + frames: ArrayLike; + constructor(frameCount: number); + getPropertyId(): number; + setFrame(frameIndex: number, time: number, rotateMix: number, translateMix: number, scaleMix: number, shearMix: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class PathConstraintPositionTimeline extends CurveTimeline { + static ENTRIES: number; + static PREV_TIME: number; + static PREV_VALUE: number; + static VALUE: number; + pathConstraintIndex: number; + frames: ArrayLike; + constructor(frameCount: number); + getPropertyId(): number; + setFrame(frameIndex: number, time: number, value: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class PathConstraintSpacingTimeline extends PathConstraintPositionTimeline { + constructor(frameCount: number); + getPropertyId(): number; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class PathConstraintMixTimeline extends CurveTimeline { + static ENTRIES: number; + static PREV_TIME: number; + static PREV_ROTATE: number; + static PREV_TRANSLATE: number; + static ROTATE: number; + static TRANSLATE: number; + pathConstraintIndex: number; + frames: ArrayLike; + constructor(frameCount: number); + getPropertyId(): number; + setFrame(frameIndex: number, time: number, rotateMix: number, translateMix: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number, setupPose: boolean, mixingOut: boolean): void; + } } - interface Timeline { - apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; - getPropertyId(): number; + namespace spine.core { + class AnimationState { + static emptyAnimation: Animation; + data: AnimationStateData; + tracks: TrackEntry[]; + events: Event[]; + listeners: AnimationStateListener2[]; + queue: EventQueue; + propertyIDs: IntSet; + animationsChanged: boolean; + timeScale: number; + trackEntryPool: Pool; + constructor(data: AnimationStateData); + update(delta: number): void; + updateMixingFrom(entry: TrackEntry, delta: number, canEnd: boolean): void; + apply(skeleton: Skeleton): void; + applyMixingFrom(entry: TrackEntry, skeleton: Skeleton): number; + applyRotateTimeline(timeline: Timeline, skeleton: Skeleton, time: number, alpha: number, setupPose: boolean, timelinesRotation: number[], i: number, firstFrame: boolean): void; + queueEvents(entry: TrackEntry, animationTime: number): void; + clearTracks(): void; + clearTrack(trackIndex: number): void; + setCurrent(index: number, current: TrackEntry): void; + setAnimation(trackIndex: number, animationName: string, loop: boolean): TrackEntry; + setAnimationWith(trackIndex: number, animation: Animation, loop: boolean): TrackEntry; + addAnimation(trackIndex: number, animationName: string, loop: boolean, delay: number): TrackEntry; + addAnimationWith(trackIndex: number, animation: Animation, loop: boolean, delay: number): TrackEntry; + setEmptyAnimation(trackIndex: number, mixDuration: number): TrackEntry; + addEmptyAnimation(trackIndex: number, mixDuration: number, delay: number): TrackEntry; + setEmptyAnimations(mixDuration: number): void; + expandToIndex(index: number): TrackEntry; + trackEntry(trackIndex: number, animation: Animation, loop: boolean, last: TrackEntry): TrackEntry; + disposeNext(entry: TrackEntry): void; + _animationsChanged(): void; + setTimelinesFirst(entry: TrackEntry): void; + checkTimelinesFirst(entry: TrackEntry): void; + checkTimelinesUsage(entry: TrackEntry, usageArray: boolean[]): void; + getCurrent(trackIndex: number): TrackEntry; + addListener(listener: AnimationStateListener2): void; + removeListener(listener: AnimationStateListener2): void; + clearListeners(): void; + clearListenerNotifications(): void; + onComplete: (trackIndex: number, loopCount: number) => any; + onEvent: (trackIndex: number, event: Event) => any; + onStart: (trackIndex: number) => any; + onEnd: (trackIndex: number) => any; + private static deprecatedWarning1; + setAnimationByName(trackIndex: number, animationName: string, loop: boolean): void; + private static deprecatedWarning2; + addAnimationByName(trackIndex: number, animationName: string, loop: boolean, delay: number): void; + private static deprecatedWarning3; + hasAnimationByName(animationName: string): boolean; + } + class TrackEntry { + animation: Animation; + next: TrackEntry; + mixingFrom: TrackEntry; + listener: AnimationStateListener2; + trackIndex: number; + loop: boolean; + eventThreshold: number; + attachmentThreshold: number; + drawOrderThreshold: number; + animationStart: number; + animationEnd: number; + animationLast: number; + nextAnimationLast: number; + delay: number; + trackTime: number; + trackLast: number; + nextTrackLast: number; + trackEnd: number; + timeScale: number; + alpha: number; + mixTime: number; + mixDuration: number; + mixAlpha: number; + timelinesFirst: boolean[]; + timelinesRotation: number[]; + reset(): void; + getAnimationTime(): number; + setAnimationLast(animationLast: number): void; + isComplete(): boolean; + resetRotationDirections(): void; + onComplete: (trackIndex: number, loopCount: number) => any; + onEvent: (trackIndex: number, event: Event) => any; + onStart: (trackIndex: number) => any; + onEnd: (trackIndex: number) => any; + private static deprecatedWarning1; + private static deprecatedWarning2; + time: number; + endTime: number; + loopsCount(): number; + } + class EventQueue { + objects: any[]; + drainDisabled: boolean; + animState: AnimationState; + constructor(animState: AnimationState); + start(entry: TrackEntry): void; + interrupt(entry: TrackEntry): void; + end(entry: TrackEntry): void; + dispose(entry: TrackEntry): void; + complete(entry: TrackEntry): void; + event(entry: TrackEntry, event: Event): void; + private static deprecatedWarning1; + deprecateStuff(): boolean; + drain(): void; + clear(): void; + } + enum EventType { + start = 0, + interrupt = 1, + end = 2, + dispose = 3, + complete = 4, + event = 5, + } + interface AnimationStateListener2 { + start(entry: TrackEntry): void; + interrupt(entry: TrackEntry): void; + end(entry: TrackEntry): void; + dispose(entry: TrackEntry): void; + complete(entry: TrackEntry): void; + event(entry: TrackEntry, event: Event): void; + } + abstract class AnimationStateAdapter2 implements AnimationStateListener2 { + start(entry: TrackEntry): void; + interrupt(entry: TrackEntry): void; + end(entry: TrackEntry): void; + dispose(entry: TrackEntry): void; + complete(entry: TrackEntry): void; + event(entry: TrackEntry, event: Event): void; + } } - enum TimelineType { - rotate = 0, - translate = 1, - scale = 2, - shear = 3, - attachment = 4, - color = 5, - deform = 6, - event = 7, - drawOrder = 8, - ikConstraint = 9, - transformConstraint = 10, - pathConstraintPosition = 11, - pathConstraintSpacing = 12, - pathConstraintMix = 13, + namespace spine.core { + class AnimationStateData { + skeletonData: SkeletonData; + animationToMixTime: Map; + defaultMix: number; + constructor(skeletonData: SkeletonData); + setMix(fromName: string, toName: string, duration: number): void; + private static deprecatedWarning1; + setMixByName(fromName: string, toName: string, duration: number): void; + setMixWith(from: Animation, to: Animation, duration: number): void; + getMix(from: Animation, to: Animation): number; + } } - abstract class CurveTimeline implements Timeline { - static LINEAR: number; - static STEPPED: number; - static BEZIER: number; - static BEZIER_SIZE: number; - private curves; - abstract getPropertyId(): number; - constructor(frameCount: number); - getFrameCount(): number; - setLinear(frameIndex: number): void; - setStepped(frameIndex: number): void; - getCurveType(frameIndex: number): number; - setCurve(frameIndex: number, cx1: number, cy1: number, cx2: number, cy2: number): void; - getCurvePercent(frameIndex: number, percent: number): number; - abstract apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + namespace spine.core { + class AtlasAttachmentLoader implements AttachmentLoader { + atlas: TextureAtlas; + constructor(atlas: TextureAtlas); + newRegionAttachment(skin: Skin, name: string, path: string): RegionAttachment; + newMeshAttachment(skin: Skin, name: string, path: string): MeshAttachment; + newBoundingBoxAttachment(skin: Skin, name: string): BoundingBoxAttachment; + newPathAttachment(skin: Skin, name: string): PathAttachment; + } } - class RotateTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_ROTATION: number; - static ROTATION: number; - boneIndex: number; - frames: ArrayLike; - constructor(frameCount: number); - getPropertyId(): number; - setFrame(frameIndex: number, time: number, degrees: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + namespace spine.core { + abstract class Attachment { + name: string; + constructor(name: string); + } + abstract class VertexAttachment extends Attachment { + bones: number[]; + vertices: ArrayLike; + worldVerticesLength: number; + constructor(name: string); + computeWorldVertices(slot: Slot, worldVertices: ArrayLike): void; + computeWorldVerticesWith(slot: Slot, start: number, count: number, worldVertices: ArrayLike, offset: number): void; + applyDeform(sourceAttachment: VertexAttachment): boolean; + } } - class TranslateTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_X: number; - static PREV_Y: number; - static X: number; - static Y: number; - boneIndex: number; - frames: ArrayLike; - constructor(frameCount: number); - getPropertyId(): number; - setFrame(frameIndex: number, time: number, x: number, y: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + namespace spine.core { + interface AttachmentLoader { + newRegionAttachment(skin: Skin, name: string, path: string): RegionAttachment; + newMeshAttachment(skin: Skin, name: string, path: string): MeshAttachment; + newBoundingBoxAttachment(skin: Skin, name: string): BoundingBoxAttachment; + newPathAttachment(skin: Skin, name: string): PathAttachment; + } } - class ScaleTimeline extends TranslateTimeline { - constructor(frameCount: number); - getPropertyId(): number; - apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + namespace spine.core { + enum AttachmentType { + Region = 0, + BoundingBox = 1, + Mesh = 2, + LinkedMesh = 3, + Path = 4, + } } - class ShearTimeline extends TranslateTimeline { - constructor(frameCount: number); - getPropertyId(): number; - apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + namespace spine.core { + class BoundingBoxAttachment extends VertexAttachment { + color: Color; + constructor(name: string); + } } - class ColorTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_R: number; - static PREV_G: number; - static PREV_B: number; - static PREV_A: number; - static R: number; - static G: number; - static B: number; - static A: number; - slotIndex: number; - frames: ArrayLike; - constructor(frameCount: number); - getPropertyId(): number; - setFrame(frameIndex: number, time: number, r: number, g: number, b: number, a: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + namespace spine.core { + class MeshAttachment extends VertexAttachment { + region: TextureRegion; + path: string; + regionUVs: ArrayLike; + triangles: number[]; + color: Color; + hullLength: number; + private parentMesh; + inheritDeform: boolean; + tempColor: Color; + constructor(name: string); + updateWorldVertices(slot: Slot, premultipliedAlpha: boolean): ArrayLike; + updateUVs(region: TextureRegion, uvs: ArrayLike): ArrayLike; + applyDeform(sourceAttachment: VertexAttachment): boolean; + getParentMesh(): MeshAttachment; + setParentMesh(parentMesh: MeshAttachment): void; + } } - class AttachmentTimeline implements Timeline { - slotIndex: number; - frames: ArrayLike; - attachmentNames: Array; - constructor(frameCount: number); - getPropertyId(): number; - getFrameCount(): number; - setFrame(frameIndex: number, time: number, attachmentName: string): void; - apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + namespace spine.core { + class PathAttachment extends VertexAttachment { + lengths: number[]; + closed: boolean; + constantSpeed: boolean; + color: Color; + constructor(name: string); + } } - class DeformTimeline extends CurveTimeline { - slotIndex: number; - attachment: VertexAttachment; - frames: ArrayLike; - frameVertices: Array>; - constructor(frameCount: number); - getPropertyId(): number; - setFrame(frameIndex: number, time: number, vertices: ArrayLike): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + namespace spine.core { + class RegionAttachment extends Attachment { + x: number; + y: number; + scaleX: number; + scaleY: number; + rotation: number; + width: number; + height: number; + color: Color; + path: string; + region: TextureRegion; + constructor(name: string); + updateWorldVertices(slot: Slot, premultipliedAlpha: boolean): ArrayLike; + } } - class EventTimeline implements Timeline { - frames: ArrayLike; - events: Array; - constructor(frameCount: number); - getPropertyId(): number; - getFrameCount(): number; - setFrame(frameIndex: number, event: Event): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + namespace spine.core { + enum BlendMode { + Normal = 0, + Additive = 1, + Multiply = 2, + Screen = 3, + } } - class DrawOrderTimeline implements Timeline { - frames: ArrayLike; - drawOrders: Array>; - constructor(frameCount: number); - getPropertyId(): number; - getFrameCount(): number; - setFrame(frameIndex: number, time: number, drawOrder: Array): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + namespace spine.core { + class Bone implements Updatable { + static yDown: boolean; + matrix: Matrix; + readonly worldX: number; + readonly worldY: number; + data: BoneData; + skeleton: Skeleton; + parent: Bone; + children: Bone[]; + x: number; + y: number; + rotation: number; + scaleX: number; + scaleY: number; + shearX: number; + shearY: number; + ax: number; + ay: number; + arotation: number; + ascaleX: number; + ascaleY: number; + ashearX: number; + ashearY: number; + appliedValid: boolean; + sorted: boolean; + constructor(data: BoneData, skeleton: Skeleton, parent: Bone); + update(): void; + updateWorldTransform(): void; + updateWorldTransformWith(x: number, y: number, rotation: number, scaleX: number, scaleY: number, shearX: number, shearY: number): void; + setToSetupPose(): void; + getWorldRotationX(): number; + getWorldRotationY(): number; + getWorldScaleX(): number; + getWorldScaleY(): number; + worldToLocalRotationX(): number; + worldToLocalRotationY(): number; + rotateWorld(degrees: number): void; + updateAppliedTransform(): void; + worldToLocal(world: Vector2): Vector2; + localToWorld(local: Vector2): Vector2; + } } - class IkConstraintTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_MIX: number; - static PREV_BEND_DIRECTION: number; - static MIX: number; - static BEND_DIRECTION: number; - ikConstraintIndex: number; - frames: ArrayLike; - constructor(frameCount: number); - getPropertyId(): number; - setFrame(frameIndex: number, time: number, mix: number, bendDirection: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + namespace spine.core { + class BoneData { + index: number; + name: string; + parent: BoneData; + length: number; + x: number; + y: number; + rotation: number; + scaleX: number; + scaleY: number; + shearX: number; + shearY: number; + transformMode: TransformMode; + constructor(index: number, name: string, parent: BoneData); + } + enum TransformMode { + Normal = 0, + OnlyTranslation = 1, + NoRotationOrReflection = 2, + NoScale = 3, + NoScaleOrReflection = 4, + } } - class TransformConstraintTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_ROTATE: number; - static PREV_TRANSLATE: number; - static PREV_SCALE: number; - static PREV_SHEAR: number; - static ROTATE: number; - static TRANSLATE: number; - static SCALE: number; - static SHEAR: number; - transformConstraintIndex: number; - frames: ArrayLike; - constructor(frameCount: number); - getPropertyId(): number; - setFrame(frameIndex: number, time: number, rotateMix: number, translateMix: number, scaleMix: number, shearMix: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + namespace spine.core { + interface Constraint extends Updatable { + getOrder(): number; + } } - class PathConstraintPositionTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_VALUE: number; - static VALUE: number; - pathConstraintIndex: number; - frames: ArrayLike; - constructor(frameCount: number); - getPropertyId(): number; - setFrame(frameIndex: number, time: number, value: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + namespace spine.core { + class Event { + data: EventData; + intValue: number; + floatValue: number; + stringValue: string; + time: number; + constructor(time: number, data: EventData); + } } - class PathConstraintSpacingTimeline extends PathConstraintPositionTimeline { - constructor(frameCount: number); - getPropertyId(): number; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + namespace spine.core { + class EventData { + name: string; + intValue: number; + floatValue: number; + stringValue: string; + constructor(name: string); + } } - class PathConstraintMixTimeline extends CurveTimeline { - static ENTRIES: number; - static PREV_TIME: number; - static PREV_ROTATE: number; - static PREV_TRANSLATE: number; - static ROTATE: number; - static TRANSLATE: number; - pathConstraintIndex: number; - frames: ArrayLike; - constructor(frameCount: number); - getPropertyId(): number; - setFrame(frameIndex: number, time: number, rotateMix: number, translateMix: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; - } -} -declare module PIXI.spine.core { - class AnimationState { - static emptyAnimation: Animation; - data: AnimationStateData; - tracks: TrackEntry[]; - events: Event[]; - listeners: AnimationStateListener2[]; - queue: EventQueue; - propertyIDs: IntSet; - animationsChanged: boolean; - timeScale: number; - trackEntryPool: Pool; - constructor(data: AnimationStateData); - update(delta: number): void; - updateMixingFrom(entry: TrackEntry, delta: number, canEnd: boolean): void; - apply(skeleton: Skeleton): void; - applyMixingFrom(entry: TrackEntry, skeleton: Skeleton): number; - applyRotateTimeline(timeline: Timeline, skeleton: Skeleton, time: number, alpha: number, setupPose: boolean, timelinesRotation: Array, i: number, firstFrame: boolean): void; - queueEvents(entry: TrackEntry, animationTime: number): void; - clearTracks(): void; - clearTrack(trackIndex: number): void; - setCurrent(index: number, current: TrackEntry): void; - setAnimation(trackIndex: number, animationName: string, loop: boolean): TrackEntry; - setAnimationWith(trackIndex: number, animation: Animation, loop: boolean): TrackEntry; - addAnimation(trackIndex: number, animationName: string, loop: boolean, delay: number): TrackEntry; - addAnimationWith(trackIndex: number, animation: Animation, loop: boolean, delay: number): TrackEntry; - setEmptyAnimation(trackIndex: number, mixDuration: number): TrackEntry; - addEmptyAnimation(trackIndex: number, mixDuration: number, delay: number): TrackEntry; - setEmptyAnimations(mixDuration: number): void; - expandToIndex(index: number): TrackEntry; - trackEntry(trackIndex: number, animation: Animation, loop: boolean, last: TrackEntry): TrackEntry; - disposeNext(entry: TrackEntry): void; - _animationsChanged(): void; - setTimelinesFirst(entry: TrackEntry): void; - checkTimelinesFirst(entry: TrackEntry): void; - checkTimelinesUsage(entry: TrackEntry, usageArray: Array): void; - getCurrent(trackIndex: number): TrackEntry; - addListener(listener: AnimationStateListener2): void; - removeListener(listener: AnimationStateListener2): void; - clearListeners(): void; - clearListenerNotifications(): void; - onComplete: (trackIndex: number, loopCount: number) => any; - onEvent: (trackIndex: number, event: Event) => any; - onStart: (trackIndex: number) => any; - onEnd: (trackIndex: number) => any; - private static deprecatedWarning1; - setAnimationByName(trackIndex: number, animationName: string, loop: boolean): void; - private static deprecatedWarning2; - addAnimationByName(trackIndex: number, animationName: string, loop: boolean, delay: number): void; - private static deprecatedWarning3; - hasAnimationByName(animationName: string): boolean; - } - class TrackEntry { - animation: Animation; - next: TrackEntry; - mixingFrom: TrackEntry; - listener: AnimationStateListener2; - trackIndex: number; - loop: boolean; - eventThreshold: number; - attachmentThreshold: number; - drawOrderThreshold: number; - animationStart: number; - animationEnd: number; - animationLast: number; - nextAnimationLast: number; - delay: number; - trackTime: number; - trackLast: number; - nextTrackLast: number; - trackEnd: number; - timeScale: number; - alpha: number; - mixTime: number; - mixDuration: number; - mixAlpha: number; - timelinesFirst: boolean[]; - timelinesRotation: number[]; - reset(): void; - getAnimationTime(): number; - setAnimationLast(animationLast: number): void; - isComplete(): boolean; - resetRotationDirections(): void; - onComplete: (trackIndex: number, loopCount: number) => any; - onEvent: (trackIndex: number, event: Event) => any; - onStart: (trackIndex: number) => any; - onEnd: (trackIndex: number) => any; - private static deprecatedWarning1; - private static deprecatedWarning2; - time: number; - endTime: number; - loopsCount(): number; - } - class EventQueue { - objects: Array; - drainDisabled: boolean; - animState: AnimationState; - constructor(animState: AnimationState); - start(entry: TrackEntry): void; - interrupt(entry: TrackEntry): void; - end(entry: TrackEntry): void; - dispose(entry: TrackEntry): void; - complete(entry: TrackEntry): void; - event(entry: TrackEntry, event: Event): void; - private static deprecatedWarning1; - deprecateStuff(): boolean; - drain(): void; - clear(): void; - } - enum EventType { - start = 0, - interrupt = 1, - end = 2, - dispose = 3, - complete = 4, - event = 5, - } - interface AnimationStateListener2 { - start(entry: TrackEntry): void; - interrupt(entry: TrackEntry): void; - end(entry: TrackEntry): void; - dispose(entry: TrackEntry): void; - complete(entry: TrackEntry): void; - event(entry: TrackEntry, event: Event): void; - } - abstract class AnimationStateAdapter2 implements AnimationStateListener2 { - start(entry: TrackEntry): void; - interrupt(entry: TrackEntry): void; - end(entry: TrackEntry): void; - dispose(entry: TrackEntry): void; - complete(entry: TrackEntry): void; - event(entry: TrackEntry, event: Event): void; - } -} -declare module PIXI.spine.core { - class AnimationStateData { - skeletonData: SkeletonData; - animationToMixTime: Map; - defaultMix: number; - constructor(skeletonData: SkeletonData); - setMix(fromName: string, toName: string, duration: number): void; - private static deprecatedWarning1; - setMixByName(fromName: string, toName: string, duration: number): void; - setMixWith(from: Animation, to: Animation, duration: number): void; - getMix(from: Animation, to: Animation): number; - } -} -declare module PIXI.spine.core { - class AtlasAttachmentLoader implements AttachmentLoader { - atlas: TextureAtlas; - constructor(atlas: TextureAtlas); - newRegionAttachment(skin: Skin, name: string, path: string): RegionAttachment; - newMeshAttachment(skin: Skin, name: string, path: string): MeshAttachment; - newBoundingBoxAttachment(skin: Skin, name: string): BoundingBoxAttachment; - newPathAttachment(skin: Skin, name: string): PathAttachment; - } -} -declare module PIXI.spine.core { - abstract class Attachment { - name: string; - constructor(name: string); - } - abstract class VertexAttachment extends Attachment { - bones: Array; - vertices: ArrayLike; - worldVerticesLength: number; - constructor(name: string); - computeWorldVertices(slot: Slot, worldVertices: ArrayLike): void; - computeWorldVerticesWith(slot: Slot, start: number, count: number, worldVertices: ArrayLike, offset: number): void; - applyDeform(sourceAttachment: VertexAttachment): boolean; - } -} -declare module PIXI.spine.core { - interface AttachmentLoader { - newRegionAttachment(skin: Skin, name: string, path: string): RegionAttachment; - newMeshAttachment(skin: Skin, name: string, path: string): MeshAttachment; - newBoundingBoxAttachment(skin: Skin, name: string): BoundingBoxAttachment; - newPathAttachment(skin: Skin, name: string): PathAttachment; - } -} -declare module PIXI.spine.core { - enum AttachmentType { - Region = 0, - BoundingBox = 1, - Mesh = 2, - LinkedMesh = 3, - Path = 4, - } -} -declare module PIXI.spine.core { - class BoundingBoxAttachment extends VertexAttachment { - color: Color; - constructor(name: string); - } -} -declare module PIXI.spine.core { - class MeshAttachment extends VertexAttachment { - region: TextureRegion; - path: string; - regionUVs: ArrayLike; - triangles: Array; - color: Color; - hullLength: number; - private parentMesh; - inheritDeform: boolean; - tempColor: Color; - constructor(name: string); - updateWorldVertices(slot: Slot, premultipliedAlpha: boolean): ArrayLike; - updateUVs(region: TextureRegion, uvs: ArrayLike): ArrayLike; - applyDeform(sourceAttachment: VertexAttachment): boolean; - getParentMesh(): MeshAttachment; - setParentMesh(parentMesh: MeshAttachment): void; - } -} -declare module PIXI.spine.core { - class PathAttachment extends VertexAttachment { - lengths: Array; - closed: boolean; - constantSpeed: boolean; - color: Color; - constructor(name: string); - } -} -declare module PIXI.spine.core { - class RegionAttachment extends Attachment { - x: number; - y: number; - scaleX: number; - scaleY: number; - rotation: number; - width: number; - height: number; - color: Color; - path: string; - region: TextureRegion; - constructor(name: string); - updateWorldVertices(slot: Slot, premultipliedAlpha: boolean): ArrayLike; - } -} -declare module PIXI.spine.core { - enum BlendMode { - Normal = 0, - Additive = 1, - Multiply = 2, - Screen = 3, - } -} -declare module PIXI.spine.core { - class Bone implements Updatable { - static yDown: boolean; - matrix: Matrix; - readonly worldX: number; - readonly worldY: number; - data: BoneData; - skeleton: Skeleton; - parent: Bone; - children: Bone[]; - x: number; - y: number; - rotation: number; - scaleX: number; - scaleY: number; - shearX: number; - shearY: number; - ax: number; - ay: number; - arotation: number; - ascaleX: number; - ascaleY: number; - ashearX: number; - ashearY: number; - appliedValid: boolean; - sorted: boolean; - constructor(data: BoneData, skeleton: Skeleton, parent: Bone); - update(): void; - updateWorldTransform(): void; - updateWorldTransformWith(x: number, y: number, rotation: number, scaleX: number, scaleY: number, shearX: number, shearY: number): void; - setToSetupPose(): void; - getWorldRotationX(): number; - getWorldRotationY(): number; - getWorldScaleX(): number; - getWorldScaleY(): number; - worldToLocalRotationX(): number; - worldToLocalRotationY(): number; - rotateWorld(degrees: number): void; - updateAppliedTransform(): void; - worldToLocal(world: Vector2): Vector2; - localToWorld(local: Vector2): Vector2; - } -} -declare module PIXI.spine.core { - class BoneData { - index: number; - name: string; - parent: BoneData; - length: number; - x: number; - y: number; - rotation: number; - scaleX: number; - scaleY: number; - shearX: number; - shearY: number; - transformMode: TransformMode; - constructor(index: number, name: string, parent: BoneData); - } - enum TransformMode { - Normal = 0, - OnlyTranslation = 1, - NoRotationOrReflection = 2, - NoScale = 3, - NoScaleOrReflection = 4, - } -} -declare module PIXI.spine.core { - interface Constraint extends Updatable { - getOrder(): number; - } -} -declare module PIXI.spine.core { - class Event { - data: EventData; - intValue: number; - floatValue: number; - stringValue: string; - time: number; - constructor(time: number, data: EventData); - } -} -declare module PIXI.spine.core { - class EventData { - name: string; - intValue: number; - floatValue: number; - stringValue: string; - constructor(name: string); - } -} -declare module PIXI.spine.core { - class IkConstraint implements Constraint { - data: IkConstraintData; - bones: Array; - target: Bone; - mix: number; - bendDirection: number; - level: number; - constructor(data: IkConstraintData, skeleton: Skeleton); - getOrder(): number; - apply(): void; - update(): void; - apply1(bone: Bone, targetX: number, targetY: number, alpha: number): void; - apply2(parent: Bone, child: Bone, targetX: number, targetY: number, bendDir: number, alpha: number): void; - } -} -declare module PIXI.spine.core { - class IkConstraintData { - name: string; - order: number; - bones: BoneData[]; - target: BoneData; - bendDirection: number; - mix: number; - constructor(name: string); - } -} -declare module PIXI.spine.core { - class PathConstraint implements Constraint { - static NONE: number; - static BEFORE: number; - static AFTER: number; - data: PathConstraintData; - bones: Array; - target: Slot; - position: number; - spacing: number; - rotateMix: number; - translateMix: number; - spaces: number[]; - positions: number[]; - world: number[]; - curves: number[]; - lengths: number[]; - segments: number[]; - constructor(data: PathConstraintData, skeleton: Skeleton); - apply(): void; - update(): void; - computeWorldPositions(path: PathAttachment, spacesCount: number, tangents: boolean, percentPosition: boolean, percentSpacing: boolean): number[]; - addBeforePosition(p: number, temp: Array, i: number, out: Array, o: number): void; - addAfterPosition(p: number, temp: Array, i: number, out: Array, o: number): void; - addCurvePosition(p: number, x1: number, y1: number, cx1: number, cy1: number, cx2: number, cy2: number, x2: number, y2: number, out: Array, o: number, tangents: boolean): void; - getOrder(): number; - } -} -declare module PIXI.spine.core { - class PathConstraintData { - name: string; - order: number; - bones: BoneData[]; - target: SlotData; - positionMode: PositionMode; - spacingMode: SpacingMode; - rotateMode: RotateMode; - offsetRotation: number; - position: number; - spacing: number; - rotateMix: number; - translateMix: number; - constructor(name: string); - } - enum PositionMode { - Fixed = 0, - Percent = 1, - } - enum SpacingMode { - Length = 0, - Fixed = 1, - Percent = 2, - } - enum RotateMode { - Tangent = 0, - Chain = 1, - ChainScale = 2, - } -} -declare module PIXI.spine.core { - class Skeleton { - data: SkeletonData; - bones: Array; - slots: Array; - drawOrder: Array; - ikConstraints: Array; - transformConstraints: Array; - pathConstraints: Array; - _updateCache: Updatable[]; - updateCacheReset: Updatable[]; - skin: Skin; - color: Color; - time: number; - flipX: boolean; - flipY: boolean; - x: number; - y: number; - constructor(data: SkeletonData); - updateCache(): void; - sortIkConstraint(constraint: IkConstraint): void; - sortPathConstraint(constraint: PathConstraint): void; - sortTransformConstraint(constraint: TransformConstraint): void; - sortPathConstraintAttachment(skin: Skin, slotIndex: number, slotBone: Bone): void; - sortPathConstraintAttachmentWith(attachment: Attachment, slotBone: Bone): void; - sortBone(bone: Bone): void; - sortReset(bones: Array): void; - updateWorldTransform(): void; - setToSetupPose(): void; - setBonesToSetupPose(): void; - setSlotsToSetupPose(): void; - getRootBone(): Bone; - findBone(boneName: string): Bone; - findBoneIndex(boneName: string): number; - findSlot(slotName: string): Slot; - findSlotIndex(slotName: string): number; - setSkinByName(skinName: string): void; - setSkin(newSkin: Skin): void; - getAttachmentByName(slotName: string, attachmentName: string): Attachment; - getAttachment(slotIndex: number, attachmentName: string): Attachment; - setAttachment(slotName: string, attachmentName: string): void; - findIkConstraint(constraintName: string): IkConstraint; - findTransformConstraint(constraintName: string): TransformConstraint; - findPathConstraint(constraintName: string): PathConstraint; - getBounds(offset: Vector2, size: Vector2): void; - update(delta: number): void; - } -} -declare module PIXI.spine.core { - class SkeletonBounds { - minX: number; - minY: number; - maxX: number; - maxY: number; - boundingBoxes: BoundingBoxAttachment[]; - polygons: ArrayLike[]; - private polygonPool; - update(skeleton: Skeleton, updateAabb: boolean): void; - aabbCompute(): void; - aabbContainsPoint(x: number, y: number): boolean; - aabbIntersectsSegment(x1: number, y1: number, x2: number, y2: number): boolean; - aabbIntersectsSkeleton(bounds: SkeletonBounds): boolean; - containsPoint(x: number, y: number): BoundingBoxAttachment; - containsPointPolygon(polygon: ArrayLike, x: number, y: number): boolean; - intersectsSegment(x1: number, y1: number, x2: number, y2: number): BoundingBoxAttachment; - intersectsSegmentPolygon(polygon: ArrayLike, x1: number, y1: number, x2: number, y2: number): boolean; - getPolygon(boundingBox: BoundingBoxAttachment): ArrayLike; - getWidth(): number; - getHeight(): number; - } -} -declare module PIXI.spine.core { - class SkeletonData { - name: string; - bones: BoneData[]; - slots: SlotData[]; - skins: Skin[]; - defaultSkin: Skin; - events: EventData[]; - animations: Animation[]; - ikConstraints: IkConstraintData[]; - transformConstraints: TransformConstraintData[]; - pathConstraints: PathConstraintData[]; - width: number; - height: number; - version: string; - hash: string; - fps: number; - imagesPath: string; - findBone(boneName: string): BoneData; - findBoneIndex(boneName: string): number; - findSlot(slotName: string): SlotData; - findSlotIndex(slotName: string): number; - findSkin(skinName: string): Skin; - findEvent(eventDataName: string): EventData; - findAnimation(animationName: string): Animation; - findIkConstraint(constraintName: string): IkConstraintData; - findTransformConstraint(constraintName: string): TransformConstraintData; - findPathConstraint(constraintName: string): PathConstraintData; - findPathConstraintIndex(pathConstraintName: string): number; - } -} -declare module PIXI.spine.core { - class SkeletonJson { - attachmentLoader: AttachmentLoader; - scale: number; - private linkedMeshes; - constructor(attachmentLoader: AttachmentLoader); - readSkeletonData(json: string | any): SkeletonData; - readAttachment(map: any, skin: Skin, slotIndex: number, name: string): Attachment; - readVertices(map: any, attachment: VertexAttachment, verticesLength: number): void; - readAnimation(map: any, name: string, skeletonData: SkeletonData): void; - readCurve(map: any, timeline: CurveTimeline, frameIndex: number): void; - getValue(map: any, prop: string, defaultValue: any): any; - static blendModeFromString(str: string): number; - static positionModeFromString(str: string): PositionMode; - static spacingModeFromString(str: string): SpacingMode; - static rotateModeFromString(str: string): RotateMode; - static transformModeFromString(str: string): TransformMode; - static transformModeLegacy(inheritRotation: boolean, inheritScale: boolean): TransformMode; - } -} -declare module PIXI.spine.core { - class Skin { - name: string; - attachments: Map[]; - constructor(name: string); - addAttachment(slotIndex: number, name: string, attachment: Attachment): void; - getAttachment(slotIndex: number, name: string): Attachment; - attachAll(skeleton: Skeleton, oldSkin: Skin): void; - } -} -declare module PIXI.spine.core { - class Slot { - currentMesh: any; - currentSprite: any; - meshes: any; - currentMeshName: String; - sprites: any; - currentSpriteName: String; - blendMode: number; - tempRegion: TextureRegion; - tempAttachment: Attachment; - data: SlotData; - bone: Bone; - color: Color; - attachment: Attachment; - private attachmentTime; - attachmentVertices: number[]; - constructor(data: SlotData, bone: Bone); - getAttachment(): Attachment; - setAttachment(attachment: Attachment): void; - setAttachmentTime(time: number): void; - getAttachmentTime(): number; - setToSetupPose(): void; - } -} -declare module PIXI.spine.core { - class SlotData { - index: number; - name: string; - boneData: BoneData; - color: Color; - attachmentName: string; - blendMode: number; - constructor(index: number, name: string, boneData: BoneData); - } -} -declare module PIXI.spine.core { - abstract class Texture { - protected _image: HTMLImageElement; - constructor(image: HTMLImageElement); - getImage(): HTMLImageElement; - abstract setFilters(minFilter: TextureFilter, magFilter: TextureFilter): void; - abstract setWraps(uWrap: TextureWrap, vWrap: TextureWrap): void; - abstract dispose(): void; - static filterFromString(text: string): TextureFilter; - static wrapFromString(text: string): TextureWrap; - } - enum TextureFilter { - Nearest = 9728, - Linear = 9729, - MipMap = 9987, - MipMapNearestNearest = 9984, - MipMapLinearNearest = 9985, - MipMapNearestLinear = 9986, - MipMapLinearLinear = 9987, - } - enum TextureWrap { - MirroredRepeat = 33648, - ClampToEdge = 33071, - Repeat = 10497, - } - class TextureRegion { - texture: PIXI.Texture; - size: PIXI.Rectangle; - readonly width: number; - readonly height: number; - readonly u: number; - readonly v: number; - readonly u2: number; - readonly v2: number; - readonly offsetX: number; - readonly offsetY: number; - readonly pixiOffsetY: number; - readonly spineOffsetY: number; - readonly originalWidth: number; - readonly originalHeight: number; - readonly x: number; - readonly y: number; - readonly rotate: boolean; - } -} -declare module PIXI.spine.core { - class TextureAtlas implements Disposable { - pages: TextureAtlasPage[]; - regions: TextureAtlasRegion[]; - constructor(atlasText: string, textureLoader: (path: string, loaderFunction: (tex: PIXI.BaseTexture) => any) => any, callback: (obj: TextureAtlas) => any); - addTexture(name: string, texture: PIXI.Texture): TextureAtlasRegion; - addTextureHash(textures: Map, stripExtension: boolean): void; - addSpineAtlas(atlasText: string, textureLoader: (path: string, loaderFunction: (tex: PIXI.BaseTexture) => any) => any, callback: (obj: TextureAtlas) => any): void; - private load(atlasText, textureLoader, callback); - findRegion(name: string): TextureAtlasRegion; - dispose(): void; - } - class TextureAtlasPage { - name: string; - minFilter: TextureFilter; - magFilter: TextureFilter; - uWrap: TextureWrap; - vWrap: TextureWrap; - baseTexture: PIXI.BaseTexture; - width: number; - height: number; - setFilters(): void; - } - class TextureAtlasRegion extends TextureRegion { - page: TextureAtlasPage; - name: string; - index: number; - } -} -declare module PIXI.spine.core { - class TransformConstraint implements Constraint { - data: TransformConstraintData; - bones: Array; - target: Bone; - rotateMix: number; - translateMix: number; - scaleMix: number; - shearMix: number; - temp: Vector2; - constructor(data: TransformConstraintData, skeleton: Skeleton); - apply(): void; - update(): void; - getOrder(): number; - } -} -declare module PIXI.spine.core { - class TransformConstraintData { - name: string; - order: number; - bones: BoneData[]; - target: BoneData; - rotateMix: number; - translateMix: number; - scaleMix: number; - shearMix: number; - offsetRotation: number; - offsetX: number; - offsetY: number; - offsetScaleX: number; - offsetScaleY: number; - offsetShearY: number; - constructor(name: string); - } -} -declare module PIXI.spine.core { - interface Updatable { - update(): void; - } -} -declare module PIXI.spine.core { - interface Map { - [key: string]: T; - } - class IntSet { - array: number[]; - add(value: number): boolean; - contains(value: number): boolean; - remove(value: number): void; - clear(): void; - } - interface Disposable { - dispose(): void; - } - class Color { - r: number; - g: number; - b: number; - a: number; - static WHITE: Color; - static RED: Color; - static GREEN: Color; - static BLUE: Color; - static MAGENTA: Color; - constructor(r?: number, g?: number, b?: number, a?: number); - set(r: number, g: number, b: number, a: number): this; - setFromColor(c: Color): this; - setFromString(hex: string): this; - add(r: number, g: number, b: number, a: number): this; - clamp(): this; - } - class MathUtils { - static PI: number; - static PI2: number; - static radiansToDegrees: number; - static radDeg: number; - static degreesToRadians: number; - static degRad: number; - static clamp(value: number, min: number, max: number): number; - static cosDeg(degrees: number): number; - static sinDeg(degrees: number): number; - static signum(value: number): number; - static toInt(x: number): number; - static cbrt(x: number): number; - } - class Utils { - static SUPPORTS_TYPED_ARRAYS: boolean; - static arrayCopy(source: ArrayLike, sourceStart: number, dest: ArrayLike, destStart: number, numElements: number): void; - static setArraySize(array: Array, size: number, value?: any): Array; - static ensureArrayCapacity(array: Array, size: number, value?: any): Array; - static newArray(size: number, defaultValue: T): Array; - static newFloatArray(size: number): ArrayLike; - static toFloatArray(array: Array): number[] | Float32Array; - } - class DebugUtils { - static logBones(skeleton: Skeleton): void; - } - class Pool { - private items; - private instantiator; - constructor(instantiator: () => T); - obtain(): T; - free(item: T): void; - freeAll(items: ArrayLike): void; - clear(): void; - } - class Vector2 { - x: number; - y: number; - constructor(x?: number, y?: number); - set(x: number, y: number): Vector2; - length(): number; - normalize(): this; - } - class TimeKeeper { - maxDelta: number; - framesPerSecond: number; - delta: number; - totalTime: number; - private lastTime; - private frameCount; - private frameTime; - update(): void; - } - interface ArrayLike { - length: number; - [n: number]: T; - } -} -declare module PIXI.spine { - function atlasParser(): (resource: loaders.Resource, next: () => any) => any; - function imageLoaderAdapter(loader: any, namePrefix: any, baseUrl: any, imageOptions: any): (line: String, callback: (baseTexture: BaseTexture) => any) => void; - function syncImageLoaderAdapter(baseUrl: any, crossOrigin: any): (line: any, callback: any) => void; -} -declare module PIXI.spine { - class SpineSprite extends PIXI.Sprite { - region: core.TextureRegion; - constructor(tex: PIXI.Texture); - } - class SpineMesh extends PIXI.mesh.Mesh { - region: core.TextureRegion; - constructor(texture: PIXI.Texture, vertices?: Float32Array, uvs?: Float32Array, indices?: Uint16Array, drawMode?: number); - } - class Spine extends PIXI.Container { - static globalAutoUpdate: boolean; - tintRgb: ArrayLike; - spineData: core.SkeletonData; - skeleton: core.Skeleton; - stateData: core.AnimationStateData; - state: core.AnimationState; - slotContainers: Array; - constructor(spineData: core.SkeletonData); - autoUpdate: boolean; - tint: number; - update(dt: number): void; - private setSpriteRegion(attachment, sprite, region); - private setMeshRegion(attachment, mesh, region); - protected lastTime: number; - autoUpdateTransform(): void; - createSprite(slot: core.Slot, attachment: core.RegionAttachment, defName: string): SpineSprite; - createMesh(slot: core.Slot, attachment: core.MeshAttachment): SpineMesh; - hackTextureBySlotIndex(slotIndex: number, texture?: PIXI.Texture, size?: PIXI.Rectangle): boolean; - hackTextureBySlotName: (slotName: String, texture?: Texture, size?: Rectangle) => any; + namespace spine.core { + class IkConstraint implements Constraint { + data: IkConstraintData; + bones: Bone[]; + target: Bone; + mix: number; + bendDirection: number; + level: number; + constructor(data: IkConstraintData, skeleton: Skeleton); + getOrder(): number; + apply(): void; + update(): void; + apply1(bone: Bone, targetX: number, targetY: number, alpha: number): void; + apply2(parent: Bone, child: Bone, targetX: number, targetY: number, bendDir: number, alpha: number): void; + } + } + namespace spine.core { + class IkConstraintData { + name: string; + order: number; + bones: BoneData[]; + target: BoneData; + bendDirection: number; + mix: number; + constructor(name: string); + } + } + namespace spine.core { + class PathConstraint implements Constraint { + static NONE: number; + static BEFORE: number; + static AFTER: number; + data: PathConstraintData; + bones: Bone[]; + target: Slot; + position: number; + spacing: number; + rotateMix: number; + translateMix: number; + spaces: number[]; + positions: number[]; + world: number[]; + curves: number[]; + lengths: number[]; + segments: number[]; + constructor(data: PathConstraintData, skeleton: Skeleton); + apply(): void; + update(): void; + computeWorldPositions(path: PathAttachment, spacesCount: number, tangents: boolean, percentPosition: boolean, percentSpacing: boolean): number[]; + addBeforePosition(p: number, temp: number[], i: number, out: number[], o: number): void; + addAfterPosition(p: number, temp: number[], i: number, out: number[], o: number): void; + addCurvePosition(p: number, x1: number, y1: number, cx1: number, cy1: number, cx2: number, cy2: number, x2: number, y2: number, out: number[], o: number, tangents: boolean): void; + getOrder(): number; + } + } + namespace spine.core { + class PathConstraintData { + name: string; + order: number; + bones: BoneData[]; + target: SlotData; + positionMode: PositionMode; + spacingMode: SpacingMode; + rotateMode: RotateMode; + offsetRotation: number; + position: number; + spacing: number; + rotateMix: number; + translateMix: number; + constructor(name: string); + } + enum PositionMode { + Fixed = 0, + Percent = 1, + } + enum SpacingMode { + Length = 0, + Fixed = 1, + Percent = 2, + } + enum RotateMode { + Tangent = 0, + Chain = 1, + ChainScale = 2, + } + } + namespace spine.core { + class Skeleton { + data: SkeletonData; + bones: Bone[]; + slots: Slot[]; + drawOrder: Slot[]; + ikConstraints: IkConstraint[]; + transformConstraints: TransformConstraint[]; + pathConstraints: PathConstraint[]; + _updateCache: Updatable[]; + updateCacheReset: Updatable[]; + skin: Skin; + color: Color; + time: number; + flipX: boolean; + flipY: boolean; + x: number; + y: number; + constructor(data: SkeletonData); + updateCache(): void; + sortIkConstraint(constraint: IkConstraint): void; + sortPathConstraint(constraint: PathConstraint): void; + sortTransformConstraint(constraint: TransformConstraint): void; + sortPathConstraintAttachment(skin: Skin, slotIndex: number, slotBone: Bone): void; + sortPathConstraintAttachmentWith(attachment: Attachment, slotBone: Bone): void; + sortBone(bone: Bone): void; + sortReset(bones: Bone[]): void; + updateWorldTransform(): void; + setToSetupPose(): void; + setBonesToSetupPose(): void; + setSlotsToSetupPose(): void; + getRootBone(): Bone; + findBone(boneName: string): Bone; + findBoneIndex(boneName: string): number; + findSlot(slotName: string): Slot; + findSlotIndex(slotName: string): number; + setSkinByName(skinName: string): void; + setSkin(newSkin: Skin): void; + getAttachmentByName(slotName: string, attachmentName: string): Attachment; + getAttachment(slotIndex: number, attachmentName: string): Attachment; + setAttachment(slotName: string, attachmentName: string): void; + findIkConstraint(constraintName: string): IkConstraint; + findTransformConstraint(constraintName: string): TransformConstraint; + findPathConstraint(constraintName: string): PathConstraint; + getBounds(offset: Vector2, size: Vector2): void; + update(delta: number): void; + } + } + namespace spine.core { + class SkeletonBounds { + minX: number; + minY: number; + maxX: number; + maxY: number; + boundingBoxes: BoundingBoxAttachment[]; + polygons: Array>; + private polygonPool; + update(skeleton: Skeleton, updateAabb: boolean): void; + aabbCompute(): void; + aabbContainsPoint(x: number, y: number): boolean; + aabbIntersectsSegment(x1: number, y1: number, x2: number, y2: number): boolean; + aabbIntersectsSkeleton(bounds: SkeletonBounds): boolean; + containsPoint(x: number, y: number): BoundingBoxAttachment; + containsPointPolygon(polygon: ArrayLike, x: number, y: number): boolean; + intersectsSegment(x1: number, y1: number, x2: number, y2: number): BoundingBoxAttachment; + intersectsSegmentPolygon(polygon: ArrayLike, x1: number, y1: number, x2: number, y2: number): boolean; + getPolygon(boundingBox: BoundingBoxAttachment): ArrayLike; + getWidth(): number; + getHeight(): number; + } + } + namespace spine.core { + class SkeletonData { + name: string; + bones: BoneData[]; + slots: SlotData[]; + skins: Skin[]; + defaultSkin: Skin; + events: EventData[]; + animations: Animation[]; + ikConstraints: IkConstraintData[]; + transformConstraints: TransformConstraintData[]; + pathConstraints: PathConstraintData[]; + width: number; + height: number; + version: string; + hash: string; + fps: number; + imagesPath: string; + findBone(boneName: string): BoneData; + findBoneIndex(boneName: string): number; + findSlot(slotName: string): SlotData; + findSlotIndex(slotName: string): number; + findSkin(skinName: string): Skin; + findEvent(eventDataName: string): EventData; + findAnimation(animationName: string): Animation; + findIkConstraint(constraintName: string): IkConstraintData; + findTransformConstraint(constraintName: string): TransformConstraintData; + findPathConstraint(constraintName: string): PathConstraintData; + findPathConstraintIndex(pathConstraintName: string): number; + } + } + namespace spine.core { + class SkeletonJson { + attachmentLoader: AttachmentLoader; + scale: number; + private linkedMeshes; + constructor(attachmentLoader: AttachmentLoader); + readSkeletonData(json: string | any): SkeletonData; + readAttachment(map: any, skin: Skin, slotIndex: number, name: string): Attachment; + readVertices(map: any, attachment: VertexAttachment, verticesLength: number): void; + readAnimation(map: any, name: string, skeletonData: SkeletonData): void; + readCurve(map: any, timeline: CurveTimeline, frameIndex: number): void; + getValue(map: any, prop: string, defaultValue: any): any; + static blendModeFromString(str: string): number; + static positionModeFromString(str: string): PositionMode; + static spacingModeFromString(str: string): SpacingMode; + static rotateModeFromString(str: string): RotateMode; + static transformModeFromString(str: string): TransformMode; + static transformModeLegacy(inheritRotation: boolean, inheritScale: boolean): TransformMode; + } + } + namespace spine.core { + class Skin { + name: string; + attachments: Array>; + constructor(name: string); + addAttachment(slotIndex: number, name: string, attachment: Attachment): void; + getAttachment(slotIndex: number, name: string): Attachment; + attachAll(skeleton: Skeleton, oldSkin: Skin): void; + } + } + namespace spine.core { + class Slot { + currentMesh: any; + currentSprite: any; + meshes: any; + currentMeshName: string; + sprites: any; + currentSpriteName: string; + blendMode: number; + tempRegion: TextureRegion; + tempAttachment: Attachment; + data: SlotData; + bone: Bone; + color: Color; + attachment: Attachment; + private attachmentTime; + attachmentVertices: number[]; + constructor(data: SlotData, bone: Bone); + getAttachment(): Attachment; + setAttachment(attachment: Attachment): void; + setAttachmentTime(time: number): void; + getAttachmentTime(): number; + setToSetupPose(): void; + } + } + namespace spine.core { + class SlotData { + index: number; + name: string; + boneData: BoneData; + color: Color; + attachmentName: string; + blendMode: number; + constructor(index: number, name: string, boneData: BoneData); + } + } + namespace spine.core { + abstract class Texture { + protected _image: HTMLImageElement; + constructor(image: HTMLImageElement); + getImage(): HTMLImageElement; + abstract setFilters(minFilter: TextureFilter, magFilter: TextureFilter): void; + abstract setWraps(uWrap: TextureWrap, vWrap: TextureWrap): void; + abstract dispose(): void; + static filterFromString(text: string): TextureFilter; + static wrapFromString(text: string): TextureWrap; + } + enum TextureFilter { + Nearest = 9728, + Linear = 9729, + MipMap = 9987, + MipMapNearestNearest = 9984, + MipMapLinearNearest = 9985, + MipMapNearestLinear = 9986, + MipMapLinearLinear = 9987, + } + enum TextureWrap { + MirroredRepeat = 33648, + ClampToEdge = 33071, + Repeat = 10497, + } + class TextureRegion { + texture: Texture; + size: Rectangle; + readonly width: number; + readonly height: number; + readonly u: number; + readonly v: number; + readonly u2: number; + readonly v2: number; + readonly offsetX: number; + readonly offsetY: number; + readonly pixiOffsetY: number; + readonly spineOffsetY: number; + readonly originalWidth: number; + readonly originalHeight: number; + readonly x: number; + readonly y: number; + readonly rotate: boolean; + } + } + namespace spine.core { + class TextureAtlas implements Disposable { + pages: TextureAtlasPage[]; + regions: TextureAtlasRegion[]; + constructor(atlasText: string, textureLoader: (path: string, loaderFunction: (tex: BaseTexture) => any) => any, callback: (obj: TextureAtlas) => any); + addTexture(name: string, texture: Texture): TextureAtlasRegion; + addTextureHash(textures: Map, stripExtension: boolean): void; + addSpineAtlas(atlasText: string, textureLoader: (path: string, loaderFunction: (tex: BaseTexture) => any) => any, callback: (obj: TextureAtlas) => any): void; + private load(atlasText, textureLoader, callback); + findRegion(name: string): TextureAtlasRegion; + dispose(): void; + } + class TextureAtlasPage { + name: string; + minFilter: TextureFilter; + magFilter: TextureFilter; + uWrap: TextureWrap; + vWrap: TextureWrap; + baseTexture: BaseTexture; + width: number; + height: number; + setFilters(): void; + } + class TextureAtlasRegion extends TextureRegion { + page: TextureAtlasPage; + name: string; + index: number; + } + } + namespace spine.core { + class TransformConstraint implements Constraint { + data: TransformConstraintData; + bones: Bone[]; + target: Bone; + rotateMix: number; + translateMix: number; + scaleMix: number; + shearMix: number; + temp: Vector2; + constructor(data: TransformConstraintData, skeleton: Skeleton); + apply(): void; + update(): void; + getOrder(): number; + } + } + namespace spine.core { + class TransformConstraintData { + name: string; + order: number; + bones: BoneData[]; + target: BoneData; + rotateMix: number; + translateMix: number; + scaleMix: number; + shearMix: number; + offsetRotation: number; + offsetX: number; + offsetY: number; + offsetScaleX: number; + offsetScaleY: number; + offsetShearY: number; + constructor(name: string); + } + } + namespace spine.core { + interface Updatable { + update(): void; + } + } + namespace spine.core { + interface Map { + [key: string]: T; + } + class IntSet { + array: number[]; + add(value: number): boolean; + contains(value: number): boolean; + remove(value: number): void; + clear(): void; + } + interface Disposable { + dispose(): void; + } + class Color { + r: number; + g: number; + b: number; + a: number; + static WHITE: Color; + static RED: Color; + static GREEN: Color; + static BLUE: Color; + static MAGENTA: Color; + constructor(r?: number, g?: number, b?: number, a?: number); + set(r: number, g: number, b: number, a: number): this; + setFromColor(c: Color): this; + setFromString(hex: string): this; + add(r: number, g: number, b: number, a: number): this; + clamp(): this; + } + class MathUtils { + static PI: number; + static PI2: number; + static radiansToDegrees: number; + static radDeg: number; + static degreesToRadians: number; + static degRad: number; + static clamp(value: number, min: number, max: number): number; + static cosDeg(degrees: number): number; + static sinDeg(degrees: number): number; + static signum(value: number): number; + static toInt(x: number): number; + static cbrt(x: number): number; + } + class Utils { + static SUPPORTS_TYPED_ARRAYS: boolean; + static arrayCopy(source: ArrayLike, sourceStart: number, dest: ArrayLike, destStart: number, numElements: number): void; + static setArraySize(array: T[], size: number, value?: any): T[]; + static ensureArrayCapacity(array: T[], size: number, value?: any): T[]; + static newArray(size: number, defaultValue: T): T[]; + static newFloatArray(size: number): ArrayLike; + static toFloatArray(array: number[]): number[] | Float32Array; + } + class DebugUtils { + static logBones(skeleton: Skeleton): void; + } + class Pool { + private items; + private instantiator; + constructor(instantiator: () => T); + obtain(): T; + free(item: T): void; + freeAll(items: ArrayLike): void; + clear(): void; + } + class Vector2 { + x: number; + y: number; + constructor(x?: number, y?: number); + set(x: number, y: number): Vector2; + length(): number; + normalize(): this; + } + class TimeKeeper { + maxDelta: number; + framesPerSecond: number; + delta: number; + totalTime: number; + private lastTime; + private frameCount; + private frameTime; + update(): void; + } + interface ArrayLike { + length: number; + [n: number]: T; + } + } + namespace spine { + function atlasParser(): (resource: loaders.Resource, next: () => any) => any; + function imageLoaderAdapter(loader: any, namePrefix: any, baseUrl: any, imageOptions: any): (line: string, callback: (baseTexture: BaseTexture) => any) => void; + function syncImageLoaderAdapter(baseUrl: any, crossOrigin: any): (line: any, callback: any) => void; + } + namespace spine { + class SpineSprite extends Sprite { + region: core.TextureRegion; + constructor(tex: Texture); + } + class SpineMesh extends mesh.Mesh { + region: core.TextureRegion; + constructor(texture: Texture, vertices?: Float32Array, uvs?: Float32Array, indices?: Uint16Array, drawMode?: number); + } + class Spine extends Container { + static globalAutoUpdate: boolean; + tintRgb: ArrayLike; + spineData: core.SkeletonData; + skeleton: core.Skeleton; + stateData: core.AnimationStateData; + state: core.AnimationState; + slotContainers: Container[]; + constructor(spineData: core.SkeletonData); + autoUpdate: boolean; + tint: number; + update(dt: number): void; + private setSpriteRegion(attachment, sprite, region); + private setMeshRegion(attachment, mesh, region); + protected lastTime: number; + autoUpdateTransform(): void; + createSprite(slot: core.Slot, attachment: core.RegionAttachment, defName: string): SpineSprite; + createMesh(slot: core.Slot, attachment: core.MeshAttachment): SpineMesh; + hackTextureBySlotIndex(slotIndex: number, texture?: Texture, size?: Rectangle): boolean; + hackTextureBySlotName: (slotName: string, texture?: Texture, size?: Rectangle) => any; + } } } diff --git a/pixi-spine/pixi-spine-tests.ts b/pixi-spine/pixi-spine-tests.ts index 2f945ecbcc..51e4c7806f 100644 --- a/pixi-spine/pixi-spine-tests.ts +++ b/pixi-spine/pixi-spine-tests.ts @@ -1,5 +1,4 @@ -/// -/// +import * as PIXI from "pixi.js"; namespace Spine { @@ -25,13 +24,13 @@ namespace Spine { private onAssetsLoaded = (loader: PIXI.loaders.Loader, res: any): void => { - //initiate the spine animation + // initiate the spine animation this.dragon = new PIXI.spine.Spine(res.dragon.spineData); this.dragon.skeleton.setToSetupPose(); this.dragon.update(0); this.dragon.autoUpdate = false; - //create a container for the spin animation and add the animation to it + // create a container for the spin animation and add the animation to it var dragonCage: PIXI.Container = new PIXI.Container(); dragonCage.addChild(this.dragon); @@ -94,7 +93,7 @@ namespace Spine { private onAssetsLoaded = (loader: PIXI.loaders.Loader, res: any): void => { - //initiate the spine animation + // initiate the spine animation this.goblin = new PIXI.spine.Spine(res.goblins.spineData); this.goblin.skeleton.setSkinByName('goblin'); this.goblin.skeleton.setSlotsToSetupPose(); @@ -270,7 +269,7 @@ namespace Spine { private onAssetsLoaded = (loader: PIXI.loaders.Loader, res: any): void => { - //initiate the spine animation + // initiate the spine animation this.spineboy = new PIXI.spine.Spine(res.spineboy.spineData); this.spineboy.position.x = this.renderer.width / 2; this.spineboy.position.y = this.renderer.height; diff --git a/pixi-spine/tslint.json b/pixi-spine/tslint.json new file mode 100644 index 0000000000..c21d1d3fb1 --- /dev/null +++ b/pixi-spine/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "../tslint.json", + "rules": {} +} diff --git a/pixi.js/index.d.ts b/pixi.js/index.d.ts index 31bd7f87f4..bacdfd23aa 100644 --- a/pixi.js/index.d.ts +++ b/pixi.js/index.d.ts @@ -1,2899 +1,2891 @@ -// Type definitions for Pixi.js v4.3.0 +// Type definitions for Pixi.js 4.3 // Project: https://github.com/pixijs/pixi.js/ // Definitions by: Clark Stevenson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module PIXI { - - // from CONST - export var VERSION: typeof CONST.VERSION; - export var PI_2: typeof CONST.PI_2; - export var RAD_TO_DEG: typeof CONST.RAD_TO_DEG; - export var DEG_TO_RAD: typeof CONST.DEG_TO_RAD; - export var RENDERER_TYPE: typeof CONST.RENDERER_TYPE; - export var BLEND_MODES: typeof CONST.BLEND_MODES; - export var DRAW_MODES: typeof CONST.DRAW_MODES; - export var SCALE_MODES: typeof CONST.SCALE_MODES; - export var WRAP_MODES: typeof CONST.WRAP_MODES; - export var TRANSFORM_MODE: typeof CONST.TRANSFORM_MODE; - export var PRECISION: typeof CONST.PRECISION; - export var TEXT_STYLE_CHANGED: typeof CONST.TEXT_STYLE_CHANGED; - export var GC_MODES: typeof CONST.GC_MODES; - export var SHAPES: typeof CONST.SHAPES; - export var TEXT_GRADIENT: typeof CONST.TEXT_GRADIENT; - - export function autoDetectRenderer(width: number, height: number, options?: PIXI.IRendererOptions, noWebGL?: boolean): PIXI.WebGLRenderer | PIXI.CanvasRenderer; - export var loader: PIXI.loaders.Loader; - - ////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////SETTINGS/////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - export module settings { - export var TARGET_FPMS: number; - export var MIPMAP_TEXTURES: boolean; - export var RESOLUTION: number; - export var FILTER_RESOLUTION: number; - export var SPRITE_MAX_TEXTURES: number; - export var SPRITE_BATCH_SIZE: number; - export var RETINA_PREFIX: RegExp; - export var RENDER_OPTIONS: { - view: HTMLCanvasElement, - antialias: boolean, - forceFXAA: boolean, - autoResize: boolean, - transparent: boolean, - backgroundColor: number, - clearBeforeRender: boolean, - preserveDrawingBuffer: boolean, - roundPixels: boolean - }; - export var TRANSFORM_MODE: number; - export var GC_MODE: number; - export var GC_MAX_IDLE: number; - export var GC_MAX_CHECK_COUNT: number; - export var WRAP_MODE: number; - export var SCALE_MODE: number; - export var PRECISION: string; - export var UPLOADS_PER_FRAME: number; - export var CAN_UPLOAD_SAME_BUFFER: boolean; - } - - ////////////////////////////////////////////////////////////////////////////// - /////////////////////////////ACCESSIBILITY//////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - export module accessibility { - - // accessibility - export class AccessibilityManager { - - constructor(renderer: CanvasRenderer | WebGLRenderer); - - protected div: HTMLElement; - protected pool: HTMLElement[]; - protected renderId: number; - debug: boolean; - renderer: SystemRenderer; - protected children: IAccessibleTarget[]; - protected isActive: boolean; - - protected activate(): void; - protected deactivate(): void; - protected updateAccessibleObjects(displayObject: DisplayObject): void; - protected update(): void; - protected capHitArea(hitArea: IHitArea): void; - protected addChild(displayObject: DisplayObject): void; - protected _onClick(e: interaction.InteractionEvent): void; - protected _onFocus(e: interaction.InteractionEvent): void; - protected _onFocusOut(e: interaction.InteractionEvent): void; - protected _onKeyDown(e: interaction.InteractionEvent): void; - protected _onMouseMove(): void; - - destroy(): void; - - } - export interface IAccessibleTarget { - - accessible: boolean; - accessibleTitle: string; - accessibleHint: string; - tabIndex: number; - - } - - } - - ////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////CORE////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - // const - - export module CONST { - export var VERSION: string; - export var PI_2: number; - export var RAD_TO_DEG: number; - export var DEG_TO_RAD: number; - export var TARGET_FPMS: number; - export var RENDERER_TYPE: { - UNKNOWN: number; - WEBGL: number; - CANVAS: number; - }; - export var BLEND_MODES: { - NORMAL: number; - ADD: number; - MULTIPLY: number; - SCREEN: number; - OVERLAY: number; - DARKEN: number; - LIGHTEN: number; - COLOR_DODGE: number; - COLOR_BURN: number; - HARD_LIGHT: number; - SOFT_LIGHT: number; - DIFFERENCE: number; - EXCLUSION: number; - HUE: number; - SATURATION: number; - COLOR: number; - LUMINOSITY: number; - }; - export var DRAW_MODES: { - POINTS: number; - LINES: number; - LINE_LOOP: number; - LINE_STRIP: number; - TRIANGLES: number; - TRIANGLE_STRIP: number; - TRIANGLE_FAN: number; - }; - export var SCALE_MODES: { - LINEAR: number, - NEAREST: number - }; - export var GC_MODES: { - AUTO: number; - MANUAL: number; - }; - export var WRAP_MODES: { - CLAMP: number; - MIRRORED_REPEAT: number; - REPEAT: number; - }; - export var TRANSFORM_MODE: { - DEFAULT: number; - DYNAMIC: number; - STATIC: number; - }; - export var URL_FILE_EXTENSION: RegExp | string; - export var DATA_URI: RegExp | string; - export var SVG_SIZE: RegExp | string; - export var SHAPES: { - POLY: number; - RECT: number; - CIRC: number; - ELIP: number; - RREC: number; - }; - export var PRECISION: { - LOW: string; - MEDIUM: string; - HIGH: string; - }; - export var TEXT_GRADIENT: { - LINEAR_VERTICAL: number; - LINEAR_HORIZONTAL: number; - }; - export var TEXT_STYLE_CHANGED: string; - - } - - // display - - export interface IDestroyOptions { - children?: boolean; - texture?: boolean; - baseTexture?: boolean; - } - export class Bounds { - - minX: number; - minY: number; - maxX: number; - maxY: number; - rect: Rectangle; - - isEmpty(): boolean; - clear(): void; - - getRectangle(rect?: Rectangle): Rectangle; - addPoint(point: Point): void; - addQuad(vertices: number[]): Bounds; - addFrame(transform: Transform, x0: number, y0: number, x1: number, y1: number): void; - addVertices(transform: Transform, vertices: number[], beginOffset: number, endOffset: number): void; - addBounds(bounds: Bounds): void; - addBoundsMask(bounds: Bounds, mask: Bounds): void; - addBoundsArea(bounds: Bounds, area: Rectangle): void; - - } - export class Container extends DisplayObject { - - // begin extras.getChildByName - getChildByName(name: string): DisplayObject; - // end extras.getChildByName - - children: DisplayObject[]; - width: number; - height: number; - - protected onChildrenChange: (...args: any[]) => void; - addChild(child: T, ...additionalChildren: DisplayObject[]): T; - addChildAt(child: T, index: number): T; - swapChildren(child: DisplayObject, child2: DisplayObject): void; - getChildIndex(child: DisplayObject): number; - setChildIndex(child: DisplayObject, index: number): void; - getChildAt(index: number): DisplayObject; - removeChild(child: DisplayObject): DisplayObject; - removeChildAt(index: number): DisplayObject; - removeChildren(beginIndex?: number, endIndex?: number): DisplayObject[]; - updateTransform(): void; - calculateBounds(): void; - protected _calculateBounds(): void; - protected containerUpdateTransform(): void; - renderWebGL(renderer: WebGLRenderer): void; - renderAdvancedWebGL(renderer: WebGLRenderer): void; - protected _renderWebGL(renderer: WebGLRenderer): void; - protected _renderCanvas(renderer: CanvasRenderer): void; - renderCanvas(renderer: CanvasRenderer): void; - destroy(options?: IDestroyOptions | boolean): void; - - once(event: "added", fn: (displayObject: DisplayObject) => void, context?: any): utils.EventEmitter; - once(event: "removed", fn: (DisplayObject: DisplayObject) => void, context?: any): utils.EventEmitter; - once(event: string, fn: Function, context?: any): utils.EventEmitter; - on(event: "added", fn: (displayObject: DisplayObject) => void, context?: any): utils.EventEmitter; - on(event: "removed", fn: (DisplayObject: DisplayObject) => void, context?: any): utils.EventEmitter; - on(event: string, fn: Function, context?: any): utils.EventEmitter; - off(event: string, fn: Function, context?: any): utils.EventEmitter; - - } - export class DisplayObject extends utils.EventEmitter implements interaction.InteractiveTarget { - - // begin extras.cacheAsBitmap - protected _cacheAsBitmap: boolean; - protected _cacheData: boolean; - cacheAsBitmap: boolean; - protected _renderCachedWebGL(renderer: WebGLRenderer): void; - protected _initCachedDisplayObject(renderer: WebGLRenderer): void; - protected _renderCachedCanvas(renderer: CanvasRenderer): void; - protected _initCachedDisplayObjectCanvas(renderer: CanvasRenderer): void; - protected _calculateCachedBounds(): Rectangle; - protected _getCachedLocalBounds(): Rectangle; - protected _destroyCachedDisplayObject(): void; - protected _cacheAsBitmapDestroy(): void; - // end extras.cacheAsBitmap - - // begin extras.getChildByName - name: string; - // end extras.getChildByName - - // begin extras.getGlobalPosition - getGlobalPosition(point?: Point, skipUpdate?: boolean): Point; - // end extras.getGlobalPosition - - // begin accessible target - accessible: boolean; - accessibleTitle: string; - accessibleHint: string; - tabIndex: number; - // end accessible target - - // begin interactive target - interactive: boolean; - buttonMode: boolean; - hitArea: IHitArea; - interactiveChildren: boolean; - defaultCursor: string; - _isRightDown: boolean; - _isLeftDown: boolean; - // end interactive target - - transform: TransformBase; - alpha: number; - visible: boolean; - renderable: boolean; - parent: Container; - worldAlpha: number; - filterArea: Rectangle; - protected _filters: Filter[]; - protected _enabledFilters: Filter[]; - protected _bounds: Bounds; - protected _boundsID: number; - protected _lastBoundsID: number; - protected _boundsRect: Rectangle; - protected _localBoundsRect: Rectangle; - protected _mask: Rectangle; - x: number; - y: number; - worldTransform: Matrix; - localTransform: Matrix; - position: Point; - scale: Point; - pivot: Point; - skew: Point; - rotation: number; - worldVisible: boolean; - mask: PIXI.Graphics | PIXI.Sprite; - filters: Filter[]; - - updateTransform(): void; - protected displayObjectUpdateTransform(): void; - protected _recursivePostUpdateTransform(): void; - getBounds(skipUpdate?: boolean, rect?: Rectangle): Rectangle; - getLocalBounds(rect?: Rectangle): Rectangle; - toGlobal(position: Point, point?: Point, skipUpdate?: boolean): Point; - toLocal(position: Point, from?: DisplayObject, point?: Point, skipUpdate?: boolean): Point; - protected renderWebGL(renderer: WebGLRenderer): void; - renderCanvas(renderer: CanvasRenderer): void; - setParent(container: Container): Container; - setTransform(x?: number, y?: number, scaleX?: number, scaleY?: number, rotation?: number, skewX?: number, skewY?: number, pivotX?: number, pivotY?: number): DisplayObject; - destroy(): void; - - on(event: string, fn: Function, context?: any): utils.EventEmitter; - once(event: string, fn: Function, context?: any): utils.EventEmitter; - off(event: string, fn: Function, context?: any): utils.EventEmitter; - - /* - on(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - on(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - - once(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - once(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; - */ - - } - - export class TransformBase { - - static IDENTITY: TransformBase; - - worldTransform: Matrix; - localTransform: Matrix; - protected _worldID: number; - updateLocalTransform(): void; - updateTransform(parentTransform: TransformBase): void; - updateWorldTransform(parentTransform: TransformBase): void; - - } - export class TransformStatic extends TransformBase { - - position: ObservablePoint; - scale: ObservablePoint; - pivot: ObservablePoint; - skew: ObservablePoint; - - protected _rotation: number; - protected _sr: number; - protected _cr: number; - protected _cy: number; - protected _sy: number; - protected _nsx: number; - protected _cx: number; - protected _currentLocalID: number; - - protected onChange(): void; - updateSkew(): void; - updateLocalTransform(): void; - updateTransform(parentTransform: TransformBase): void; - setFromMatrix(matrix: Matrix): void; - - rotation: number; - - } - export class Transform extends TransformBase { - - constructor(); - - position: Point; - scale: Point; - skew: ObservablePoint; - pivot: Point; - - protected _rotation: number; - protected _sr: number; - protected _cr: number; - protected _cy: number; - protected _sy: number; - protected _nsx: number; - protected _cx: number; - - updateSkew(): void; - setFromMatrix(matrix: Matrix): void; - - rotation: number; - - } - - // graphics - - export class GraphicsData { - - constructor(lineWidth: number, lineColor: number, lineAlpha: number, fillColor: number, fillAlpha: number, fill: boolean, shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon); - - lineWidth: number; - lineColor: number; - lineAlpha: number; - protected _lineTint: number; - fillColor: number; - fillAlpha: number; - protected _fillTint: number; - fill: boolean; - protected holes: IShape[]; - shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon; - type: number; - clone(): GraphicsData; - addHole(shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon): void; - destroy(options?: IDestroyOptions | boolean): void; - - } - export class Graphics extends Container { - - fillAlpha: number; - lineWidth: number; - lineColor: number; - protected graphicsData: GraphicsData[]; - tint: number; - protected _prevTint: number; - blendMode: number; - currentPath: GraphicsData; - protected _webGL: any; - isMask: boolean; - boundsPadding: number; - protected _localBounds: Bounds; - dirty: boolean; - fastRectDirty: number; - clearDirty: number; - boundsDirty: number; - protected cachedSpriteDirty: boolean; - protected _spriteRect: Rectangle; - protected _fastRect: boolean; - - static _SPRITE_TEXTURE: Texture; - - clone(): Graphics; - lineStyle(lineWidth?: number, color?: number, alpha?: number): Graphics; - moveTo(x: number, y: number): Graphics; - lineTo(x: number, y: number): Graphics; - quadraticCurveTo(cpX: number, cpY: number, toX: number, toY: number): Graphics; - bezierCurveTo(cpX: number, cpY: number, cpX2: number, cpY2: number, toX: number, toY: number): Graphics; - arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): Graphics; - arc(cx: number, cy: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): Graphics; - beginFill(color: number, alpha?: number): Graphics; - endFill(): Graphics; - drawRect(x: number, y: number, width: number, height: number): Graphics; - drawRoundedRect(x: number, y: number, width: number, height: number, radius: number): Graphics; - drawCircle(x: number, y: number, radius: number): Graphics; - drawEllipse(x: number, y: number, width: number, height: number): Graphics; - drawPolygon(path: number[] | Point[]): Graphics; - clear(): Graphics; - isFastRect(): boolean; - protected _renderCanvas(renderer: CanvasRenderer): void; - protected _calculateBounds(): Rectangle; - protected _renderSpriteRect(renderer: PIXI.SystemRenderer): void; - containsPoint(point: Point): boolean; - updateLocalBounds(): void; - drawShape(shape: IShape | Circle | Rectangle | Ellipse | Polygon | RoundedRectangle): GraphicsData; - generateCanvasTexture(scaleMode?: number, resolution?: number): Texture; - protected closePath(): Graphics; - protected addHole(): Graphics; - destroy(options?: IDestroyOptions | boolean): void; - - } - export class CanvasGraphicsRenderer { - - constructor(renderer: SystemRenderer); - render(graphics: Graphics): void; - protected updateGraphicsTint(graphics: Graphics): void; - protected renderPolygon(points: Point[], close: boolean, context: CanvasRenderingContext2D): void; - destroy(): void; - - } - export class GraphicsRenderer extends ObjectRenderer { - - constructor(renderer: PIXI.CanvasRenderer); - - protected graphicsDataPool: GraphicsData[]; - protected primitiveShader: PrimitiveShader; - gl: WebGLRenderingContext; - - CONTEXT_UID: number; - - destroy(): void; - render(graphics: Graphics): void; - protected updateGraphics(graphics: PIXI.Graphics): void; - getWebGLData(webGL: WebGLRenderingContext, type: number): WebGLGraphicsData; - - } - export class WebGLGraphicsData { - - constructor(gl: WebGLRenderingContext, shader: glCore.GLShader, attribsState: glCore.IAttribState); - - gl: WebGLRenderingContext; - color: number[]; - points: Point[]; - indices: number[]; - buffer: WebGLBuffer; - indexBuffer: WebGLBuffer; - dirty: boolean; - glPoints: number[]; - glIndices: number[]; - shader: glCore.GLShader; - vao: glCore.VertexArrayObject; - - reset(): void; - upload(): void; - destroy(): void; - - } - export class PrimitiveShader extends glCore.GLShader { } - - // math - - export module GroupD8 { - - export var E: number; - export var SE: number; - export var S: number; - export var SW: number; - export var W: number; - export var NW: number; - export var N: number; - export var NE: number; - export var MIRROR_HORIZONTAL: number; - export var MIRROR_VERTICAL: number; - - export function uX(ind: number): number; - export function uY(ind: number): number; - export function vX(ind: number): number; - export function vY(ind: number): number; - export function inv(rotation: number): number; - export function add(rotationSecond: number, rotationFirst: number): number; - export function sub(rotationSecond: number, rotationFirst: number): number; - export function rotate180(rotation: number): number; - export function isSwapWidthHeight(rotation: number): boolean; - export function byDirection(dx: number, dy: number): number; - export function matrixAppendRotationInv(matrix: Matrix, rotation: number, tx: number, ty: number): void; - - } - export class Matrix { - - a: number; - b: number; - c: number; - d: number; - tx: number; - ty: number; - - fromArray(array: number[]): void; - set(a: number, b: number, c: number, d: number, tx: number, ty: number): Matrix; - toArray(transpose?: boolean, out?: number[]): number[]; - apply(pos: Point, newPos?: Point): Point; - applyInverse(pos: Point, newPos?: Point): Point; - translate(x: number, y: number): Matrix; - scale(x: number, y: number): Matrix; - rotate(angle: number): Matrix; - append(matrix: Matrix): Matrix; - setTransform(x: number, y: number, pivotX: number, pivotY: number, scaleX: number, scaleY: number, rotation: number, skewX: number, skewY: number): PIXI.Matrix; - prepend(matrix: Matrix): Matrix; - invert(): Matrix; - identity(): Matrix; - decompose(transform: TransformBase): TransformBase; - clone(): Matrix; - copy(matrix: Matrix): Matrix; - - static IDENTITY: Matrix; - static TEMP_MATRIX: Matrix; - - } - export class ObservablePoint { - - constructor(cb: Function, scope?: any, x?: number, y?: number); - - x: number; - y: number; - cb: () => void; - scope: any; - - set(x?: number, y?: number): void; - copy(point: Point | ObservablePoint): void; - - } - export class Point { - - constructor(x?: number, y?: number); - - x: number; - y: number; - - clone(): Point; - copy(p: Point): void; - equals(p: Point): boolean; - set(x?: number, y?: number): void; - - } - - export interface IShape { - } - export interface IHitArea extends IShape { - - contains(x: number, y: number): boolean; - - } - export class Circle { - - constructor(x?: number, y?: number, radius?: number); - - x: number; - y: number; - radius: number; - type: number; - - clone(): Circle; - contains(x: number, y: number): boolean; - getBounds(): Rectangle; - - } - export class Ellipse { - - constructor(x?: number, y?: number, width?: number, height?: number); - - x: number; - y: number; - width: number; - height: number; - type: number; - - clone(): Ellipse; - contains(x: number, y: number): boolean; - getBounds(): Rectangle; - - } - export class Polygon { - - constructor(points: Point[] | number[]); - constructor(...points: Point[]); - constructor(...points: number[]); - - closed: boolean; - points: number[]; - type: number; - - clone(): Polygon; - contains(x: number, y: number): boolean; - close(): void; - - } - export class Rectangle { - - constructor(x?: number, y?: number, width?: number, height?: number); - - x: number; - y: number; - width: number; - height: number; - type: number; - left: number; - right: number; - top: number; - bottom: number; - - static EMPTY: Rectangle; - - clone(): Rectangle; - copy(rectangle: Rectangle): Rectangle; - contains(x: number, y: number): boolean; - pad(paddingX: number, paddingY: number): void; - fit(rectangle: Rectangle): void; - enlarge(rect: Rectangle): void; - - } - export class RoundedRectangle { - - constructor(x?: number, y?: number, width?: number, height?: number, radius?: number); - - x: number; - y: number; - width: number; - height: number; - radius: number; - type: number; - - clone(): RoundedRectangle; - contains(x: number, y: number): boolean; - - } - - // renderers - - export interface IRendererOptions { - - view?: HTMLCanvasElement; - transparent?: boolean; - autoResize?: boolean; - antialias?: boolean; - resolution?: number; - clearBeforeRender?: boolean; - backgroundColor?: number; - roundPixels?: boolean; - context?: WebGLRenderingContext; - - } - export class SystemRenderer extends utils.EventEmitter { - - constructor(system: string, width?: number, height?: number, options?: IRendererOptions); - - type: number; - width: number; - height: number; - view: HTMLCanvasElement; - resolution: number; - transparent: boolean; - autoResize: boolean; - blendModes: any; // todo? - preserveDrawingBuffer: boolean; - clearBeforeRender: boolean; - roundPixels: boolean; - protected _backgroundColor: number; - protected _backgroundColorRgba: number[]; - protected _backgroundColorString: string; - protected _tempDisplayObjectParent: Container; - protected _lastObjectRendered: DisplayObject; - backgroundColor: number; - - resize(width: number, height: number): void; - generateTexture(displayObject: DisplayObject, scaleMode?: number, resolution?: number): RenderTexture; - render(...args: any[]): void; - destroy(removeView?: boolean): void; - - } - export class CanvasRenderer extends SystemRenderer { - - // plugintarget mixin start - static __plugins: any[]; - static registerPlugin(pluginName: string, ctor: Function): void; - plugins: any; - initPlugins(): void; - destroyPlugins(): void; - // plugintarget mixin end - - constructor(width?: number, height?: number, options?: IRendererOptions); - - rootContext: CanvasRenderingContext2D; - rootResolution: number; - refresh: boolean; - maskManager: CanvasMaskManager; - smoothProperty: string; - extract: extract.CanvasExtract; - - context: CanvasRenderingContext2D; - - render(displayObject: PIXI.DisplayObject, renderTexture?: PIXI.RenderTexture, clear?: boolean, transform?: PIXI.Transform, skipUpdateTransform?: boolean): void - setBlendMode(blendMode: number): void; - destroy(removeView?: boolean): void; - resize(w: number, h: number): void; - - on(event: "prerender", fn: () => void, context?: any): utils.EventEmitter; - on(event: "postrender", fn: () => void, context?: any): utils.EventEmitter; - on(event: string, fn: Function, context?: any): utils.EventEmitter; - once(event: "prerender", fn: () => void, context?: any): utils.EventEmitter; - once(event: "postrender", fn: () => void, context?: any): utils.EventEmitter; - once(event: string, fn: Function, context?: any): utils.EventEmitter; - off(event: string, fn: Function, context?: any): utils.EventEmitter; - - } - export class CanvasMaskManager { - - constructor(renderer: CanvasRenderer); - - pushMask(maskData: any): void; - protected renderGraphicsShape(graphics: Graphics): void; - popMask(renderer: WebGLRenderer | CanvasRenderer): void; - destroy(): void; - - } - export class CanvasRenderTarget { - - constructor(width: number, height: number, resolution: number); - - canvas: HTMLCanvasElement; - context: CanvasRenderingContext2D; - resolution: number; - - width: number; - height: number; - - clear(): void; - resize(width: number, height: number): void; - destroy(): void; - - } - - export interface IWebGLRendererOptions { - - view?: HTMLCanvasElement; - transparent?: boolean; - autoResize?: boolean; - antialias?: boolean; - forceFXAA?: boolean; - resolution?: number; - clearBeforeRender?: boolean; - preserveDrawingBuffer?: boolean; - roundPixels?: boolean; - - } - export class WebGLRenderer extends SystemRenderer { - - // plugintarget mixin start - static __plugins: any[]; - static registerPlugin(pluginName: string, ctor: Function): void; - plugins: any; - initPlugins(): void; - destroyPlugins(): void; - // plugintarget mixin end - - constructor(width?: number, height?: number, options?: IWebGLRendererOptions); - - protected _contextOptions: { - alpha: boolean; - antiAlias: boolean; - premultipliedAlpha: boolean; - stencil: boolean; - preseveDrawingBuffer: boolean; - }; - protected _backgroundColorRgba: number[]; - maskManager: MaskManager; - stencilManager: StencilManager; - emptyRenderer: ObjectRenderer; - currentRenderer: ObjectRenderer; - gl: WebGLRenderingContext; - CONTEXT_UID: number; - state: WebGLState; - renderingToScreen: boolean; - boundTextures: Texture[]; - filterManager: FilterManager; - textureManager: TextureManager; - extract: extract.WebGLExtract; - protected drawModes: any; - protected _activeShader: Shader; - _activeRenderTarget: RenderTarget; - protected _initContext(): void; - - render(displayObject: PIXI.DisplayObject, renderTexture?: PIXI.RenderTexture, clear?: boolean, transform?: PIXI.Transform, skipUpdateTransform?: boolean): void - setObjectRenderer(objectRenderer: ObjectRenderer): void; - flush(): void; - resize(width: number, height: number): void; - setBlendMode(blendMode: number): void; - clear(clearColor?: number): void; - setTransform(matrix: Matrix): void; - bindRenderTexture(renderTexture: RenderTexture, transform: Transform): WebGLRenderer; - bindRenderTarget(renderTarget: RenderTarget): WebGLRenderer; - bindShader(shader: Shader): WebGLRenderer; - bindTexture(texture: Texture | BaseTexture, location?: number, forceLocation?: boolean): number; - unbindTexture(texture: Texture | BaseTexture): WebGLRenderer; - createVao(): glCore.VertexArrayObject; - bindVao(vao: glCore.VertexArrayObject): WebGLRenderer; - reset(): WebGLRenderer; - handleContextLost: (event: WebGLContextEvent) => void; - handleContextRestored: () => void; - destroy(removeView?: boolean): void; - - on(event: "context", fn: (gl: WebGLRenderingContext) => void, context?: any): utils.EventEmitter; - on(event: "prerender", fn: () => void, context?: any): utils.EventEmitter; - on(event: "postrender", fn: () => void, context?: any): utils.EventEmitter; - on(event: string, fn: Function, context?: any): utils.EventEmitter; - once(event: "context", fn: (gl: WebGLRenderingContext) => void, context?: any): utils.EventEmitter; - once(event: "prerender", fn: () => void, context?: any): utils.EventEmitter; - once(event: "postrender", fn: () => void, context?: any): utils.EventEmitter; - once(event: string, fn: Function, context?: any): utils.EventEmitter; - off(event: string, fn: Function, context?: any): utils.EventEmitter; - - } - export class WebGLState { - - constructor(gl: WebGLRenderingContext); - - activeState: number[]; - defaultState: number[]; - stackIndex: number; - stack: number[]; - gl: WebGLRenderingContext; - maxAttribs: number; - attribState: glCore.IAttribState; - nativeVaoExtension: any; - - push(): void; - pop(): void; - setState(state: number[]): void; - setBlend(value: number): void; - setBlendMode(value: number): void; - setDepthTest(value: number): void; - setCullFace(value: number): void; - setFrontFace(value: number): void; - resetAttributes(): void; - resetToDefault(): void; - - } - export class TextureManager { - - constructor(renderer: WebGLRenderer); - - renderer: WebGLRenderer; - gl: WebGLRenderingContext; - protected _managedTextures: WebGLTexture[]; - - bindTexture(): void; - getTexture(): WebGLTexture; - updateTexture(texture: BaseTexture | Texture): WebGLTexture; - destroyTexture(texture: BaseTexture, _skipRemove?: boolean): void; - removeAll(): void; - destroy(): void; - - } - export class TextureGarbageCollector { - - constructor(renderer: WebGLRenderer); - - renderer: WebGLRenderer; - count: number; - checkCount: number; - maxIdle: number; - checkCountMax: number; - mode: number; - - update(): void; - run(): void; - unload(): void; - - } - export abstract class ObjectRenderer extends WebGLManager { - - constructor(renderer: WebGLRenderer); - - start(): void; - stop(): void; - flush(): void; - - render(...args: any[]): void; - - } - export class Quad { - - constructor(gl: WebGLRenderingContext); - - gl: WebGLRenderingContext; - vertices: number[]; - uvs: number[]; - interleaved: number[]; - indices: number[]; - vertexBuffer: WebGLBuffer; - vao: glCore.VertexArrayObject; - initVao(shader: glCore.GLShader): void; - map(targetTextureFrame: Rectangle, destinationFrame: Rectangle): Quad; - upload(): Quad; - destroy(): void; - - } - export class RenderTarget { - - constructor(gl: WebGLRenderingContext, width: number, height: number, scaleMode: number, resolution: number, root?: boolean); - - gl: WebGLRenderingContext; - frameBuffer: glCore.GLFramebuffer; - texture: Texture; - clearColor: number[]; - size: Rectangle; - resolution: number; - projectionMatrix: Matrix; - transform: Matrix; - frame: Rectangle; - defaultFrame: Rectangle; - destinationFrame: Rectangle; - sourceFrame: Rectangle; - stencilBuffer: glCore.GLFramebuffer; - stencilMaskStack: Graphics[]; - filterData: { - index: number, - stack: { - renderTarget: RenderTarget, - filter: any[]; - bounds: Rectangle - }[] - }; - scaleMode: number; - root: boolean; - - clear(clearColor?: number[]): void; - attachStencilBuffer(): void; - setFrame(destinationFrame: Rectangle, sourceFrame: Rectangle): void; - activate(): void; - calculateProjection(destinationFrame: Rectangle, sourceFrame: Rectangle): void; - resize(width: number, height: number): void; - destroy(): void; - - } - - export class BlendModeManager extends WebGLManager { - - constructor(renderer: WebGLRenderer); - - currentBlendMode: number; - - setBlendMode(blendMode: number): boolean; - - } - export class FilterManager extends WebGLManager { - - constructor(renderer: WebGLRenderer); - - gl: WebGLRenderingContext; - quad: Quad; - stack: { - renderTarget: RenderTarget; - sourceFrame: Rectangle; - destinationFrame: Rectangle; - filters: Filter[]; - target: any; - resolution: number; - }[]; - stackIndex: number; - shaderCache: any; - filterData: any; - - pushFilter(target: RenderTarget, filters: Filter[]): void; - popFilter(): void; - applyFilter(shader: glCore.GLShader | Filter, inputTarget: RenderTarget, outputTarget: RenderTarget, clear?: boolean): void; - syncUniforms(shader: glCore.GLShader, filter: Filter): void; - getRenderTarget(clear?: boolean, resolution?: number): RenderTarget; - returnRenderTarget(renderTarget: RenderTarget): RenderTarget; - calculateScreenSpaceMatrix(outputMatrix: Matrix): Matrix; - calculateNormalisedScreenSpaceMatrix(outputMatrix: Matrix): Matrix; - calculateSpriteMatrix(outputMatrix: Matrix, sprite: Sprite): Matrix; - destroy(): void; - emptyPool(): void; - getPotRenderTarget(gl: WebGLRenderingContext, minWidth: number, minHeight: number, resolution: number): RenderTarget; - freePotRenderTarget(renderTarget: RenderTarget): void; - - } - export class StencilMaskStack { - - stencilStack: any[]; - reverse: boolean; - count: number; - - } - export class MaskManager extends WebGLManager { - - scissor: boolean; - scissorData: any; - scissorRenderTarget: RenderTarget; - enableScissor: boolean; - alphaMaskPool: number[]; - alphaMaskIndex: number; - pushMask(target: RenderTarget, maskData: Sprite | Graphics): void; - popMask(target: RenderTarget, maskData: Sprite | Graphics): void; - pushSpriteMask(target: RenderTarget, maskData: Sprite | Graphics): void; - popSpriteMask(): void; - pushStencilMask(maskData: Sprite | Graphics): void; - popStencilMask(): void; - pushScissorMask(target: RenderTarget, maskData: Sprite | Graphics): void; - popScissorMask(): void; - - } - export class StencilManager extends WebGLManager { - - constructor(renderer: WebGLRenderer); - - stencilMaskStack: Graphics[]; - - setMaskStack(stencilMasStack: Graphics[]): void; - pushStencil(graphics: Graphics): void; - popStencil(): void; - destroy(): void; - - } - export class WebGLManager { - - constructor(renderer: WebGLRenderer); - - renderer: WebGLRenderer; - onContextChange(): void; - destroy(): void; - - } - export interface IUniformData { - - type: string; - value: any; - - // name is set by pixi if uniforms were automatically extracted from shader code, but not used anywhere - name?: string; - - } - export class Filter { - - // param uniforms should be an object matching type {[name: string]: IUniformData}; - // left untyped as there's no way to define the type without requiring an index signature or making this class generic - constructor(vertexSrc?: string, fragmentSrc?: string, uniforms?: any); - - vertextSrc: string; - fragmentSrc: string; - protected uniformData: { [name: string]: IUniformData }; - uniforms: { [name: string]: any }; - glShaders: any; - glShaderKey: string; - padding: number; - resolution: number; - blendMode: number; - enabled: boolean; - apply(filterManager: FilterManager, input: RenderTarget, output: RenderTarget, clear?: boolean): void; - - static defaultVertexSrc: string; - static defaultFragmentSrc: string; - - } - export class SpriteMaskFilter extends Filter { - - constructor(sprite: Sprite); - - maskSprite: Sprite; - maskMatrix: Matrix; - apply(filterManager: FilterManager, input: RenderTarget, output: RenderTarget): void; - - } - - // sprites - - export class Sprite extends Container { - - constructor(texture?: Texture); - - protected _anchor: ObservablePoint; - anchor: ObservablePoint; - protected _texture: Texture; - protected _width: number; - protected _height: number; - tint: number; - protected _tint: number; - protected _tintRGB: number; - blendMode: number; - pluginName: string; - protected cachedTint: number; - texture: Texture; - protected textureDirty: boolean; - protected _textureID: number; - protected _transformID: number; - protected vertexTrimmedData: Float32Array; - vertexData: Float32Array; - width: number; - height: number; - - protected _onTextureUpdate(): void; - calculateVertices(): void; - protected _calculateBounds(): void; - protected calculateTrimmedVertices(): void; - protected onAnchorUpdate(): void; - protected _renderWebGL(renderer: WebGLRenderer): void; - protected _renderCanvas(renderer: CanvasRenderer): void; - getLocalBounds(): Rectangle; - containsPoint(point: Point): boolean; - destroy(options?: IDestroyOptions | boolean): void; - - static from(source: number | string | BaseTexture | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement): Sprite; - static fromFrame(frameId: string): Sprite; - static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; - - } - export class BatchBuffer { - - vertices: ArrayBuffer; - float32View: number[]; - uint32View: number[]; - - destroy(): void; - - } - export class SpriteRenderer extends ObjectRenderer { - - constructor(renderer: PIXI.WebGLRenderer); - - vertSize: number; - vertByteSize: number; - size: number; - buffers: BatchBuffer[]; - indices: number[]; - shaders: Shader[]; - currentIndex: number; - tick: number; - groups: any[]; - sprites: Sprite[]; - vertexBuffers: number[]; - vaos: glCore.VertexArrayObject[]; - vaoMax: number; - vertexCount: number; - - protected onContextChanged: () => void; - protected onPrerender: () => void; - render(sprite: Sprite): void; - flush(): void; - start(): void; - stop(): void; - destroy(): void; - - } - export class CanvasSpriteRenderer extends ObjectRenderer { - - constructor(renderer: WebGLRenderer); - - render(sprite: Sprite): void; - destroy(): void; - - } - export module CanvasTinter { - - export function getTintedTexture(sprite: Sprite, color: number): HTMLCanvasElement; - export function tintWithMultiply(texture: Texture, color: number, canvas: HTMLCanvasElement): void; - export function tintWithOverlay(texture: Texture, color: number, canvas: HTMLCanvasElement): void; - export function tintWithPerPixel(texture: Texture, color: number, canvas: HTMLCanvasElement): void; - export function roundColor(color: number): number; - - export var cacheStepsPerColorChannel: number; - export var convertTintToImage: boolean; - export var canUseMultiply: boolean; - export var tintMethod: Function; - - } - - // text - export interface TextStyleOptions { - align?: string; - breakWords?: boolean; - dropShadow?: boolean; - dropShadowAngle?: number; - dropShadowBlur?: number; - dropShadowColor?: string | number; - dropShadowDistance?: number; - fill?: string | string[] | number | number[] | CanvasGradient | CanvasPattern; - fillGradientType?: number; - fontFamily?: string; - fontSize?: number | string; - fontStyle?: string; - fontVariant?: string; - fontWeight?: string; - letterSpacing?: number; - lineHeight?: number; - lineJoin?: string; - miterLimit?: number; - padding?: number; - stroke?: string | number; - strokeThickness?: number; - styleID?: number; - textBaseline?: string; - wordWrap?: boolean; - wordWrapWidth?: number; - } - - export class TextStyle implements TextStyleOptions { - align: string; - breakWords: boolean; - dropShadow: boolean; - dropShadowAngle: number; - dropShadowBlur: number; - dropShadowColor: string | number; - dropShadowDistance: number; - fill: string | string[] | number | number[] | CanvasGradient | CanvasPattern; - fillGradientType: number; - fontFamily: string; - fontSize: number | string; - fontStyle: string; - fontVariant: string; - fontWeight: string; - letterSpacing: number; - lineHeight: number; - lineJoin: string; - miterLimit: number; - padding: number; - stroke: string | number; - strokeThickness: number; - styleID: number; - textBaseline: string; - wordWrap: boolean; - wordWrapWidth: number; - constructor(style?: TextStyleOptions); - public clone(): TextStyle; - public reset(): void; - } - - export class Text extends Sprite { - - static getFontStyle(style: TextStyleOptions): string; - static calculateFontProperties(style: string): any; - - constructor(text?: string, style?: TextStyleOptions); - - canvas: HTMLCanvasElement; - context: CanvasRenderingContext2D; - resolution: number; - protected _text: string; - protected _style: TextStyle; - protected _styleListener: Function; - protected _font: string; - protected localStyleID: number; - - static fontPropertiesCache: any; - static fontPropertiesCanvas: HTMLCanvasElement; - static fontPropertiesContext: CanvasRenderingContext2D; - - width: number; - height: number; - style: TextStyle; - text: string; - - protected updateText(respectDirty?: boolean): void; - protected drawLetterSpacing(text: string, x: number, y: number, isStroke?: boolean): void; - protected updateTexture(): void; - renderWebGL(renderer: WebGLRenderer): void; - protected _renderCanvas(renderer: CanvasRenderer): void; - protected wordWrap(text: string): string; - protected _calculateBounds(): void; - protected _onStyleChange: () => void; - protected _generateFillStyle(style: TextStyle, lines: string[]): string | number | CanvasGradient; - destroy(options?: IDestroyOptions | boolean): void; - dirty: boolean; - - } - - // textures - - export class BaseRenderTexture extends BaseTexture { - - constructor(width?: number, height?: number, scaleMode?: number, resolution?: number); - - height: number; - width: number; - realHeight: number; - realWidth: number; - resolution: number; - scaleMode: number; - hasLoaded: boolean; - protected _glRenderTargets: { [n: number]: WebGLTexture; }; - protected _canvasRenderTarget: { [n: number]: WebGLTexture; }; - valid: boolean; - - resize(width: number, height: number): void; - destroy(): void; - - once(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): utils.EventEmitter; - once(event: string, fn: Function, context?: any): utils.EventEmitter; - on(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): utils.EventEmitter; - on(event: string, fn: Function, context?: any): utils.EventEmitter; - off(event: string, fn: Function, context?: any): utils.EventEmitter; - - } - export class BaseTexture extends utils.EventEmitter { - - constructor(source?: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, scaleMode?: number, resolution?: number); - - protected uuid: number; - protected touched: number; - resolution: number; - width: number; - height: number; - realWidth: number; - realHeight: number; - scaleMode: number; - hasLoaded: boolean; - isLoading: boolean; - wrapMode: number; - source: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement; - origSource: HTMLImageElement; - imageType: string; - sourceScale: number; - premultipliedAlpha: boolean; - imageUrl: string; - protected isPowerOfTwo: boolean; - mipmap: boolean; - wrap: boolean; - protected _glTextures: any; - protected _enabled: number; - protected _id: number; - - update(): void; - protected _updateImageType(): void; - protected _loadSvgSource(): void; - protected _loadSvgSourceUsingDataUri(dataUri: string): void; - protected _loadSvgSourceUsingXhr(): void; - protected _loadSvgSourceUsingString(svgString: string): void; - protected loadSource(source: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement): void; - protected _sourceLoaded(): void; - destroy(): void; - dispose(): void; - updateSourceImage(newSrc: string): void; - - static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: number, sourceScale?: number): BaseTexture; - static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): BaseTexture; - - on(event: "update", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; - on(event: "loaded", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; - on(event: "error", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; - on(event: "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; - on(event: string, fn: Function, context?: any): utils.EventEmitter; - once(event: "update", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; - once(event: "loaded", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; - once(event: "error", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; - once(event: "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; - once(event: string, fn: Function, context?: any): utils.EventEmitter; - off(event: string, fn: Function, context?: any): utils.EventEmitter; - - } - export class RenderTexture extends Texture { - - constructor(baseRenderTexture: BaseRenderTexture, frame?: Rectangle); - - protected legacyRenderer: any; - valid: boolean; - - resize(width: number, height: number, doNotResizeBaseTexture?: boolean): void; - - static create(width?: number, height?: number, scaleMode?: number, resolution?: number): RenderTexture; - - } - export class Texture extends utils.EventEmitter { - - constructor(baseTexture: BaseTexture, frame?: Rectangle, orig?: Rectangle, trim?: Rectangle, rotate?: number); - - noFrame: boolean; - baseTexture: BaseTexture; - protected _frame: Rectangle; - trim: Rectangle; - valid: boolean; - requiresUpdate: boolean; - protected _uvs: TextureUvs; - orig: Rectangle; - protected _updateID: number; - transform: any; - - update(): void; - protected onBaseTextureLoaded(baseTexture: BaseTexture): void; - protected onBaseTextureUpdated(baseTexture: BaseTexture): void; - destroy(destroyBase?: boolean): void; - clone(): Texture; - protected _updateUvs(): void; - - static fromImage(imageUrl: string, crossOrigin?: boolean, scaleMode?: number, sourceScale?: number): Texture; - static fromFrame(frameId: string): Texture; - static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): Texture; - static fromVideo(video: HTMLVideoElement | string, scaleMode?: number): Texture; - static fromVideoUrl(videoUrl: string, scaleMode?: number): Texture; - static from(source: number | string | BaseTexture | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement): Texture; - static addTextureToCache(texture: Texture, id: string): void; - static removeTextureFromCache(id: string): Texture; - - frame: Rectangle; - protected _rotate: boolean; - rotate: number; - width: number; - height: number; - - static EMPTY: Texture; - - on(event: "update", fn: (texture: Texture) => void, context?: any): utils.EventEmitter; - on(event: string, fn: Function, context?: any): utils.EventEmitter; - once(event: "update", fn: (texture: Texture) => void, context?: any): utils.EventEmitter; - once(event: string, fn: Function, context?: any): utils.EventEmitter; - off(event: string, fn: Function, context?: any): utils.EventEmitter; - - } - export class TextureUvs { - - x0: number; - y0: number; - x1: number; - y1: number; - x2: number; - y2: number; - x3: number; - y3: number; - - uvsUint32: Uint32Array; - - protected set(frame: Rectangle, baseFrame: Rectangle, rotate: number): void; - - } - export class VideoBaseTexture extends BaseTexture { - - constructor(source: HTMLVideoElement, scaleMode?: number); - - autoUpdate: boolean; - autoPlay: boolean; - protected _isAutoUpdating: boolean; - - update(): void; - protected _onCanPlay(): void; - protected _onPlayStart(): void; - protected _onPlayStop(): void; - destroy(): void; - protected _isSourcePlaying(): boolean; - protected _isSourceReady(): boolean; - - static fromVideo(video: HTMLVideoElement, scaleMode?: number): VideoBaseTexture; - static fromUrl(videoSrc: string | any | string[] | any[]): VideoBaseTexture; - static fromUrls(videoSrc: string | any | string[] | any[]): VideoBaseTexture; - - source: HTMLVideoElement; - protected loadSource(source: HTMLVideoElement): void; - } - - // ticker - - module ticker { - - export var shared: Ticker; - - export class Ticker { - - protected _tick(time: number): void; - protected _emitter: utils.EventEmitter; - protected _requestId: number; - protected _maxElapsedMS: number; - - protected _requestIfNeeded(): void; - protected _cancelIfNeeded(): void; - protected _startIfPossible(): void; - - autoStart: boolean; - deltaTime: number; - elapsedMS: number; - lastTime: number; - speed: number; - started: boolean; - - FPS: number; - minFPS: number; - - add(fn: (deltaTime: number) => void, context?: any): Ticker; - addOnce(fn: (deltaTime: number) => void, context?: any): Ticker; - remove(fn: (deltaTime: number) => void, context?: any): Ticker; - start(): void; - stop(): void; - update(): void; - - } - - } - - // shader - - export class Shader extends glCore.GLShader { } - - ////////////////////////////////////////////////////////////////////////////// - ////////////////////////////EXTRACT/////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - export module extract { - - export class CanvasExtract { - - protected renderer: CanvasRenderer; - - constructor(renderer: CanvasRenderer); - - image(target?: DisplayObject | RenderTexture): HTMLImageElement; - base64(target?: DisplayObject | RenderTexture): string; - canvas(target?: DisplayObject | RenderTexture): HTMLCanvasElement; - pixels(renderTexture?: DisplayObject | RenderTexture): number[]; - - destroy(): void; - - } - export class WebGLExtract { - protected renderer: WebGLRenderer; - - constructor(renderer: WebGLRenderer); - - image(target?: DisplayObject | RenderTexture): HTMLImageElement; - base64(target?: DisplayObject | RenderTexture): string; - canvas(target?: DisplayObject | RenderTexture): HTMLCanvasElement; - pixels(renderTexture?: DisplayObject | RenderTexture): number[]; - - destroy(): void; - } - - } - - ////////////////////////////////////////////////////////////////////////////// - ////////////////////////////EXTRAS//////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - export module extras { - - export interface IBitmapTextStyle { - - font?: string | { - - name?: string; - size?: number; - - }; - align?: string; - tint?: number; - - } - export class BitmapText extends Container { - - constructor(text: string, style?: IBitmapTextStyle); - - textWidth: number; - textHeight: number; - protected _glyphs: Sprite[]; - protected _font: string | { - name?: string; - size?: number; - }; - font: string | { - name?: string; - size?: number; - }; - protected _text: string; - maxWidth: number; - maxLineHeight: number; - dirty: boolean; - tint: number; - align: string; - text: string; - anchor: PIXI.Point | number; - - protected updateText(): void; - updateTransform(): void; - getLocalBounds(): Rectangle; - validate(): void; - - static fonts: any; - - } - export class AnimatedSprite extends Sprite { - - constructor(textures: Texture[] | { texture: Texture, time?: number }[]); - - protected _textures: Texture[]; - protected _durations: number[]; - textures: Texture[] | { texture: Texture, time?: number }[]; - animationSpeed: number; - loop: boolean; - onComplete: () => void; - onFrameChange: (currentFrame: number) => void; - protected _currentTime: number; - playing: boolean; - totalFrames: number; - currentFrame: number; - stop(): void; - play(): void; - gotoAndStop(frameNumber: number): void; - gotoAndPlay(frameNumber: number): void; - protected update(deltaTime: number): void; - destroy(): void; - - static fromFrames(frame: string[]): AnimatedSprite; - static fromImages(images: string[]): AnimatedSprite; - - } - export class TextureTransform { - - constructor(texture: Texture, clampMargin?: number); - - protected _texture: Texture; - protected mapCoord: Matrix; - protected uClampFrame: Float32Array; - protected uClampOffset: Float32Array; - protected _lastTextureID: number; - - clampOffset: number; - clampMargin: number; - - texture: Texture; - - update(forceUpdate?: boolean): void; - - } - export class TilingSprite extends Sprite { - - constructor(texture: Texture, width?: number, height?: number); - - tileTransform: TransformStatic; - protected _width: number; - protected _height: number; - protected _canvasPattern: CanvasPattern; - uvTransform: TextureTransform; - - clampMargin: number; - tileScale: Point | ObservablePoint; - tilePosition: Point | ObservablePoint; - - protected _onTextureUpdate(): void; - protected _renderWebGL(renderer: WebGLRenderer): void; - protected _renderCanvas(renderer: CanvasRenderer): void; - protected _calculateBounds(): void; - getLocalBounds(rect?: Rectangle): Rectangle; - containsPoint(point: Point): boolean; - destroy(): void; - - static from(source: number | string | BaseTexture | HTMLCanvasElement | HTMLVideoElement, width?: number, height?: number): TilingSprite; - static fromFrame(frameId: string, width?: number, height?: number): TilingSprite; - // if you remove the next line, the class will break. https://github.com/pixijs/pixi-typescript/issues/96 - static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; - static fromImage(imageId: string, width?: number, height?: number, crossorigin?: boolean, scaleMode?: number): TilingSprite; - - width: number; - height: number; - - } - export class TilingSpriteRenderer extends ObjectRenderer { - - constructor(renderer: WebGLRenderer); - - render(ts: TilingSprite): void; - - } - - } - - ////////////////////////////////////////////////////////////////////////////// - ////////////////////////////FILTERS/////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - export module filters { - - export class FXAAFilter extends Filter { } - export class BlurFilter extends Filter { - - constructor(strength?: number, quality?: number, resolution?: number, kernelSize?: number); - - blurXFilter: BlurXFilter; - blurYFilter: BlurYFilter; - resolution: number; - padding: number; - passes: number; - blur: number; - blurX: number; - blurY: number; - quality: number; - - } - export class BlurXFilter extends Filter { - - constructor(strength?: number, quality?: number, resolution?: number, kernelSize?: number); - - protected _quality: number; - - quality: number; - passes: number; - resolution: number; - strength: number; - firstRun: boolean; - blur: number; - - } - export class BlurYFilter extends Filter { - - constructor(strength?: number, quality?: number, resolution?: number, kernelSize?: number); - - protected _quality: number; - - quality: number; - passes: number; - resolution: number; - strength: number; - firstRun: boolean; - blur: number; - - } - export class ColorMatrixFilter extends Filter { - - constructor(); - - protected _loadMatrix(matrix: number[], multiply?: boolean): void; - protected _multiply(out: number[], a: number[], b: number[]): void; - protected _colorMatrix(matrix: number[]): void; - - matrix: number[]; - - brightness(b: number, multiply?: boolean): void; - greyscale(scale: number, multiply?: boolean): void; - blackAndWhite(multiply?: boolean): void; - hue(rotation: number, multiply?: boolean): void; - contrast(amount: number, multiply?: boolean): void; - saturate(amount: number, multiply?: boolean): void; - desaturate(multiply?: boolean): void; - negative(multiply?: boolean): void; - sepia(multiply?: boolean): void; - technicolor(multiply?: boolean): void; - polaroid(multiply?: boolean): void; - toBGR(multiply?: boolean): void; - kodachrome(multiply?: boolean): void; - browni(multiply?: boolean): void; - vintage(multiply?: boolean): void; - colorTone(desaturation: number, toned: number, lightColor: string, darkColor: string, multiply?: boolean): void; - night(intensity: number, multiply?: boolean): void; - predator(amount: number, multiply?: boolean): void; - lsd(multiply?: boolean): void; - reset(): void; - - } - export class DisplacementFilter extends Filter { - - constructor(sprite: Sprite, scale?: number); - - scale: Point; - map: Texture; - - } - export class VoidFilter extends Filter { - glShaderKey: string; - } - - // pixi-filters.d.ts todo - // https://github.com/pixijs/pixi-filters/ - export class NoiseFilter extends Filter { - - noise: number; - - } - - } - - ////////////////////////////////////////////////////////////////////////////// - ////////////////////////////INTERACTION/////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - export module interaction { - - export interface InteractionEvent { - - stopped: boolean; - target: DisplayObject; - currentTarget: DisplayObject; - type: string; - data: InteractionData; - stopPropagation(): void; - - } - export class InteractionData { - - global: Point; - - protected _target: DisplayObject; - target: DisplayObject; - targetProxy: DisplayObject; - originalEvent: Event; - - getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; - - } - export class InteractionManager extends utils.EventEmitter { - - constructor(renderer: SystemRenderer, options?: { autoPreventDefault?: boolean; interactionFrequency?: number; }); - - renderer: SystemRenderer; - autoPreventDefault: boolean; - interactionFrequency: number; - mouse: InteractionData; - pointer: InteractionData; - eventData: { - stopped: boolean; - target: any; - type: any; - data: InteractionData; - stopPropagination(): void; - }; - interactiveDataPool: InteractionData[]; - protected interactionDOMElement: HTMLElement; - protected moveWhenInside: boolean; - protected eventsAdded: boolean; - mouseOverRenderer: boolean; - supportsTouchEvents: boolean; - supportsPointerEvents: boolean; - normalizeTouchEvents: boolean; - normalizeMouseEvents: boolean; - - protected onMouseUp: (event: MouseEvent) => void; - protected processMouseUp: (displayObject: DisplayObject, hit: boolean) => void; - protected onMouseDown: (event: MouseEvent) => void; - protected processMouseDown: (displayObject: DisplayObject, hit: boolean) => void; - protected onMouseMove: (event: MouseEvent) => void; - protected processMouseMove: (displayObject: DisplayObject, hit: boolean) => void; - protected onMouseOut: (event: MouseEvent) => void; - protected processMouseOverOut: (displayObject: DisplayObject, hit: boolean) => void; - protected onMouseOver: (event: MouseEvent) => void; - - protected onPointerUp: (event: PointerEvent) => void; - protected processPointerUp: (displayObject: DisplayObject, hit: boolean) => void; - protected onPointerDown: (event: PointerEvent) => void; - protected processPointerDown: (displayObject: DisplayObject, hit: boolean) => void; - protected onPointerMove: (event: PointerEvent) => void; - protected processPointerMove: (displayObject: DisplayObject, hit: boolean) => void; - protected onPointerOut: (event: PointerEvent) => void; - protected processPointerOut: (displayObject: DisplayObject, hit: boolean) => void; - protected onPointerOver: (event: PointerEvent) => void; - - protected onTouchStart: (event: TouchEvent) => void; - protected processTouchStart: (DisplayObject: DisplayObject, hit: boolean) => void; - protected onTouchEnd: (event: TouchEvent) => void; - protected processTouchEnd: (displayObject: DisplayObject, hit: boolean) => void; - protected onTouchMove: (event: TouchEvent) => void; - protected processTouchMove: (displayObject: DisplayObject, hit: boolean) => void; - defaultCursorStyle: string; - currentCursorStyle: string; - protected _tempPoint: Point; - resolution: number; - protected setTargetElement(element: HTMLElement, resolution: number): void; - protected addEvents(): void; - protected removeEvents(): void; - update(deltaTime: number): void; - protected dispatchEvent(displayObject: DisplayObject, eventString: string, eventData: any): void; - mapPositionToPoint(point: Point, x: number, y: number): void; - protected processInteractive(point: Point, displayObject: DisplayObject, func: (displayObject: DisplayObject, hit: boolean) => void, hitTest: boolean, interactive: boolean): boolean; - protected _startInteractionProcess(): void; - protected _queueAdd(displayObject: DisplayObject, order: number): void; - protected _finishInteractionProcess(func: Function): void; - protected getTouchData(touchEvent: InteractionData): InteractionData; - protected returnTouchData(touchData: InteractionData): void; - protected normalizeToPointerData(Event: Event): void; - - destroy(): void; - - } - export interface InteractiveTarget { - - interactive: boolean; - interactiveChildren: boolean; - hitArea: IHitArea; - buttonMode: boolean; - defaultCursor: string; - - } - export interface InteractiveTargetProxy extends InteractiveTarget { - } - - } - - ////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////LOADER///////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - // extends - // https://github.com/englercj/resource-loader/ - // 1.6.4 - - export module loaders { - - export interface ILoaderOptions { - - crossOrigin?: boolean | string; - loadType?: number; - xhrType?: string; - metaData?: any; - - } - export interface IResourceDictionary { - - [index: string]: PIXI.loaders.Resource; - - } - export class Loader extends utils.EventEmitter { - - protected static _pixiMiddleware: Function[]; - static addPixiMiddleware(fn: Function): void; - - constructor(baseUrl?: string, concurrency?: number); - - baseUrl: string; - progress: number; - loading: boolean; - resources: IResourceDictionary; - - add(name: string, url: string, options?: ILoaderOptions, cb?: () => void): Loader; - add(url: string, options?: ILoaderOptions, cb?: () => void): Loader; - // todo I am not sure of object literal notional (or its options) so just allowing any but would love to improve this - add(obj: any, options?: ILoaderOptions, cb?: () => void): Loader; - - on(event: "complete", fn: (loader: loaders.Loader, object: any) => void, context?: any): utils.EventEmitter; - on(event: "error", fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; - on(event: "load", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; - on(event: "progress", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; - on(event: "start", fn: (loader: loaders.Loader) => void, context?: any): utils.EventEmitter; - on(event: string, fn: Function, context?: any): utils.EventEmitter; - - once(event: "complete", fn: (loader: loaders.Loader, object: any) => void, context?: any): utils.EventEmitter; - once(event: "error", fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; - once(event: "load", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; - once(event: "progress", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; - once(event: "start", fn: (loader: loaders.Loader) => void, context?: any): utils.EventEmitter; - once(event: string, fn: Function, context?: any): utils.EventEmitter; - - before(fn: Function): Loader; - pre(fn: Function): Loader; - - after(fn: Function): Loader; - use(fn: Function): Loader; - - reset(): void; - - load(cb?: (loader: loaders.Loader, object: any) => void): Loader; - - } - export interface ITextureDictionary { - [index: string]: PIXI.Texture; - } - - export class Resource extends utils.EventEmitter { - - static LOAD_TYPE: { - XHR: number; - IMAGE: number; - AUDIO: number; - VIDEO: number; - }; - - static XHR_READ_STATE: { - UNSENT: number; - OPENED: number; - HEADERS_RECIEVED: number; - LOADING: number; - DONE: number; - }; - - static XHR_RESPONSE_TYPE: { - DEFAULT: number; - BUFFER: number; - BLOB: number; - DOCUMENT: number; - JSON: number; - TEXT: number; - }; - - constructor(name?: string, url?: string | string[], options?: ILoaderOptions); - - protected _loadSourceElement(type: string): void; - isLoading: boolean; - isComplete: boolean; - - isJson: boolean; - isXml: boolean; - isImage: boolean; - isAudio: boolean; - isVideo: boolean; - - name: string; - texture: Texture; - textures: ITextureDictionary; - url: string; - data: any; - crossOrigin: boolean | string; - loadType: number; - xhrType: string; - error: Error; - xhr: XMLHttpRequest; - SVGMetadataElement: any; - - metadata: any; - spineAtlas: any; - spineData: any; - - complete(): void; - load(cb?: () => void): void; - abort(message: string): void; - - } - } - - ////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////MESH/////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - export module mesh { - - export class Mesh extends Container { - - constructor(texture: Texture, vertices?: Float32Array, uvs?: Float32Array, indices?: Uint16Array, drawMode?: number); - - protected _texture: Texture; - uvs: Float32Array; - vertices: Float32Array; - indices: Uint16Array; - dirty: number; - indexDirty: number; - dirtyVertex: boolean; - protected _geometryVersion: number; - blendMode: number; - pluginName: string; - canvasPadding: number; - drawMode: number; - texture: Texture; - tintRgb: Float32Array; - protected _glDatas: { [n: number]: any; }; - protected _renderWebGL(renderer: WebGLRenderer): void; - protected _renderCanvas(renderer: CanvasRenderer): void; - protected _onTextureUpdate(): void; - protected _calculateBounds(): void; - containsPoint(point: Point): boolean; - tint: number; - - static DRAW_MODES: { - TRIANGLE_MESH: number; - TRIANGLES: number; - }; - - } - - export class CanvasMeshRenderer { - - constructor(renderer: CanvasRenderer); - - renderer: CanvasRenderer; - - render(mesh: Mesh): void; - protected _renderTriangleMesh(mesh: Mesh): void; - protected _renderTriangles(mesh: Mesh): void; - protected _renderDrawTriangle(mesh: Mesh, index0: number, index1: number, index2: number): void; - protected renderMeshFlat(mesh: Mesh): void; - - destroy(): void; - - } - - export class MeshRenderer extends ObjectRenderer { - - constructor(renderer: WebGLRenderer); - - shader: Shader; - render(mesh: Mesh): void; - - } - - export class Plane extends Mesh { - - constructor(texture: Texture, verticesX?: number, verticesY?: number); - protected _ready: boolean; - verticesX: number; - verticesY: number; - drawMode: number; - - refresh(): void; - - protected _onTexureUpdate(): void; - - } - - export class NineSlicePlane extends Plane { - - constructor(texture: Texture, leftWidth?: number, topHeight?: number, rightWidth?: number, bottomHeight?: number); - - width: number; - height: number; - leftWidth: number; - rightWidth: number; - topHeight: number; - bottomHeight: number; - - protected _leftWidth: number; - protected _rightWidth: number; - protected _topHeight: number; - protected _bottomHeight: number; - protected _height: number; - protected _width: number; - protected _origHeight: number; - protected _origWidth: number; - protected _uvh: number; - protected _uvw: number; - - updateHorizontalVertices(): void; - updateVerticalVertices(): void; - protected drawSegment(context: CanvasRenderingContext2D | WebGLRenderingContext, textureSource: any, w: number, h: number, x1: number, y1: number, x2: number, y2: number): void; - - } - - export class Rope extends Mesh { - - constructor(texture: Texture, points: Point[]); - - points: Point[]; - colors: number[]; - protected _ready: boolean; - refresh(): void; - - protected _onTextureUpdate(): void; - updateTransform(): void; - - } - } - - ////////////////////////////////////////////////////////////////////////////// - /////////////////////////////PARTICLES//////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - export module particles { - - export interface IParticleContainerProperties { - - scale?: boolean; - position?: boolean; - rotation?: boolean; - uvs?: boolean; - alpha?: boolean; - - } - export class ParticleContainer extends Container { - - constructor(size?: number, properties?: IParticleContainerProperties, batchSize?: number); - - protected _properties: boolean[]; - protected _maxSize: number; - protected _batchSize: number; - protected _glBuffers: { [n: number]: WebGLBuffer; }; - protected _bufferToUpdate: number; - interactiveChildren: boolean; - blendMode: number; - roundPixels: boolean; - baseTexture: BaseTexture; - - setProperties(properties: IParticleContainerProperties): void; - protected onChildrenChange: (smallestChildIndex?: number) => void; - - destroy(options?: IDestroyOptions | boolean): void; - - } - export class ParticleBuffer { - - constructor(gl: WebGLRenderingContext, properties: any, dynamicPropertyFlags: any[], size: number); - - gl: WebGLRenderingContext; - vertSize: number; - vertByteSize: number; - size: number; - dynamicProperties: any[]; - staticProperties: any[]; - staticStride: number; - staticBuffer: any; - staticData: any; - dynamicStride: number; - dynamicBuffer: any; - dynamicData: any; - - destroy(): void; - - } - export interface IParticleRendererProperty { - attribute: number; - size: number; - uploadFunction: (children: PIXI.DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number) => void; - offset: number; - } - export class ParticleRenderer extends ObjectRenderer { - - constructor(renderer: WebGLRenderer); - - shader: glCore.GLShader; - indexBuffer: WebGLBuffer; - properties: IParticleRendererProperty[]; - protected tempMatrix: Matrix; - - start(): void; - generateBuffers(container: ParticleContainer): ParticleBuffer[]; - uploadVertices(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; - uploadPosition(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; - uploadRotation(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; - uploadUvs(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; - uploadAlpha(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; - destroy(): void; - - indices: Uint16Array; - - } - export interface IParticleShader extends glCore.GLShader { } - - } - - ////////////////////////////////////////////////////////////////////////////// - ////////////////////////////PREPARE/////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - export module prepare { - - interface addHook { - (item: any, queue: any[]): boolean; - } - interface uploadHook { - (prepare: UploadHookSource, item: any): boolean - } - export abstract class BasePrepare{ - - constructor(renderer: SystemRenderer); - - limiter: CountLimiter | TimeLimiter; - protected renderer: SystemRenderer; - protected uploadHookHelper: UploadHookSource; - protected queue: any[]; - protected addHooks: addHook[]; - protected uploadHooks: uploadHook[]; - protected completes: Function[]; - protected ticking: boolean; - protected delayedTick: () => void; - - upload(item: Function | DisplayObject | BaseTexture | TextStyle | any, done?: () => void): void; - protected tick(): void; - protected prepareItems(): void; - register(addHook?: addHook, uploadHook?: uploadHook): this; - add(item: DisplayObject | any): this; - destroy(): void; - - } - export class CanvasPrepare extends BasePrepare { - - constructor(renderer: CanvasRenderer); - - protected canvas: HTMLCanvasElement; - protected ctx: CanvasRenderingContext2D; - - } - export class WebGLPrepare extends BasePrepare { - - constructor(renderer: WebGLRenderer); - - } - export class CountLimiter { - - constructor(maxItemsPerFrame: number); - - protected maxItemsPerFrame: number; - protected itemsLeft: number; - - } - export class TimeLimiter { - - constructor(maxMilliseconds: number); - - protected maxMilliseconds: number; - protected frameStart: number; - - } - - } - - ////////////////////////////////////////////////////////////////////////////// - /////////////////////////////pixi-gl-core///////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - // pixi-gl-core https://github.com/pixijs/pixi-gl-core - // sharedArrayBuffer as a type is not available yet. - // need to fully define what an `Attrib` is. - export module glCore { - - export interface IContextOptions { - /** - * Boolean that indicates if the canvas contains an alpha buffer. - */ - alpha?: boolean; - /** - * Boolean that indicates that the drawing buffer has a depth buffer of at least 16 bits. - */ - depth?: boolean; - /** - * Boolean that indicates that the drawing buffer has a stencil buffer of at least 8 bits. - */ - stencil?: boolean; - /** - * Boolean that indicates whether or not to perform anti-aliasing. - */ - antialias?: boolean; - /** - * Boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. - */ - premultipliedAlpha?: boolean; - /** - * If the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author. - */ - preserveDrawingBuffer?: boolean; - /** - * Boolean that indicates if a context will be created if the system performance is low. - */ - failIfMajorPerformanceCaveat?: boolean; - } - export function createContext(view: HTMLCanvasElement, options?: IContextOptions): WebGLRenderingContext; - export function setVertexAttribArrays(gl: WebGLRenderingContext, attribs: IAttrib[], state?: WebGLState): WebGLRenderingContext; - export class GLBuffer { - - static EMPTY_ARRAY_BUFFER: ArrayBuffer; - - constructor(gl: WebGLRenderingContext, type: number, data: ArrayBuffer | ArrayBufferView | any, drawType: number); - - protected _updateID: number; - gl: WebGLRenderingContext; - buffer: WebGLBuffer; - type: number; - drawType: number; - data: ArrayBuffer | ArrayBufferView | any; - - upload(data: ArrayBuffer | ArrayBufferView | any, offset?: number, dontBind?: boolean): void; - bind(): void; - - static createVertexBuffer(gl: WebGLRenderingContext, data: ArrayBuffer | ArrayBufferView | any, drawType: number): GLBuffer; - static createIndexBuffer(gl: WebGLRenderingContext, data: ArrayBuffer | ArrayBufferView | any, drawType: number): GLBuffer; - static create(gl: WebGLRenderingContext, type: number, data: ArrayBuffer | ArrayBufferView | any, drawType: number): GLBuffer; - - destroy(): void; - - } - export class GLFramebuffer { - - constructor(gl: WebGLRenderingContext, width: number, height: number); - - gl: WebGLRenderingContext; - frameBuffer: WebGLFramebuffer; - stencil: WebGLRenderbuffer; - texture: GLTexture; - width: number; - height: number; - - enableTexture(texture: GLTexture): void; - enableStencil(): void; - clear(r: number, g: number, b: number, a: number): void; - bind(): void; - unbind(): void; - resize(width: number, height: number): void; - destroy(): void; - - static createRGBA(gl: WebGLRenderingContext, width: number, height: number, data: ArrayBuffer | ArrayBufferView | any): GLFramebuffer; - static createFloat32(gl: WebGLRenderingContext, width: number, height: number, data: ArrayBuffer | ArrayBufferView | any): GLFramebuffer; - - } - export class GLShader { - - constructor(gl: WebGLRenderingContext, vertexSrc: string | string[], fragmentSrc: string | string[]); - - gl: WebGLRenderingContext; - program: WebGLProgram; - uniforms: any; - attributes: any; - - bind(): void; - destroy(): void; - - } - export class GLTexture { - - constructor(gl: WebGLRenderingContext, width?: number, height?: number, format?: number, type?: number); - - gl: WebGLRenderingContext; - texture: WebGLTexture; - mipmap: boolean; - premultiplyAlpha: boolean; - width: number; - height: number; - format: number; - type: number; - - upload(source: HTMLImageElement | ImageData | HTMLVideoElement | HTMLCanvasElement): void; - uploadData(data: number, width: number, height: number): void; - bind(location?: number): void; - unbind(): void; - minFilter(linear: boolean): void; - magFilter(linear: boolean): void; - enableMipmap(): void; - enableLinearScaling(): void; - enableNearestScaling(): void; - enableWrapClamp(): void; - enableWrapRepeat(): void; - enableWrapMirrorRepeat(): void; - destroy(): void; - - static fromSource(gl: WebGLRenderingContext, source: HTMLImageElement | ImageData | HTMLVideoElement | HTMLCanvasElement, premultipleAlpha?: boolean): GLTexture; - static fromData(gl: WebGLRenderingContext, data: number[], width: number, height: number): GLTexture; - - } - export interface IAttrib { - - attribute: { - location: boolean; - size: number; - }; - normalized: boolean; - stride: number; - start: number; - buffer: ArrayBuffer; - - } - export interface IWebGLRenderingContextAttribute { - - buffer: WebGLBuffer; - attribute: any; - type: number; - normalized: boolean; - stride: number; - start: number; - - } - export interface IAttribState { - tempAttribState: IAttrib[]; - attribState: IAttrib[]; - } - - export class VertexArrayObject { - - static FORCE_NATIVE: boolean; - - constructor(gl: WebGLRenderingContext, state: WebGLState); - - protected nativeVaoExtension: any; - protected nativeState: IAttribState; - protected nativeVao: VertexArrayObject; - gl: WebGLRenderingContext; - attributes: IAttrib[]; - indexBuffer: GLBuffer; - dirty: boolean; - - bind(): VertexArrayObject; - unbind(): VertexArrayObject; - activate(): VertexArrayObject; - addAttribute(buffer: GLBuffer, attribute: IAttrib, type: number, normalized: boolean, stride: number, start: number): VertexArrayObject; - addIndex(buffer: GLBuffer, options?: any): VertexArrayObject; - clear(): VertexArrayObject; - draw(type: number, size: number, start: number): VertexArrayObject; - destroy(): void; - - } - - } - - ////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////UTILS////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - export interface IDecomposedDataUri { - mediaType: string; - subType: string; - encoding: string; - data: any; - } - - export module utils { - - export function uid(): number; - export function hex2rgb(hex: number, out?: number[]): number[]; - export function hex2string(hex: number): string; - export function rgb2hex(rgb: Number[]): number; - export function canUseNewCanvasBlendModes(): boolean; - export function getResolutionOfUrl(url: string, defaultValue?: number): number; - export function getSvgSize(svgString: string): any; - export function decomposeDataUri(dataUri: string): IDecomposedDataUri; - export function getUrlFileExtension(url: string): string; - export function sayHello(type: string): void; - export function skipHello(): void; - export function isWebGLSupported(): boolean; - export function sign(n: number): number; - export function removeItems(arr: T[], startIdx: number, removeCount: number): void; - export var TextureCache: any; - export var BaseTextureCache: any; - - //https://github.com/kaimallea/isMobile - export module isMobile { - export var apple: { - phone: boolean; - ipod: boolean; - tablet: boolean; - device: boolean; - }; - export var android: { - phone: boolean; - tablet: boolean; - device: boolean; - } - export var amazon: { - phone: boolean; - table: boolean; - device: boolean; - } - export var windows: { - phone: boolean; - tablet: boolean; - device: boolean; - } - export var seven_inch: boolean; - export var other: { - blackberry_10: boolean; - blackberry: boolean; - opera: boolean; - firefox: boolean; - chrome: boolean; - device: boolean; - } - export var any: boolean; - export var phone: boolean; - export var tablet: boolean; - } - - // https://github.com/primus/eventemitter3 - export class EventEmitter { - - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - on(event: string, fn: Function, context?: any): EventEmitter; - once(event: string, fn: Function, context?: any): EventEmitter; - removeListener(event: string, fn: Function, context?: any, once?: boolean): EventEmitter; - removeAllListeners(event: string): EventEmitter; - eventNames(): string[]; - - off(event: string, fn: Function, context?: any, once?: boolean): EventEmitter; - addListener(event: string, fn: Function, context?: any): EventEmitter; - - } - - } - - ////////////////////////////////////////////////////////////////////////////// - /////////////////////////////depreciation///////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - // not sure how to handle blendmodes scalemodes basetexturecache - module core { - - /** - * @class - * @private - * @name SpriteBatch - * @memberof PIXI - * @see PIXI.ParticleContainer - * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. - * @deprecated since version 3.0.0 - */ - type SpriteBatch = ParticleContainer; - - /** - * @class - * @private - * @name AssetLoader - * @memberof PIXI - * @see PIXI.loaders.Loader - * @throws {ReferenceError} The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class. - * @deprecated since version 3.0.0 - */ - type AssetLoader = loaders.Loader; - - /** - * @class - * @private - * @name Stage - * @memberof PIXI - * @see PIXI.Container - * @deprecated since version 3.0.0 - */ - type Stage = Container; - - /** - * @class - * @private - * @name DisplayObjectContainer - * @memberof PIXI - * @see PIXI.Container - * @deprecated since version 3.0.0 - */ - type DisplayObjectContainer = Container; - - /** - * @class - * @private - * @name Strip - * @memberof PIXI - * @see PIXI.mesh.Mesh - * @deprecated since version 3.0.0 - */ - type Strip = mesh.Mesh; - - /** - * @class - * @private - * @name Rope - * @memberof PIXI - * @see PIXI.mesh.Rope - * @deprecated since version 3.0.0 - */ - type Rope = mesh.Rope; - - /** - * @class - * @private - * @name ParticleContainer - * @memberof PIXI - * @see PIXI.particles.ParticleContainer - * @deprecated since version 4.0.0 - */ - type ParticleContainer = particles.ParticleContainer; - - /** - * @class - * @private - * @name MovieClip - * @memberof PIXI - * @see PIXI.extras.MovieClip - * @deprecated since version 3.0.0 - */ - type MovieClip = extras.AnimatedSprite - - /** - * @class - * @private - * @name TilingSprite - * @memberof PIXI - * @see PIXI.extras.TilingSprite - * @deprecated since version 3.0.0 - */ - type TilingSprite = extras.TilingSprite; - - /** - * @class - * @private - * @name BitmapText - * @memberof PIXI - * @see PIXI.extras.BitmapText - * @deprecated since version 3.0.0 - */ - type BitmapText = extras.BitmapText; - - /** - * @namespace - * @private - * @name math - * @memberof PIXI - * @see PIXI - * @deprecated since version 3.0.6 - */ - type math = any; - - /** - * @class - * @private - * @name PIXI.AbstractFilter - * @see PIXI.Filter - * @deprecated since version 3.0.6 - */ - type AbstractFilter = Filter; - - /** - * @class - * @private - * @name PIXI.TransformManual - * @see PIXI.TransformBase - * @deprecated since version 4.0.0 - */ - type TransformManual = TransformBase; - - /** - * @static - * @constant - * @name PIXI.TARGET_FPMS - * @see PIXI.settings.TARGET_FPMS - * @deprecated since version 4.2.0 - */ - type TARGET_FPMS = number; - - /** - * @static - * @constant - * @name PIXI.FILTER_RESOLUTION - * @see PIXI.settings.FILTER_RESOLUTION - * @deprecated since version 4.2.0 - */ - type FILTER_RESOLUTION = number; - - /** - * @static - * @constant - * @name PIXI.RESOLUTION - * @see PIXI.settings.RESOLUTION - * @deprecated since version 4.2.0 - */ - type RESOLUTION = number; - - /** - * @static - * @constant - * @name PIXI.MIPMAP_TEXTURES - * @see PIXI.settings.MIPMAP_TEXTURES - * @deprecated since version 4.2.0 - */ - type MIPMAP_TEXTURES = any; - - /** - * @static - * @constant - * @name PIXI.SPRITE_BATCH_SIZE - * @see PIXI.settings.SPRITE_BATCH_SIZE - * @deprecated since version 4.2.0 - */ - type SPRITE_BATCH_SIZE = number; - - /** - * @static - * @constant - * @name PIXI.SPRITE_MAX_TEXTURES - * @see PIXI.settings.SPRITE_MAX_TEXTURES - * @deprecated since version 4.2.0 - */ - type SPRITE_MAX_TEXTURES = number; - - /** - * @static - * @constant - * @name PIXI.RETINA_PREFIX - * @see PIXI.settings.RETINA_PREFIX - * @deprecated since version 4.2.0 - */ - type RETINA_PREFIX = RegExp | string; - - /** - * @static - * @constant - * @name PIXI.DEFAULT_RENDER_OPTIONS - * @see PIXI.settings.RENDER_OPTIONS - * @deprecated since version 4.2.0 - */ - type DEFAULT_RENDER_OPTIONS = number; - - } - - export module extras { - - /** - * @class - * @name MovieClip - * @memberof PIXI.extras - * @see PIXI.extras.AnimatedSprite - * @deprecated since version 4.2.0 - */ - type MovieClip = extras.AnimatedSprite; - - } +// from CONST +export var VERSION: typeof CONST.VERSION; +export var PI_2: typeof CONST.PI_2; +export var RAD_TO_DEG: typeof CONST.RAD_TO_DEG; +export var DEG_TO_RAD: typeof CONST.DEG_TO_RAD; +export var RENDERER_TYPE: typeof CONST.RENDERER_TYPE; +export var BLEND_MODES: typeof CONST.BLEND_MODES; +export var DRAW_MODES: typeof CONST.DRAW_MODES; +export var SCALE_MODES: typeof CONST.SCALE_MODES; +export var WRAP_MODES: typeof CONST.WRAP_MODES; +export var TRANSFORM_MODE: typeof CONST.TRANSFORM_MODE; +export var PRECISION: typeof CONST.PRECISION; +export var TEXT_STYLE_CHANGED: typeof CONST.TEXT_STYLE_CHANGED; +export var GC_MODES: typeof CONST.GC_MODES; +export var SHAPES: typeof CONST.SHAPES; +export var TEXT_GRADIENT: typeof CONST.TEXT_GRADIENT; + +export function autoDetectRenderer(width: number, height: number, options?: PIXI.IRendererOptions, noWebGL?: boolean): PIXI.WebGLRenderer | PIXI.CanvasRenderer; +export var loader: PIXI.loaders.Loader; + +////////////////////////////////////////////////////////////////////////////// +///////////////////////////////SETTINGS/////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +export namespace settings { + export var TARGET_FPMS: number; + export var MIPMAP_TEXTURES: boolean; + export var RESOLUTION: number; + export var FILTER_RESOLUTION: number; + export var SPRITE_MAX_TEXTURES: number; + export var SPRITE_BATCH_SIZE: number; + export var RETINA_PREFIX: RegExp; + export var RENDER_OPTIONS: { + view: HTMLCanvasElement, + antialias: boolean, + forceFXAA: boolean, + autoResize: boolean, + transparent: boolean, + backgroundColor: number, + clearBeforeRender: boolean, + preserveDrawingBuffer: boolean, + roundPixels: boolean + }; + export var TRANSFORM_MODE: number; + export var GC_MODE: number; + export var GC_MAX_IDLE: number; + export var GC_MAX_CHECK_COUNT: number; + export var WRAP_MODE: number; + export var SCALE_MODE: number; + export var PRECISION: string; + export var UPLOADS_PER_FRAME: number; + export var CAN_UPLOAD_SAME_BUFFER: boolean; +} + +////////////////////////////////////////////////////////////////////////////// +/////////////////////////////ACCESSIBILITY//////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +export namespace accessibility { + + // accessibility + export class AccessibilityManager { + + constructor(renderer: CanvasRenderer | WebGLRenderer); + + protected div: HTMLElement; + protected pool: HTMLElement[]; + protected renderId: number; + debug: boolean; + renderer: SystemRenderer; + protected children: IAccessibleTarget[]; + protected isActive: boolean; + + protected activate(): void; + protected deactivate(): void; + protected updateAccessibleObjects(displayObject: DisplayObject): void; + protected update(): void; + protected capHitArea(hitArea: IHitArea): void; + protected addChild(displayObject: DisplayObject): void; + protected _onClick(e: interaction.InteractionEvent): void; + protected _onFocus(e: interaction.InteractionEvent): void; + protected _onFocusOut(e: interaction.InteractionEvent): void; + protected _onKeyDown(e: interaction.InteractionEvent): void; + protected _onMouseMove(): void; + + destroy(): void; + + } + export interface IAccessibleTarget { + + accessible: boolean; + accessibleTitle: string; + accessibleHint: string; + tabIndex: number; + + } } -declare module pixi { - export var gl: typeof PIXI.glCore; +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////CORE////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +// const + +export namespace CONST { + export var VERSION: string; + export var PI_2: number; + export var RAD_TO_DEG: number; + export var DEG_TO_RAD: number; + export var TARGET_FPMS: number; + export var RENDERER_TYPE: { + UNKNOWN: number; + WEBGL: number; + CANVAS: number; + }; + export var BLEND_MODES: { + NORMAL: number; + ADD: number; + MULTIPLY: number; + SCREEN: number; + OVERLAY: number; + DARKEN: number; + LIGHTEN: number; + COLOR_DODGE: number; + COLOR_BURN: number; + HARD_LIGHT: number; + SOFT_LIGHT: number; + DIFFERENCE: number; + EXCLUSION: number; + HUE: number; + SATURATION: number; + COLOR: number; + LUMINOSITY: number; + }; + export var DRAW_MODES: { + POINTS: number; + LINES: number; + LINE_LOOP: number; + LINE_STRIP: number; + TRIANGLES: number; + TRIANGLE_STRIP: number; + TRIANGLE_FAN: number; + }; + export var SCALE_MODES: { + LINEAR: number, + NEAREST: number + }; + export var GC_MODES: { + AUTO: number; + MANUAL: number; + }; + export var WRAP_MODES: { + CLAMP: number; + MIRRORED_REPEAT: number; + REPEAT: number; + }; + export var TRANSFORM_MODE: { + DEFAULT: number; + DYNAMIC: number; + STATIC: number; + }; + export var URL_FILE_EXTENSION: RegExp | string; + export var DATA_URI: RegExp | string; + export var SVG_SIZE: RegExp | string; + export var SHAPES: { + POLY: number; + RECT: number; + CIRC: number; + ELIP: number; + RREC: number; + }; + export var PRECISION: { + LOW: string; + MEDIUM: string; + HIGH: string; + }; + export var TEXT_GRADIENT: { + LINEAR_VERTICAL: number; + LINEAR_HORIZONTAL: number; + }; + export var TEXT_STYLE_CHANGED: string; + } -declare module "pixi.js" { - export = PIXI; +// display + +export interface IDestroyOptions { + children?: boolean; + texture?: boolean; + baseTexture?: boolean; } +export class Bounds { + + minX: number; + minY: number; + maxX: number; + maxY: number; + rect: Rectangle; + + isEmpty(): boolean; + clear(): void; + + getRectangle(rect?: Rectangle): Rectangle; + addPoint(point: Point): void; + addQuad(vertices: number[]): Bounds; + addFrame(transform: Transform, x0: number, y0: number, x1: number, y1: number): void; + addVertices(transform: Transform, vertices: number[], beginOffset: number, endOffset: number): void; + addBounds(bounds: Bounds): void; + addBoundsMask(bounds: Bounds, mask: Bounds): void; + addBoundsArea(bounds: Bounds, area: Rectangle): void; + +} +export class Container extends DisplayObject { + + // begin extras.getChildByName + getChildByName(name: string): DisplayObject; + // end extras.getChildByName + + children: DisplayObject[]; + width: number; + height: number; + + protected onChildrenChange: (...args: any[]) => void; + addChild(child: T, ...additionalChildren: DisplayObject[]): T; + addChildAt(child: T, index: number): T; + swapChildren(child: DisplayObject, child2: DisplayObject): void; + getChildIndex(child: DisplayObject): number; + setChildIndex(child: DisplayObject, index: number): void; + getChildAt(index: number): DisplayObject; + removeChild(child: DisplayObject): DisplayObject; + removeChildAt(index: number): DisplayObject; + removeChildren(beginIndex?: number, endIndex?: number): DisplayObject[]; + updateTransform(): void; + calculateBounds(): void; + protected _calculateBounds(): void; + protected containerUpdateTransform(): void; + renderWebGL(renderer: WebGLRenderer): void; + renderAdvancedWebGL(renderer: WebGLRenderer): void; + protected _renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; + renderCanvas(renderer: CanvasRenderer): void; + destroy(options?: IDestroyOptions | boolean): void; + + once(event: "added", fn: (displayObject: DisplayObject) => void, context?: any): utils.EventEmitter; + once(event: "removed", fn: (DisplayObject: DisplayObject) => void, context?: any): utils.EventEmitter; + once(event: string, fn: Function, context?: any): utils.EventEmitter; + on(event: "added", fn: (displayObject: DisplayObject) => void, context?: any): utils.EventEmitter; + on(event: "removed", fn: (DisplayObject: DisplayObject) => void, context?: any): utils.EventEmitter; + on(event: string, fn: Function, context?: any): utils.EventEmitter; + off(event: string, fn: Function, context?: any): utils.EventEmitter; + +} +export class DisplayObject extends utils.EventEmitter implements interaction.InteractiveTarget { + + // begin extras.cacheAsBitmap + protected _cacheAsBitmap: boolean; + protected _cacheData: boolean; + cacheAsBitmap: boolean; + protected _renderCachedWebGL(renderer: WebGLRenderer): void; + protected _initCachedDisplayObject(renderer: WebGLRenderer): void; + protected _renderCachedCanvas(renderer: CanvasRenderer): void; + protected _initCachedDisplayObjectCanvas(renderer: CanvasRenderer): void; + protected _calculateCachedBounds(): Rectangle; + protected _getCachedLocalBounds(): Rectangle; + protected _destroyCachedDisplayObject(): void; + protected _cacheAsBitmapDestroy(): void; + // end extras.cacheAsBitmap + + // begin extras.getChildByName + name: string; + // end extras.getChildByName + + // begin extras.getGlobalPosition + getGlobalPosition(point?: Point, skipUpdate?: boolean): Point; + // end extras.getGlobalPosition + + // begin accessible target + accessible: boolean; + accessibleTitle: string; + accessibleHint: string; + tabIndex: number; + // end accessible target + + // begin interactive target + interactive: boolean; + buttonMode: boolean; + hitArea: IHitArea; + interactiveChildren: boolean; + defaultCursor: string; + _isRightDown: boolean; + _isLeftDown: boolean; + // end interactive target + + transform: TransformBase; + alpha: number; + visible: boolean; + renderable: boolean; + parent: Container; + worldAlpha: number; + filterArea: Rectangle; + protected _filters: Filter[]; + protected _enabledFilters: Filter[]; + protected _bounds: Bounds; + protected _boundsID: number; + protected _lastBoundsID: number; + protected _boundsRect: Rectangle; + protected _localBoundsRect: Rectangle; + protected _mask: Rectangle; + x: number; + y: number; + worldTransform: Matrix; + localTransform: Matrix; + position: Point; + scale: Point; + pivot: Point; + skew: Point; + rotation: number; + worldVisible: boolean; + mask: PIXI.Graphics | PIXI.Sprite; + filters: Filter[]; + + updateTransform(): void; + protected displayObjectUpdateTransform(): void; + protected _recursivePostUpdateTransform(): void; + getBounds(skipUpdate?: boolean, rect?: Rectangle): Rectangle; + getLocalBounds(rect?: Rectangle): Rectangle; + toGlobal(position: Point, point?: Point, skipUpdate?: boolean): Point; + toLocal(position: Point, from?: DisplayObject, point?: Point, skipUpdate?: boolean): Point; + protected renderWebGL(renderer: WebGLRenderer): void; + renderCanvas(renderer: CanvasRenderer): void; + setParent(container: Container): Container; + setTransform(x?: number, y?: number, scaleX?: number, scaleY?: number, rotation?: number, skewX?: number, skewY?: number, pivotX?: number, pivotY?: number): DisplayObject; + destroy(): void; + + on(event: string, fn: Function, context?: any): utils.EventEmitter; + once(event: string, fn: Function, context?: any): utils.EventEmitter; + off(event: string, fn: Function, context?: any): utils.EventEmitter; + + /* + on(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + + once(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + */ + +} + +export class TransformBase { + + static IDENTITY: TransformBase; + + worldTransform: Matrix; + localTransform: Matrix; + protected _worldID: number; + updateLocalTransform(): void; + updateTransform(parentTransform: TransformBase): void; + updateWorldTransform(parentTransform: TransformBase): void; + +} +export class TransformStatic extends TransformBase { + + position: ObservablePoint; + scale: ObservablePoint; + pivot: ObservablePoint; + skew: ObservablePoint; + + protected _rotation: number; + protected _sr: number; + protected _cr: number; + protected _cy: number; + protected _sy: number; + protected _nsx: number; + protected _cx: number; + protected _currentLocalID: number; + + protected onChange(): void; + updateSkew(): void; + updateLocalTransform(): void; + updateTransform(parentTransform: TransformBase): void; + setFromMatrix(matrix: Matrix): void; + + rotation: number; + +} +export class Transform extends TransformBase { + + constructor(); + + position: Point; + scale: Point; + skew: ObservablePoint; + pivot: Point; + + protected _rotation: number; + protected _sr: number; + protected _cr: number; + protected _cy: number; + protected _sy: number; + protected _nsx: number; + protected _cx: number; + + updateSkew(): void; + setFromMatrix(matrix: Matrix): void; + + rotation: number; + +} + +// graphics + +export class GraphicsData { + + constructor(lineWidth: number, lineColor: number, lineAlpha: number, fillColor: number, fillAlpha: number, fill: boolean, shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon); + + lineWidth: number; + lineColor: number; + lineAlpha: number; + protected _lineTint: number; + fillColor: number; + fillAlpha: number; + protected _fillTint: number; + fill: boolean; + protected holes: IShape[]; + shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon; + type: number; + clone(): GraphicsData; + addHole(shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon): void; + destroy(options?: IDestroyOptions | boolean): void; + +} +export class Graphics extends Container { + + fillAlpha: number; + lineWidth: number; + lineColor: number; + protected graphicsData: GraphicsData[]; + tint: number; + protected _prevTint: number; + blendMode: number; + currentPath: GraphicsData; + protected _webGL: any; + isMask: boolean; + boundsPadding: number; + protected _localBounds: Bounds; + dirty: boolean; + fastRectDirty: number; + clearDirty: number; + boundsDirty: number; + protected cachedSpriteDirty: boolean; + protected _spriteRect: Rectangle; + protected _fastRect: boolean; + + static _SPRITE_TEXTURE: Texture; + + clone(): Graphics; + lineStyle(lineWidth?: number, color?: number, alpha?: number): Graphics; + moveTo(x: number, y: number): Graphics; + lineTo(x: number, y: number): Graphics; + quadraticCurveTo(cpX: number, cpY: number, toX: number, toY: number): Graphics; + bezierCurveTo(cpX: number, cpY: number, cpX2: number, cpY2: number, toX: number, toY: number): Graphics; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): Graphics; + arc(cx: number, cy: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): Graphics; + beginFill(color: number, alpha?: number): Graphics; + endFill(): Graphics; + drawRect(x: number, y: number, width: number, height: number): Graphics; + drawRoundedRect(x: number, y: number, width: number, height: number, radius: number): Graphics; + drawCircle(x: number, y: number, radius: number): Graphics; + drawEllipse(x: number, y: number, width: number, height: number): Graphics; + drawPolygon(path: number[] | Point[]): Graphics; + clear(): Graphics; + isFastRect(): boolean; + protected _renderCanvas(renderer: CanvasRenderer): void; + protected _calculateBounds(): Rectangle; + protected _renderSpriteRect(renderer: PIXI.SystemRenderer): void; + containsPoint(point: Point): boolean; + updateLocalBounds(): void; + drawShape(shape: IShape | Circle | Rectangle | Ellipse | Polygon | RoundedRectangle): GraphicsData; + generateCanvasTexture(scaleMode?: number, resolution?: number): Texture; + protected closePath(): Graphics; + protected addHole(): Graphics; + destroy(options?: IDestroyOptions | boolean): void; + +} +export class CanvasGraphicsRenderer { + + constructor(renderer: SystemRenderer); + render(graphics: Graphics): void; + protected updateGraphicsTint(graphics: Graphics): void; + protected renderPolygon(points: Point[], close: boolean, context: CanvasRenderingContext2D): void; + destroy(): void; + +} +export class GraphicsRenderer extends ObjectRenderer { + + constructor(renderer: PIXI.CanvasRenderer); + + protected graphicsDataPool: GraphicsData[]; + protected primitiveShader: PrimitiveShader; + gl: WebGLRenderingContext; + + CONTEXT_UID: number; + + destroy(): void; + render(graphics: Graphics): void; + protected updateGraphics(graphics: PIXI.Graphics): void; + getWebGLData(webGL: WebGLRenderingContext, type: number): WebGLGraphicsData; + +} +export class WebGLGraphicsData { + + constructor(gl: WebGLRenderingContext, shader: glCore.GLShader, attribsState: glCore.IAttribState); + + gl: WebGLRenderingContext; + color: number[]; + points: Point[]; + indices: number[]; + buffer: WebGLBuffer; + indexBuffer: WebGLBuffer; + dirty: boolean; + glPoints: number[]; + glIndices: number[]; + shader: glCore.GLShader; + vao: glCore.VertexArrayObject; + + reset(): void; + upload(): void; + destroy(): void; + +} +export class PrimitiveShader extends glCore.GLShader { } + +// math + +export namespace GroupD8 { + + export var E: number; + export var SE: number; + export var S: number; + export var SW: number; + export var W: number; + export var NW: number; + export var N: number; + export var NE: number; + export var MIRROR_HORIZONTAL: number; + export var MIRROR_VERTICAL: number; + + export function uX(ind: number): number; + export function uY(ind: number): number; + export function vX(ind: number): number; + export function vY(ind: number): number; + export function inv(rotation: number): number; + export function add(rotationSecond: number, rotationFirst: number): number; + export function sub(rotationSecond: number, rotationFirst: number): number; + export function rotate180(rotation: number): number; + export function isSwapWidthHeight(rotation: number): boolean; + export function byDirection(dx: number, dy: number): number; + export function matrixAppendRotationInv(matrix: Matrix, rotation: number, tx: number, ty: number): void; + +} +export class Matrix { + + a: number; + b: number; + c: number; + d: number; + tx: number; + ty: number; + + fromArray(array: number[]): void; + set(a: number, b: number, c: number, d: number, tx: number, ty: number): Matrix; + toArray(transpose?: boolean, out?: number[]): number[]; + apply(pos: Point, newPos?: Point): Point; + applyInverse(pos: Point, newPos?: Point): Point; + translate(x: number, y: number): Matrix; + scale(x: number, y: number): Matrix; + rotate(angle: number): Matrix; + append(matrix: Matrix): Matrix; + setTransform(x: number, y: number, pivotX: number, pivotY: number, scaleX: number, scaleY: number, rotation: number, skewX: number, skewY: number): PIXI.Matrix; + prepend(matrix: Matrix): Matrix; + invert(): Matrix; + identity(): Matrix; + decompose(transform: TransformBase): TransformBase; + clone(): Matrix; + copy(matrix: Matrix): Matrix; + + static IDENTITY: Matrix; + static TEMP_MATRIX: Matrix; + +} +export class ObservablePoint { + + constructor(cb: Function, scope?: any, x?: number, y?: number); + + x: number; + y: number; + cb: () => void; + scope: any; + + set(x?: number, y?: number): void; + copy(point: Point | ObservablePoint): void; + +} +export class Point { + + constructor(x?: number, y?: number); + + x: number; + y: number; + + clone(): Point; + copy(p: Point): void; + equals(p: Point): boolean; + set(x?: number, y?: number): void; + +} + +export interface IShape { +} +export interface IHitArea extends IShape { + + contains(x: number, y: number): boolean; + +} +export class Circle { + + constructor(x?: number, y?: number, radius?: number); + + x: number; + y: number; + radius: number; + type: number; + + clone(): Circle; + contains(x: number, y: number): boolean; + getBounds(): Rectangle; + +} +export class Ellipse { + + constructor(x?: number, y?: number, width?: number, height?: number); + + x: number; + y: number; + width: number; + height: number; + type: number; + + clone(): Ellipse; + contains(x: number, y: number): boolean; + getBounds(): Rectangle; + +} +export class Polygon { + + constructor(points: Point[] | number[]); + constructor(...points: Point[]); + constructor(...points: number[]); + + closed: boolean; + points: number[]; + type: number; + + clone(): Polygon; + contains(x: number, y: number): boolean; + close(): void; + +} +export class Rectangle { + + constructor(x?: number, y?: number, width?: number, height?: number); + + x: number; + y: number; + width: number; + height: number; + type: number; + left: number; + right: number; + top: number; + bottom: number; + + static EMPTY: Rectangle; + + clone(): Rectangle; + copy(rectangle: Rectangle): Rectangle; + contains(x: number, y: number): boolean; + pad(paddingX: number, paddingY: number): void; + fit(rectangle: Rectangle): void; + enlarge(rect: Rectangle): void; + +} +export class RoundedRectangle { + + constructor(x?: number, y?: number, width?: number, height?: number, radius?: number); + + x: number; + y: number; + width: number; + height: number; + radius: number; + type: number; + + clone(): RoundedRectangle; + contains(x: number, y: number): boolean; + +} + +// renderers + +export interface IRendererOptions { + + view?: HTMLCanvasElement; + transparent?: boolean; + autoResize?: boolean; + antialias?: boolean; + resolution?: number; + clearBeforeRender?: boolean; + backgroundColor?: number; + roundPixels?: boolean; + context?: WebGLRenderingContext; + +} +export class SystemRenderer extends utils.EventEmitter { + + constructor(system: string, width?: number, height?: number, options?: IRendererOptions); + + type: number; + width: number; + height: number; + view: HTMLCanvasElement; + resolution: number; + transparent: boolean; + autoResize: boolean; + blendModes: any; // todo? + preserveDrawingBuffer: boolean; + clearBeforeRender: boolean; + roundPixels: boolean; + protected _backgroundColor: number; + protected _backgroundColorRgba: number[]; + protected _backgroundColorString: string; + protected _tempDisplayObjectParent: Container; + protected _lastObjectRendered: DisplayObject; + backgroundColor: number; + + resize(width: number, height: number): void; + generateTexture(displayObject: DisplayObject, scaleMode?: number, resolution?: number): RenderTexture; + render(...args: any[]): void; + destroy(removeView?: boolean): void; + +} +export class CanvasRenderer extends SystemRenderer { + + // plugintarget mixin start + static __plugins: any[]; + static registerPlugin(pluginName: string, ctor: Function): void; + plugins: any; + initPlugins(): void; + destroyPlugins(): void; + // plugintarget mixin end + + constructor(width?: number, height?: number, options?: IRendererOptions); + + rootContext: CanvasRenderingContext2D; + rootResolution: number; + refresh: boolean; + maskManager: CanvasMaskManager; + smoothProperty: string; + extract: extract.CanvasExtract; + + context: CanvasRenderingContext2D; + + render(displayObject: PIXI.DisplayObject, renderTexture?: PIXI.RenderTexture, clear?: boolean, transform?: PIXI.Transform, skipUpdateTransform?: boolean): void + setBlendMode(blendMode: number): void; + destroy(removeView?: boolean): void; + resize(w: number, h: number): void; + + on(event: "prerender", fn: () => void, context?: any): utils.EventEmitter; + on(event: "postrender", fn: () => void, context?: any): utils.EventEmitter; + on(event: string, fn: Function, context?: any): utils.EventEmitter; + once(event: "prerender", fn: () => void, context?: any): utils.EventEmitter; + once(event: "postrender", fn: () => void, context?: any): utils.EventEmitter; + once(event: string, fn: Function, context?: any): utils.EventEmitter; + off(event: string, fn: Function, context?: any): utils.EventEmitter; + +} +export class CanvasMaskManager { + + constructor(renderer: CanvasRenderer); + + pushMask(maskData: any): void; + protected renderGraphicsShape(graphics: Graphics): void; + popMask(renderer: WebGLRenderer | CanvasRenderer): void; + destroy(): void; + +} +export class CanvasRenderTarget { + + constructor(width: number, height: number, resolution: number); + + canvas: HTMLCanvasElement; + context: CanvasRenderingContext2D; + resolution: number; + + width: number; + height: number; + + clear(): void; + resize(width: number, height: number): void; + destroy(): void; + +} + +export interface IWebGLRendererOptions { + + view?: HTMLCanvasElement; + transparent?: boolean; + autoResize?: boolean; + antialias?: boolean; + forceFXAA?: boolean; + resolution?: number; + clearBeforeRender?: boolean; + preserveDrawingBuffer?: boolean; + roundPixels?: boolean; + +} +export class WebGLRenderer extends SystemRenderer { + + // plugintarget mixin start + static __plugins: any[]; + static registerPlugin(pluginName: string, ctor: Function): void; + plugins: any; + initPlugins(): void; + destroyPlugins(): void; + // plugintarget mixin end + + constructor(width?: number, height?: number, options?: IWebGLRendererOptions); + + protected _contextOptions: { + alpha: boolean; + antiAlias: boolean; + premultipliedAlpha: boolean; + stencil: boolean; + preseveDrawingBuffer: boolean; + }; + protected _backgroundColorRgba: number[]; + maskManager: MaskManager; + stencilManager: StencilManager; + emptyRenderer: ObjectRenderer; + currentRenderer: ObjectRenderer; + gl: WebGLRenderingContext; + CONTEXT_UID: number; + state: WebGLState; + renderingToScreen: boolean; + boundTextures: Texture[]; + filterManager: FilterManager; + textureManager: TextureManager; + extract: extract.WebGLExtract; + protected drawModes: any; + protected _activeShader: Shader; + _activeRenderTarget: RenderTarget; + protected _initContext(): void; + + render(displayObject: PIXI.DisplayObject, renderTexture?: PIXI.RenderTexture, clear?: boolean, transform?: PIXI.Transform, skipUpdateTransform?: boolean): void + setObjectRenderer(objectRenderer: ObjectRenderer): void; + flush(): void; + resize(width: number, height: number): void; + setBlendMode(blendMode: number): void; + clear(clearColor?: number): void; + setTransform(matrix: Matrix): void; + bindRenderTexture(renderTexture: RenderTexture, transform: Transform): WebGLRenderer; + bindRenderTarget(renderTarget: RenderTarget): WebGLRenderer; + bindShader(shader: Shader): WebGLRenderer; + bindTexture(texture: Texture | BaseTexture, location?: number, forceLocation?: boolean): number; + unbindTexture(texture: Texture | BaseTexture): WebGLRenderer; + createVao(): glCore.VertexArrayObject; + bindVao(vao: glCore.VertexArrayObject): WebGLRenderer; + reset(): WebGLRenderer; + handleContextLost: (event: WebGLContextEvent) => void; + handleContextRestored: () => void; + destroy(removeView?: boolean): void; + + on(event: "context", fn: (gl: WebGLRenderingContext) => void, context?: any): utils.EventEmitter; + on(event: "prerender", fn: () => void, context?: any): utils.EventEmitter; + on(event: "postrender", fn: () => void, context?: any): utils.EventEmitter; + on(event: string, fn: Function, context?: any): utils.EventEmitter; + once(event: "context", fn: (gl: WebGLRenderingContext) => void, context?: any): utils.EventEmitter; + once(event: "prerender", fn: () => void, context?: any): utils.EventEmitter; + once(event: "postrender", fn: () => void, context?: any): utils.EventEmitter; + once(event: string, fn: Function, context?: any): utils.EventEmitter; + off(event: string, fn: Function, context?: any): utils.EventEmitter; + +} +export class WebGLState { + + constructor(gl: WebGLRenderingContext); + + activeState: number[]; + defaultState: number[]; + stackIndex: number; + stack: number[]; + gl: WebGLRenderingContext; + maxAttribs: number; + attribState: glCore.IAttribState; + nativeVaoExtension: any; + + push(): void; + pop(): void; + setState(state: number[]): void; + setBlend(value: number): void; + setBlendMode(value: number): void; + setDepthTest(value: number): void; + setCullFace(value: number): void; + setFrontFace(value: number): void; + resetAttributes(): void; + resetToDefault(): void; + +} +export class TextureManager { + + constructor(renderer: WebGLRenderer); + + renderer: WebGLRenderer; + gl: WebGLRenderingContext; + protected _managedTextures: WebGLTexture[]; + + bindTexture(): void; + getTexture(): WebGLTexture; + updateTexture(texture: BaseTexture | Texture): WebGLTexture; + destroyTexture(texture: BaseTexture, _skipRemove?: boolean): void; + removeAll(): void; + destroy(): void; + +} +export class TextureGarbageCollector { + + constructor(renderer: WebGLRenderer); + + renderer: WebGLRenderer; + count: number; + checkCount: number; + maxIdle: number; + checkCountMax: number; + mode: number; + + update(): void; + run(): void; + unload(): void; + +} +export abstract class ObjectRenderer extends WebGLManager { + + constructor(renderer: WebGLRenderer); + + start(): void; + stop(): void; + flush(): void; + + render(...args: any[]): void; + +} +export class Quad { + + constructor(gl: WebGLRenderingContext); + + gl: WebGLRenderingContext; + vertices: number[]; + uvs: number[]; + interleaved: number[]; + indices: number[]; + vertexBuffer: WebGLBuffer; + vao: glCore.VertexArrayObject; + initVao(shader: glCore.GLShader): void; + map(targetTextureFrame: Rectangle, destinationFrame: Rectangle): Quad; + upload(): Quad; + destroy(): void; + +} +export class RenderTarget { + + constructor(gl: WebGLRenderingContext, width: number, height: number, scaleMode: number, resolution: number, root?: boolean); + + gl: WebGLRenderingContext; + frameBuffer: glCore.GLFramebuffer; + texture: Texture; + clearColor: number[]; + size: Rectangle; + resolution: number; + projectionMatrix: Matrix; + transform: Matrix; + frame: Rectangle; + defaultFrame: Rectangle; + destinationFrame: Rectangle; + sourceFrame: Rectangle; + stencilBuffer: glCore.GLFramebuffer; + stencilMaskStack: Graphics[]; + filterData: { + index: number, + stack: Array<{ + renderTarget: RenderTarget, + filter: any[]; + bounds: Rectangle + }> + }; + scaleMode: number; + root: boolean; + + clear(clearColor?: number[]): void; + attachStencilBuffer(): void; + setFrame(destinationFrame: Rectangle, sourceFrame: Rectangle): void; + activate(): void; + calculateProjection(destinationFrame: Rectangle, sourceFrame: Rectangle): void; + resize(width: number, height: number): void; + destroy(): void; + +} + +export class BlendModeManager extends WebGLManager { + + constructor(renderer: WebGLRenderer); + + currentBlendMode: number; + + setBlendMode(blendMode: number): boolean; + +} +export class FilterManager extends WebGLManager { + + constructor(renderer: WebGLRenderer); + + gl: WebGLRenderingContext; + quad: Quad; + stack: Array<{ + renderTarget: RenderTarget; + sourceFrame: Rectangle; + destinationFrame: Rectangle; + filters: Filter[]; + target: any; + resolution: number; + }>; + stackIndex: number; + shaderCache: any; + filterData: any; + + pushFilter(target: RenderTarget, filters: Filter[]): void; + popFilter(): void; + applyFilter(shader: glCore.GLShader | Filter, inputTarget: RenderTarget, outputTarget: RenderTarget, clear?: boolean): void; + syncUniforms(shader: glCore.GLShader, filter: Filter): void; + getRenderTarget(clear?: boolean, resolution?: number): RenderTarget; + returnRenderTarget(renderTarget: RenderTarget): RenderTarget; + calculateScreenSpaceMatrix(outputMatrix: Matrix): Matrix; + calculateNormalisedScreenSpaceMatrix(outputMatrix: Matrix): Matrix; + calculateSpriteMatrix(outputMatrix: Matrix, sprite: Sprite): Matrix; + destroy(): void; + emptyPool(): void; + getPotRenderTarget(gl: WebGLRenderingContext, minWidth: number, minHeight: number, resolution: number): RenderTarget; + freePotRenderTarget(renderTarget: RenderTarget): void; + +} +export class StencilMaskStack { + + stencilStack: any[]; + reverse: boolean; + count: number; + +} +export class MaskManager extends WebGLManager { + + scissor: boolean; + scissorData: any; + scissorRenderTarget: RenderTarget; + enableScissor: boolean; + alphaMaskPool: number[]; + alphaMaskIndex: number; + pushMask(target: RenderTarget, maskData: Sprite | Graphics): void; + popMask(target: RenderTarget, maskData: Sprite | Graphics): void; + pushSpriteMask(target: RenderTarget, maskData: Sprite | Graphics): void; + popSpriteMask(): void; + pushStencilMask(maskData: Sprite | Graphics): void; + popStencilMask(): void; + pushScissorMask(target: RenderTarget, maskData: Sprite | Graphics): void; + popScissorMask(): void; + +} +export class StencilManager extends WebGLManager { + + constructor(renderer: WebGLRenderer); + + stencilMaskStack: Graphics[]; + + setMaskStack(stencilMasStack: Graphics[]): void; + pushStencil(graphics: Graphics): void; + popStencil(): void; + destroy(): void; + +} +export class WebGLManager { + + constructor(renderer: WebGLRenderer); + + renderer: WebGLRenderer; + onContextChange(): void; + destroy(): void; + +} +export interface IUniformData { + + type: string; + value: any; + + // name is set by pixi if uniforms were automatically extracted from shader code, but not used anywhere + name?: string; + +} +export class Filter { + + // param uniforms should be an object matching type {[name: string]: IUniformData}; + // left untyped as there's no way to define the type without requiring an index signature or making this class generic + constructor(vertexSrc?: string, fragmentSrc?: string, uniforms?: any); + + vertextSrc: string; + fragmentSrc: string; + protected uniformData: { [name: string]: IUniformData }; + uniforms: { [name: string]: any }; + glShaders: any; + glShaderKey: string; + padding: number; + resolution: number; + blendMode: number; + enabled: boolean; + apply(filterManager: FilterManager, input: RenderTarget, output: RenderTarget, clear?: boolean): void; + + static defaultVertexSrc: string; + static defaultFragmentSrc: string; + +} +export class SpriteMaskFilter extends Filter { + + constructor(sprite: Sprite); + + maskSprite: Sprite; + maskMatrix: Matrix; + apply(filterManager: FilterManager, input: RenderTarget, output: RenderTarget): void; + +} + +// sprites + +export class Sprite extends Container { + + constructor(texture?: Texture); + + protected _anchor: ObservablePoint; + anchor: ObservablePoint; + protected _texture: Texture; + protected _width: number; + protected _height: number; + tint: number; + protected _tint: number; + protected _tintRGB: number; + blendMode: number; + pluginName: string; + protected cachedTint: number; + texture: Texture; + protected textureDirty: boolean; + protected _textureID: number; + protected _transformID: number; + protected vertexTrimmedData: Float32Array; + vertexData: Float32Array; + width: number; + height: number; + + protected _onTextureUpdate(): void; + calculateVertices(): void; + protected _calculateBounds(): void; + protected calculateTrimmedVertices(): void; + protected onAnchorUpdate(): void; + protected _renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; + getLocalBounds(): Rectangle; + containsPoint(point: Point): boolean; + destroy(options?: IDestroyOptions | boolean): void; + + static from(source: number | string | BaseTexture | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement): Sprite; + static fromFrame(frameId: string): Sprite; + static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; + +} +export class BatchBuffer { + + vertices: ArrayBuffer; + float32View: number[]; + uint32View: number[]; + + destroy(): void; + +} +export class SpriteRenderer extends ObjectRenderer { + + constructor(renderer: PIXI.WebGLRenderer); + + vertSize: number; + vertByteSize: number; + size: number; + buffers: BatchBuffer[]; + indices: number[]; + shaders: Shader[]; + currentIndex: number; + tick: number; + groups: any[]; + sprites: Sprite[]; + vertexBuffers: number[]; + vaos: glCore.VertexArrayObject[]; + vaoMax: number; + vertexCount: number; + + protected onContextChanged: () => void; + protected onPrerender: () => void; + render(sprite: Sprite): void; + flush(): void; + start(): void; + stop(): void; + destroy(): void; + +} +export class CanvasSpriteRenderer extends ObjectRenderer { + + constructor(renderer: WebGLRenderer); + + render(sprite: Sprite): void; + destroy(): void; + +} +export namespace CanvasTinter { + + export function getTintedTexture(sprite: Sprite, color: number): HTMLCanvasElement; + export function tintWithMultiply(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + export function tintWithOverlay(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + export function tintWithPerPixel(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + export function roundColor(color: number): number; + + export var cacheStepsPerColorChannel: number; + export var convertTintToImage: boolean; + export var canUseMultiply: boolean; + export var tintMethod: Function; + +} + +// text +export interface TextStyleOptions { + align?: string; + breakWords?: boolean; + dropShadow?: boolean; + dropShadowAngle?: number; + dropShadowBlur?: number; + dropShadowColor?: string | number; + dropShadowDistance?: number; + fill?: string | string[] | number | number[] | CanvasGradient | CanvasPattern; + fillGradientType?: number; + fontFamily?: string; + fontSize?: number | string; + fontStyle?: string; + fontVariant?: string; + fontWeight?: string; + letterSpacing?: number; + lineHeight?: number; + lineJoin?: string; + miterLimit?: number; + padding?: number; + stroke?: string | number; + strokeThickness?: number; + styleID?: number; + textBaseline?: string; + wordWrap?: boolean; + wordWrapWidth?: number; +} + +export class TextStyle implements TextStyleOptions { + align: string; + breakWords: boolean; + dropShadow: boolean; + dropShadowAngle: number; + dropShadowBlur: number; + dropShadowColor: string | number; + dropShadowDistance: number; + fill: string | string[] | number | number[] | CanvasGradient | CanvasPattern; + fillGradientType: number; + fontFamily: string; + fontSize: number | string; + fontStyle: string; + fontVariant: string; + fontWeight: string; + letterSpacing: number; + lineHeight: number; + lineJoin: string; + miterLimit: number; + padding: number; + stroke: string | number; + strokeThickness: number; + styleID: number; + textBaseline: string; + wordWrap: boolean; + wordWrapWidth: number; + constructor(style?: TextStyleOptions); + clone(): TextStyle; + reset(): void; +} + +export class Text extends Sprite { + + static getFontStyle(style: TextStyleOptions): string; + static calculateFontProperties(style: string): any; + + constructor(text?: string, style?: TextStyleOptions); + + canvas: HTMLCanvasElement; + context: CanvasRenderingContext2D; + resolution: number; + protected _text: string; + protected _style: TextStyle; + protected _styleListener: Function; + protected _font: string; + protected localStyleID: number; + + static fontPropertiesCache: any; + static fontPropertiesCanvas: HTMLCanvasElement; + static fontPropertiesContext: CanvasRenderingContext2D; + + width: number; + height: number; + style: TextStyle; + text: string; + + protected updateText(respectDirty?: boolean): void; + protected drawLetterSpacing(text: string, x: number, y: number, isStroke?: boolean): void; + protected updateTexture(): void; + renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; + protected wordWrap(text: string): string; + protected _calculateBounds(): void; + protected _onStyleChange: () => void; + protected _generateFillStyle(style: TextStyle, lines: string[]): string | number | CanvasGradient; + destroy(options?: IDestroyOptions | boolean): void; + dirty: boolean; + +} + +// textures + +export class BaseRenderTexture extends BaseTexture { + + constructor(width?: number, height?: number, scaleMode?: number, resolution?: number); + + height: number; + width: number; + realHeight: number; + realWidth: number; + resolution: number; + scaleMode: number; + hasLoaded: boolean; + protected _glRenderTargets: { [n: number]: WebGLTexture; }; + protected _canvasRenderTarget: { [n: number]: WebGLTexture; }; + valid: boolean; + + resize(width: number, height: number): void; + destroy(): void; + + once(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): utils.EventEmitter; + once(event: string, fn: Function, context?: any): utils.EventEmitter; + on(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): utils.EventEmitter; + on(event: string, fn: Function, context?: any): utils.EventEmitter; + off(event: string, fn: Function, context?: any): utils.EventEmitter; + +} +export class BaseTexture extends utils.EventEmitter { + + constructor(source?: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, scaleMode?: number, resolution?: number); + + protected uuid: number; + protected touched: number; + resolution: number; + width: number; + height: number; + realWidth: number; + realHeight: number; + scaleMode: number; + hasLoaded: boolean; + isLoading: boolean; + wrapMode: number; + source: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement; + origSource: HTMLImageElement; + imageType: string; + sourceScale: number; + premultipliedAlpha: boolean; + imageUrl: string; + protected isPowerOfTwo: boolean; + mipmap: boolean; + wrap: boolean; + protected _glTextures: any; + protected _enabled: number; + protected _id: number; + + update(): void; + protected _updateImageType(): void; + protected _loadSvgSource(): void; + protected _loadSvgSourceUsingDataUri(dataUri: string): void; + protected _loadSvgSourceUsingXhr(): void; + protected _loadSvgSourceUsingString(svgString: string): void; + protected loadSource(source: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement): void; + protected _sourceLoaded(): void; + destroy(): void; + dispose(): void; + updateSourceImage(newSrc: string): void; + + static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: number, sourceScale?: number): BaseTexture; + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): BaseTexture; + + on(event: "update", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; + on(event: "loaded", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; + on(event: "error", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; + on(event: "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; + on(event: string, fn: Function, context?: any): utils.EventEmitter; + once(event: "update", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; + once(event: "loaded", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; + once(event: "error", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; + once(event: "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; + once(event: string, fn: Function, context?: any): utils.EventEmitter; + off(event: string, fn: Function, context?: any): utils.EventEmitter; + +} +export class RenderTexture extends Texture { + + constructor(baseRenderTexture: BaseRenderTexture, frame?: Rectangle); + + protected legacyRenderer: any; + valid: boolean; + + resize(width: number, height: number, doNotResizeBaseTexture?: boolean): void; + + static create(width?: number, height?: number, scaleMode?: number, resolution?: number): RenderTexture; + +} +export class Texture extends utils.EventEmitter { + + constructor(baseTexture: BaseTexture, frame?: Rectangle, orig?: Rectangle, trim?: Rectangle, rotate?: number); + + noFrame: boolean; + baseTexture: BaseTexture; + protected _frame: Rectangle; + trim: Rectangle; + valid: boolean; + requiresUpdate: boolean; + protected _uvs: TextureUvs; + orig: Rectangle; + protected _updateID: number; + transform: any; + + update(): void; + protected onBaseTextureLoaded(baseTexture: BaseTexture): void; + protected onBaseTextureUpdated(baseTexture: BaseTexture): void; + destroy(destroyBase?: boolean): void; + clone(): Texture; + protected _updateUvs(): void; + + static fromImage(imageUrl: string, crossOrigin?: boolean, scaleMode?: number, sourceScale?: number): Texture; + static fromFrame(frameId: string): Texture; + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): Texture; + static fromVideo(video: HTMLVideoElement | string, scaleMode?: number): Texture; + static fromVideoUrl(videoUrl: string, scaleMode?: number): Texture; + static from(source: number | string | BaseTexture | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement): Texture; + static addTextureToCache(texture: Texture, id: string): void; + static removeTextureFromCache(id: string): Texture; + + frame: Rectangle; + protected _rotate: boolean; + rotate: number; + width: number; + height: number; + + static EMPTY: Texture; + + on(event: "update", fn: (texture: Texture) => void, context?: any): utils.EventEmitter; + on(event: string, fn: Function, context?: any): utils.EventEmitter; + once(event: "update", fn: (texture: Texture) => void, context?: any): utils.EventEmitter; + once(event: string, fn: Function, context?: any): utils.EventEmitter; + off(event: string, fn: Function, context?: any): utils.EventEmitter; + +} +export class TextureUvs { + + x0: number; + y0: number; + x1: number; + y1: number; + x2: number; + y2: number; + x3: number; + y3: number; + + uvsUint32: Uint32Array; + + protected set(frame: Rectangle, baseFrame: Rectangle, rotate: number): void; + +} +export class VideoBaseTexture extends BaseTexture { + + constructor(source: HTMLVideoElement, scaleMode?: number); + + autoUpdate: boolean; + autoPlay: boolean; + protected _isAutoUpdating: boolean; + + update(): void; + protected _onCanPlay(): void; + protected _onPlayStart(): void; + protected _onPlayStop(): void; + destroy(): void; + protected _isSourcePlaying(): boolean; + protected _isSourceReady(): boolean; + + static fromVideo(video: HTMLVideoElement, scaleMode?: number): VideoBaseTexture; + static fromUrl(videoSrc: string | any | string[] | any[]): VideoBaseTexture; + static fromUrls(videoSrc: string | any | string[] | any[]): VideoBaseTexture; + + source: HTMLVideoElement; + protected loadSource(source: HTMLVideoElement): void; +} + +// ticker + +export namespace ticker { + + export var shared: Ticker; + + export class Ticker { + + protected _tick(time: number): void; + protected _emitter: utils.EventEmitter; + protected _requestId: number; + protected _maxElapsedMS: number; + + protected _requestIfNeeded(): void; + protected _cancelIfNeeded(): void; + protected _startIfPossible(): void; + + autoStart: boolean; + deltaTime: number; + elapsedMS: number; + lastTime: number; + speed: number; + started: boolean; + + FPS: number; + minFPS: number; + + add(fn: (deltaTime: number) => void, context?: any): Ticker; + addOnce(fn: (deltaTime: number) => void, context?: any): Ticker; + remove(fn: (deltaTime: number) => void, context?: any): Ticker; + start(): void; + stop(): void; + update(): void; + + } + +} + +// shader + +export class Shader extends glCore.GLShader { } + +////////////////////////////////////////////////////////////////////////////// +////////////////////////////EXTRACT/////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +export namespace extract { + + export class CanvasExtract { + + protected renderer: CanvasRenderer; + + constructor(renderer: CanvasRenderer); + + image(target?: DisplayObject | RenderTexture): HTMLImageElement; + base64(target?: DisplayObject | RenderTexture): string; + canvas(target?: DisplayObject | RenderTexture): HTMLCanvasElement; + pixels(renderTexture?: DisplayObject | RenderTexture): number[]; + + destroy(): void; + + } + export class WebGLExtract { + protected renderer: WebGLRenderer; + + constructor(renderer: WebGLRenderer); + + image(target?: DisplayObject | RenderTexture): HTMLImageElement; + base64(target?: DisplayObject | RenderTexture): string; + canvas(target?: DisplayObject | RenderTexture): HTMLCanvasElement; + pixels(renderTexture?: DisplayObject | RenderTexture): number[]; + + destroy(): void; + } + +} + +////////////////////////////////////////////////////////////////////////////// +////////////////////////////EXTRAS//////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +export namespace extras { + + export interface IBitmapTextStyle { + + font?: string | { + + name?: string; + size?: number; + + }; + align?: string; + tint?: number; + + } + export class BitmapText extends Container { + + constructor(text: string, style?: IBitmapTextStyle); + + textWidth: number; + textHeight: number; + protected _glyphs: Sprite[]; + protected _font: string | { + name?: string; + size?: number; + }; + font: string | { + name?: string; + size?: number; + }; + protected _text: string; + maxWidth: number; + maxLineHeight: number; + dirty: boolean; + tint: number; + align: string; + text: string; + anchor: PIXI.Point | number; + + protected updateText(): void; + updateTransform(): void; + getLocalBounds(): Rectangle; + validate(): void; + + static fonts: any; + + } + export class AnimatedSprite extends Sprite { + + constructor(textures: Texture[] | Array<{ texture: Texture, time?: number }>); + + protected _textures: Texture[]; + protected _durations: number[]; + textures: Texture[] | Array<{ texture: Texture, time?: number }>; + animationSpeed: number; + loop: boolean; + onComplete: () => void; + onFrameChange: (currentFrame: number) => void; + protected _currentTime: number; + playing: boolean; + totalFrames: number; + currentFrame: number; + stop(): void; + play(): void; + gotoAndStop(frameNumber: number): void; + gotoAndPlay(frameNumber: number): void; + protected update(deltaTime: number): void; + destroy(): void; + + static fromFrames(frame: string[]): AnimatedSprite; + static fromImages(images: string[]): AnimatedSprite; + + } + export class TextureTransform { + + constructor(texture: Texture, clampMargin?: number); + + protected _texture: Texture; + protected mapCoord: Matrix; + protected uClampFrame: Float32Array; + protected uClampOffset: Float32Array; + protected _lastTextureID: number; + + clampOffset: number; + clampMargin: number; + + texture: Texture; + + update(forceUpdate?: boolean): void; + + } + export class TilingSprite extends Sprite { + + constructor(texture: Texture, width?: number, height?: number); + + tileTransform: TransformStatic; + protected _width: number; + protected _height: number; + protected _canvasPattern: CanvasPattern; + uvTransform: TextureTransform; + + clampMargin: number; + tileScale: Point | ObservablePoint; + tilePosition: Point | ObservablePoint; + + protected _onTextureUpdate(): void; + protected _renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; + protected _calculateBounds(): void; + getLocalBounds(rect?: Rectangle): Rectangle; + containsPoint(point: Point): boolean; + destroy(): void; + + static from(source: number | string | BaseTexture | HTMLCanvasElement | HTMLVideoElement, width?: number, height?: number): TilingSprite; + static fromFrame(frameId: string, width?: number, height?: number): TilingSprite; + // if you remove the next line, the class will break. https://github.com/pixijs/pixi-typescript/issues/96 + static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; + static fromImage(imageId: string, width?: number, height?: number, crossorigin?: boolean, scaleMode?: number): TilingSprite; + + width: number; + height: number; + + } + export class TilingSpriteRenderer extends ObjectRenderer { + + constructor(renderer: WebGLRenderer); + + render(ts: TilingSprite): void; + + } + +} + +////////////////////////////////////////////////////////////////////////////// +////////////////////////////FILTERS/////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +export namespace filters { + + export class FXAAFilter extends Filter { } + export class BlurFilter extends Filter { + + constructor(strength?: number, quality?: number, resolution?: number, kernelSize?: number); + + blurXFilter: BlurXFilter; + blurYFilter: BlurYFilter; + resolution: number; + padding: number; + passes: number; + blur: number; + blurX: number; + blurY: number; + quality: number; + + } + export class BlurXFilter extends Filter { + + constructor(strength?: number, quality?: number, resolution?: number, kernelSize?: number); + + protected _quality: number; + + quality: number; + passes: number; + resolution: number; + strength: number; + firstRun: boolean; + blur: number; + + } + export class BlurYFilter extends Filter { + + constructor(strength?: number, quality?: number, resolution?: number, kernelSize?: number); + + protected _quality: number; + + quality: number; + passes: number; + resolution: number; + strength: number; + firstRun: boolean; + blur: number; + + } + export class ColorMatrixFilter extends Filter { + + constructor(); + + protected _loadMatrix(matrix: number[], multiply?: boolean): void; + protected _multiply(out: number[], a: number[], b: number[]): void; + protected _colorMatrix(matrix: number[]): void; + + matrix: number[]; + + brightness(b: number, multiply?: boolean): void; + greyscale(scale: number, multiply?: boolean): void; + blackAndWhite(multiply?: boolean): void; + hue(rotation: number, multiply?: boolean): void; + contrast(amount: number, multiply?: boolean): void; + saturate(amount: number, multiply?: boolean): void; + desaturate(multiply?: boolean): void; + negative(multiply?: boolean): void; + sepia(multiply?: boolean): void; + technicolor(multiply?: boolean): void; + polaroid(multiply?: boolean): void; + toBGR(multiply?: boolean): void; + kodachrome(multiply?: boolean): void; + browni(multiply?: boolean): void; + vintage(multiply?: boolean): void; + colorTone(desaturation: number, toned: number, lightColor: string, darkColor: string, multiply?: boolean): void; + night(intensity: number, multiply?: boolean): void; + predator(amount: number, multiply?: boolean): void; + lsd(multiply?: boolean): void; + reset(): void; + + } + export class DisplacementFilter extends Filter { + + constructor(sprite: Sprite, scale?: number); + + scale: Point; + map: Texture; + + } + export class VoidFilter extends Filter { + glShaderKey: string; + } + + // pixi-filters.d.ts todo + // https://github.com/pixijs/pixi-filters/ + export class NoiseFilter extends Filter { + + noise: number; + + } + +} + +////////////////////////////////////////////////////////////////////////////// +////////////////////////////INTERACTION/////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +export namespace interaction { + + export interface InteractionEvent { + + stopped: boolean; + target: DisplayObject; + currentTarget: DisplayObject; + type: string; + data: InteractionData; + stopPropagation(): void; + + } + export class InteractionData { + + global: Point; + + protected _target: DisplayObject; + target: DisplayObject; + targetProxy: DisplayObject; + originalEvent: Event; + + getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; + + } + export class InteractionManager extends utils.EventEmitter { + + constructor(renderer: SystemRenderer, options?: { autoPreventDefault?: boolean; interactionFrequency?: number; }); + + renderer: SystemRenderer; + autoPreventDefault: boolean; + interactionFrequency: number; + mouse: InteractionData; + pointer: InteractionData; + eventData: { + stopped: boolean; + target: any; + type: any; + data: InteractionData; + stopPropagination(): void; + }; + interactiveDataPool: InteractionData[]; + protected interactionDOMElement: HTMLElement; + protected moveWhenInside: boolean; + protected eventsAdded: boolean; + mouseOverRenderer: boolean; + supportsTouchEvents: boolean; + supportsPointerEvents: boolean; + normalizeTouchEvents: boolean; + normalizeMouseEvents: boolean; + + protected onMouseUp: (event: MouseEvent) => void; + protected processMouseUp: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseDown: (event: MouseEvent) => void; + protected processMouseDown: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseMove: (event: MouseEvent) => void; + protected processMouseMove: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseOut: (event: MouseEvent) => void; + protected processMouseOverOut: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseOver: (event: MouseEvent) => void; + + protected onPointerUp: (event: PointerEvent) => void; + protected processPointerUp: (displayObject: DisplayObject, hit: boolean) => void; + protected onPointerDown: (event: PointerEvent) => void; + protected processPointerDown: (displayObject: DisplayObject, hit: boolean) => void; + protected onPointerMove: (event: PointerEvent) => void; + protected processPointerMove: (displayObject: DisplayObject, hit: boolean) => void; + protected onPointerOut: (event: PointerEvent) => void; + protected processPointerOut: (displayObject: DisplayObject, hit: boolean) => void; + protected onPointerOver: (event: PointerEvent) => void; + + protected onTouchStart: (event: TouchEvent) => void; + protected processTouchStart: (DisplayObject: DisplayObject, hit: boolean) => void; + protected onTouchEnd: (event: TouchEvent) => void; + protected processTouchEnd: (displayObject: DisplayObject, hit: boolean) => void; + protected onTouchMove: (event: TouchEvent) => void; + protected processTouchMove: (displayObject: DisplayObject, hit: boolean) => void; + defaultCursorStyle: string; + currentCursorStyle: string; + protected _tempPoint: Point; + resolution: number; + protected setTargetElement(element: HTMLElement, resolution: number): void; + protected addEvents(): void; + protected removeEvents(): void; + update(deltaTime: number): void; + protected dispatchEvent(displayObject: DisplayObject, eventString: string, eventData: any): void; + mapPositionToPoint(point: Point, x: number, y: number): void; + protected processInteractive(point: Point, displayObject: DisplayObject, func: (displayObject: DisplayObject, hit: boolean) => void, hitTest: boolean, interactive: boolean): boolean; + protected _startInteractionProcess(): void; + protected _queueAdd(displayObject: DisplayObject, order: number): void; + protected _finishInteractionProcess(func: Function): void; + protected getTouchData(touchEvent: InteractionData): InteractionData; + protected returnTouchData(touchData: InteractionData): void; + protected normalizeToPointerData(Event: Event): void; + + destroy(): void; + + } + export interface InteractiveTarget { + + interactive: boolean; + interactiveChildren: boolean; + hitArea: IHitArea; + buttonMode: boolean; + defaultCursor: string; + + } + export interface InteractiveTargetProxy extends InteractiveTarget { + } + +} + +////////////////////////////////////////////////////////////////////////////// +///////////////////////////////LOADER///////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +// extends +// https://github.com/englercj/resource-loader/ +// 1.6.4 + +export namespace loaders { + + export interface ILoaderOptions { + + crossOrigin?: boolean | string; + loadType?: number; + xhrType?: string; + metaData?: any; + + } + export interface IResourceDictionary { + + [index: string]: PIXI.loaders.Resource; + + } + export class Loader extends utils.EventEmitter { + + protected static _pixiMiddleware: Function[]; + static addPixiMiddleware(fn: Function): void; + + constructor(baseUrl?: string, concurrency?: number); + + baseUrl: string; + progress: number; + loading: boolean; + resources: IResourceDictionary; + + add(name: string, url: string, options?: ILoaderOptions, cb?: () => void): Loader; + add(url: string, options?: ILoaderOptions, cb?: () => void): Loader; + // todo I am not sure of object literal notional (or its options) so just allowing any but would love to improve this + add(obj: any, options?: ILoaderOptions, cb?: () => void): Loader; + + on(event: "complete", fn: (loader: loaders.Loader, object: any) => void, context?: any): utils.EventEmitter; + on(event: "error", fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; + on(event: "load", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; + on(event: "progress", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; + on(event: "start", fn: (loader: loaders.Loader) => void, context?: any): utils.EventEmitter; + on(event: string, fn: Function, context?: any): utils.EventEmitter; + + once(event: "complete", fn: (loader: loaders.Loader, object: any) => void, context?: any): utils.EventEmitter; + once(event: "error", fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; + once(event: "load", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; + once(event: "progress", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; + once(event: "start", fn: (loader: loaders.Loader) => void, context?: any): utils.EventEmitter; + once(event: string, fn: Function, context?: any): utils.EventEmitter; + + before(fn: Function): Loader; + pre(fn: Function): Loader; + + after(fn: Function): Loader; + use(fn: Function): Loader; + + reset(): void; + + load(cb?: (loader: loaders.Loader, object: any) => void): Loader; + + } + export interface ITextureDictionary { + [index: string]: PIXI.Texture; + } + + export class Resource extends utils.EventEmitter { + + static LOAD_TYPE: { + XHR: number; + IMAGE: number; + AUDIO: number; + VIDEO: number; + }; + + static XHR_READ_STATE: { + UNSENT: number; + OPENED: number; + HEADERS_RECIEVED: number; + LOADING: number; + DONE: number; + }; + + static XHR_RESPONSE_TYPE: { + DEFAULT: number; + BUFFER: number; + BLOB: number; + DOCUMENT: number; + JSON: number; + TEXT: number; + }; + + constructor(name?: string, url?: string | string[], options?: ILoaderOptions); + + protected _loadSourceElement(type: string): void; + isLoading: boolean; + isComplete: boolean; + + isJson: boolean; + isXml: boolean; + isImage: boolean; + isAudio: boolean; + isVideo: boolean; + + name: string; + texture: Texture; + textures: ITextureDictionary; + url: string; + data: any; + crossOrigin: boolean | string; + loadType: number; + xhrType: string; + error: Error; + xhr: XMLHttpRequest; + SVGMetadataElement: any; + + metadata: any; + spineAtlas: any; + spineData: any; + + complete(): void; + load(cb?: () => void): void; + abort(message: string): void; + + } +} + +////////////////////////////////////////////////////////////////////////////// +///////////////////////////////MESH/////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +export namespace mesh { + + export class Mesh extends Container { + + constructor(texture: Texture, vertices?: Float32Array, uvs?: Float32Array, indices?: Uint16Array, drawMode?: number); + + protected _texture: Texture; + uvs: Float32Array; + vertices: Float32Array; + indices: Uint16Array; + dirty: number; + indexDirty: number; + dirtyVertex: boolean; + protected _geometryVersion: number; + blendMode: number; + pluginName: string; + canvasPadding: number; + drawMode: number; + texture: Texture; + tintRgb: Float32Array; + protected _glDatas: { [n: number]: any; }; + protected _renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; + protected _onTextureUpdate(): void; + protected _calculateBounds(): void; + containsPoint(point: Point): boolean; + tint: number; + + static DRAW_MODES: { + TRIANGLE_MESH: number; + TRIANGLES: number; + }; + + } + + export class CanvasMeshRenderer { + + constructor(renderer: CanvasRenderer); + + renderer: CanvasRenderer; + + render(mesh: Mesh): void; + protected _renderTriangleMesh(mesh: Mesh): void; + protected _renderTriangles(mesh: Mesh): void; + protected _renderDrawTriangle(mesh: Mesh, index0: number, index1: number, index2: number): void; + protected renderMeshFlat(mesh: Mesh): void; + + destroy(): void; + + } + + export class MeshRenderer extends ObjectRenderer { + + constructor(renderer: WebGLRenderer); + + shader: Shader; + render(mesh: Mesh): void; + + } + + export class Plane extends Mesh { + + constructor(texture: Texture, verticesX?: number, verticesY?: number); + protected _ready: boolean; + verticesX: number; + verticesY: number; + drawMode: number; + + refresh(): void; + + protected _onTexureUpdate(): void; + + } + + export class NineSlicePlane extends Plane { + + constructor(texture: Texture, leftWidth?: number, topHeight?: number, rightWidth?: number, bottomHeight?: number); + + width: number; + height: number; + leftWidth: number; + rightWidth: number; + topHeight: number; + bottomHeight: number; + + protected _leftWidth: number; + protected _rightWidth: number; + protected _topHeight: number; + protected _bottomHeight: number; + protected _height: number; + protected _width: number; + protected _origHeight: number; + protected _origWidth: number; + protected _uvh: number; + protected _uvw: number; + + updateHorizontalVertices(): void; + updateVerticalVertices(): void; + protected drawSegment(context: CanvasRenderingContext2D | WebGLRenderingContext, textureSource: any, w: number, h: number, x1: number, y1: number, x2: number, y2: number): void; + + } + + export class Rope extends Mesh { + + constructor(texture: Texture, points: Point[]); + + points: Point[]; + colors: number[]; + protected _ready: boolean; + refresh(): void; + + protected _onTextureUpdate(): void; + updateTransform(): void; + + } +} + +////////////////////////////////////////////////////////////////////////////// +/////////////////////////////PARTICLES//////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +export namespace particles { + + export interface IParticleContainerProperties { + + scale?: boolean; + position?: boolean; + rotation?: boolean; + uvs?: boolean; + alpha?: boolean; + + } + export class ParticleContainer extends Container { + + constructor(size?: number, properties?: IParticleContainerProperties, batchSize?: number); + + protected _properties: boolean[]; + protected _maxSize: number; + protected _batchSize: number; + protected _glBuffers: { [n: number]: WebGLBuffer; }; + protected _bufferToUpdate: number; + interactiveChildren: boolean; + blendMode: number; + roundPixels: boolean; + baseTexture: BaseTexture; + + setProperties(properties: IParticleContainerProperties): void; + protected onChildrenChange: (smallestChildIndex?: number) => void; + + destroy(options?: IDestroyOptions | boolean): void; + + } + export class ParticleBuffer { + + constructor(gl: WebGLRenderingContext, properties: any, dynamicPropertyFlags: any[], size: number); + + gl: WebGLRenderingContext; + vertSize: number; + vertByteSize: number; + size: number; + dynamicProperties: any[]; + staticProperties: any[]; + staticStride: number; + staticBuffer: any; + staticData: any; + dynamicStride: number; + dynamicBuffer: any; + dynamicData: any; + + destroy(): void; + + } + export interface IParticleRendererProperty { + attribute: number; + size: number; + uploadFunction: (children: PIXI.DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number) => void; + offset: number; + } + export class ParticleRenderer extends ObjectRenderer { + + constructor(renderer: WebGLRenderer); + + shader: glCore.GLShader; + indexBuffer: WebGLBuffer; + properties: IParticleRendererProperty[]; + protected tempMatrix: Matrix; + + start(): void; + generateBuffers(container: ParticleContainer): ParticleBuffer[]; + uploadVertices(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; + uploadPosition(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; + uploadRotation(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; + uploadUvs(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; + uploadAlpha(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; + destroy(): void; + + indices: Uint16Array; + + } + export interface IParticleShader extends glCore.GLShader { } + +} + +////////////////////////////////////////////////////////////////////////////// +////////////////////////////PREPARE/////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +export namespace prepare { + + type addHook = (item: any, queue: any[]) => boolean; + type uploadHook = (prepare: UploadHookSource, item: any) => boolean; + export abstract class BasePrepare{ + + constructor(renderer: SystemRenderer); + + limiter: CountLimiter | TimeLimiter; + protected renderer: SystemRenderer; + protected uploadHookHelper: UploadHookSource; + protected queue: any[]; + protected addHooks: addHook[]; + protected uploadHooks: Array>; + protected completes: Function[]; + protected ticking: boolean; + protected delayedTick: () => void; + + upload(item: Function | DisplayObject | BaseTexture | TextStyle | any, done?: () => void): void; + protected tick(): void; + protected prepareItems(): void; + register(addHook?: addHook, uploadHook?: uploadHook): this; + add(item: DisplayObject | any): this; + destroy(): void; + + } + export class CanvasPrepare extends BasePrepare { + + constructor(renderer: CanvasRenderer); + + protected canvas: HTMLCanvasElement; + protected ctx: CanvasRenderingContext2D; + + } + export class WebGLPrepare extends BasePrepare { + + constructor(renderer: WebGLRenderer); + + } + export class CountLimiter { + + constructor(maxItemsPerFrame: number); + + protected maxItemsPerFrame: number; + protected itemsLeft: number; + + } + export class TimeLimiter { + + constructor(maxMilliseconds: number); + + protected maxMilliseconds: number; + protected frameStart: number; + + } + +} + +////////////////////////////////////////////////////////////////////////////// +/////////////////////////////pixi-gl-core///////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +// pixi-gl-core https://github.com/pixijs/pixi-gl-core +// sharedArrayBuffer as a type is not available yet. +// need to fully define what an `Attrib` is. +export namespace glCore { + + export interface IContextOptions { + /** + * Boolean that indicates if the canvas contains an alpha buffer. + */ + alpha?: boolean; + /** + * Boolean that indicates that the drawing buffer has a depth buffer of at least 16 bits. + */ + depth?: boolean; + /** + * Boolean that indicates that the drawing buffer has a stencil buffer of at least 8 bits. + */ + stencil?: boolean; + /** + * Boolean that indicates whether or not to perform anti-aliasing. + */ + antialias?: boolean; + /** + * Boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. + */ + premultipliedAlpha?: boolean; + /** + * If the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author. + */ + preserveDrawingBuffer?: boolean; + /** + * Boolean that indicates if a context will be created if the system performance is low. + */ + failIfMajorPerformanceCaveat?: boolean; + } + export function createContext(view: HTMLCanvasElement, options?: IContextOptions): WebGLRenderingContext; + export function setVertexAttribArrays(gl: WebGLRenderingContext, attribs: IAttrib[], state?: WebGLState): WebGLRenderingContext; + export class GLBuffer { + + static EMPTY_ARRAY_BUFFER: ArrayBuffer; + + constructor(gl: WebGLRenderingContext, type: number, data: ArrayBuffer | ArrayBufferView | any, drawType: number); + + protected _updateID: number; + gl: WebGLRenderingContext; + buffer: WebGLBuffer; + type: number; + drawType: number; + data: ArrayBuffer | ArrayBufferView | any; + + upload(data: ArrayBuffer | ArrayBufferView | any, offset?: number, dontBind?: boolean): void; + bind(): void; + + static createVertexBuffer(gl: WebGLRenderingContext, data: ArrayBuffer | ArrayBufferView | any, drawType: number): GLBuffer; + static createIndexBuffer(gl: WebGLRenderingContext, data: ArrayBuffer | ArrayBufferView | any, drawType: number): GLBuffer; + static create(gl: WebGLRenderingContext, type: number, data: ArrayBuffer | ArrayBufferView | any, drawType: number): GLBuffer; + + destroy(): void; + + } + export class GLFramebuffer { + + constructor(gl: WebGLRenderingContext, width: number, height: number); + + gl: WebGLRenderingContext; + frameBuffer: WebGLFramebuffer; + stencil: WebGLRenderbuffer; + texture: GLTexture; + width: number; + height: number; + + enableTexture(texture: GLTexture): void; + enableStencil(): void; + clear(r: number, g: number, b: number, a: number): void; + bind(): void; + unbind(): void; + resize(width: number, height: number): void; + destroy(): void; + + static createRGBA(gl: WebGLRenderingContext, width: number, height: number, data: ArrayBuffer | ArrayBufferView | any): GLFramebuffer; + static createFloat32(gl: WebGLRenderingContext, width: number, height: number, data: ArrayBuffer | ArrayBufferView | any): GLFramebuffer; + + } + export class GLShader { + + constructor(gl: WebGLRenderingContext, vertexSrc: string | string[], fragmentSrc: string | string[]); + + gl: WebGLRenderingContext; + program: WebGLProgram; + uniforms: any; + attributes: any; + + bind(): void; + destroy(): void; + + } + export class GLTexture { + + constructor(gl: WebGLRenderingContext, width?: number, height?: number, format?: number, type?: number); + + gl: WebGLRenderingContext; + texture: WebGLTexture; + mipmap: boolean; + premultiplyAlpha: boolean; + width: number; + height: number; + format: number; + type: number; + + upload(source: HTMLImageElement | ImageData | HTMLVideoElement | HTMLCanvasElement): void; + uploadData(data: number, width: number, height: number): void; + bind(location?: number): void; + unbind(): void; + minFilter(linear: boolean): void; + magFilter(linear: boolean): void; + enableMipmap(): void; + enableLinearScaling(): void; + enableNearestScaling(): void; + enableWrapClamp(): void; + enableWrapRepeat(): void; + enableWrapMirrorRepeat(): void; + destroy(): void; + + static fromSource(gl: WebGLRenderingContext, source: HTMLImageElement | ImageData | HTMLVideoElement | HTMLCanvasElement, premultipleAlpha?: boolean): GLTexture; + static fromData(gl: WebGLRenderingContext, data: number[], width: number, height: number): GLTexture; + + } + export interface IAttrib { + + attribute: { + location: boolean; + size: number; + }; + normalized: boolean; + stride: number; + start: number; + buffer: ArrayBuffer; + + } + export interface IWebGLRenderingContextAttribute { + + buffer: WebGLBuffer; + attribute: any; + type: number; + normalized: boolean; + stride: number; + start: number; + + } + export interface IAttribState { + tempAttribState: IAttrib[]; + attribState: IAttrib[]; + } + + export class VertexArrayObject { + + static FORCE_NATIVE: boolean; + + constructor(gl: WebGLRenderingContext, state: WebGLState); + + protected nativeVaoExtension: any; + protected nativeState: IAttribState; + protected nativeVao: VertexArrayObject; + gl: WebGLRenderingContext; + attributes: IAttrib[]; + indexBuffer: GLBuffer; + dirty: boolean; + + bind(): VertexArrayObject; + unbind(): VertexArrayObject; + activate(): VertexArrayObject; + addAttribute(buffer: GLBuffer, attribute: IAttrib, type: number, normalized: boolean, stride: number, start: number): VertexArrayObject; + addIndex(buffer: GLBuffer, options?: any): VertexArrayObject; + clear(): VertexArrayObject; + draw(type: number, size: number, start: number): VertexArrayObject; + destroy(): void; + + } + +} + +////////////////////////////////////////////////////////////////////////////// +///////////////////////////////UTILS////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +export interface IDecomposedDataUri { + mediaType: string; + subType: string; + encoding: string; + data: any; +} + +export namespace utils { + + export function uid(): number; + export function hex2rgb(hex: number, out?: number[]): number[]; + export function hex2string(hex: number): string; + export function rgb2hex(rgb: Number[]): number; + export function canUseNewCanvasBlendModes(): boolean; + export function getResolutionOfUrl(url: string, defaultValue?: number): number; + export function getSvgSize(svgString: string): any; + export function decomposeDataUri(dataUri: string): IDecomposedDataUri; + export function getUrlFileExtension(url: string): string; + export function sayHello(type: string): void; + export function skipHello(): void; + export function isWebGLSupported(): boolean; + export function sign(n: number): number; + export function removeItems(arr: T[], startIdx: number, removeCount: number): void; + export var TextureCache: any; + export var BaseTextureCache: any; + + // https://github.com/kaimallea/isMobile + export namespace isMobile { + export var apple: { + phone: boolean; + ipod: boolean; + tablet: boolean; + device: boolean; + }; + export var android: { + phone: boolean; + tablet: boolean; + device: boolean; + }; + export var amazon: { + phone: boolean; + table: boolean; + device: boolean; + }; + export var windows: { + phone: boolean; + tablet: boolean; + device: boolean; + }; + export var seven_inch: boolean; + export var other: { + blackberry_10: boolean; + blackberry: boolean; + opera: boolean; + firefox: boolean; + chrome: boolean; + device: boolean; + }; + export var any: boolean; + export var phone: boolean; + export var tablet: boolean; + } + + // https://github.com/primus/eventemitter3 + export class EventEmitter { + + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + on(event: string, fn: Function, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + removeListener(event: string, fn: Function, context?: any, once?: boolean): EventEmitter; + removeAllListeners(event: string): EventEmitter; + eventNames(): string[]; + + off(event: string, fn: Function, context?: any, once?: boolean): EventEmitter; + addListener(event: string, fn: Function, context?: any): EventEmitter; + + } + +} + +////////////////////////////////////////////////////////////////////////////// +/////////////////////////////depreciation///////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +// not sure how to handle blendmodes scalemodes basetexturecache +export namespace core { + + /** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ + type SpriteBatch = ParticleContainer; + + /** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ + type AssetLoader = loaders.Loader; + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + type Stage = Container; + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + type DisplayObjectContainer = Container; + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + type Strip = mesh.Mesh; + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + type Rope = mesh.Rope; + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + type ParticleContainer = particles.ParticleContainer; + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + type MovieClip = extras.AnimatedSprite; + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + type TilingSprite = extras.TilingSprite; + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + type BitmapText = extras.BitmapText; + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + type math = any; + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + type AbstractFilter = Filter; + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + type TransformManual = TransformBase; + + /** + * @static + * @constant + * @name PIXI.TARGET_FPMS + * @see PIXI.settings.TARGET_FPMS + * @deprecated since version 4.2.0 + */ + type TARGET_FPMS = number; + + /** + * @static + * @constant + * @name PIXI.FILTER_RESOLUTION + * @see PIXI.settings.FILTER_RESOLUTION + * @deprecated since version 4.2.0 + */ + type FILTER_RESOLUTION = number; + + /** + * @static + * @constant + * @name PIXI.RESOLUTION + * @see PIXI.settings.RESOLUTION + * @deprecated since version 4.2.0 + */ + type RESOLUTION = number; + + /** + * @static + * @constant + * @name PIXI.MIPMAP_TEXTURES + * @see PIXI.settings.MIPMAP_TEXTURES + * @deprecated since version 4.2.0 + */ + type MIPMAP_TEXTURES = any; + + /** + * @static + * @constant + * @name PIXI.SPRITE_BATCH_SIZE + * @see PIXI.settings.SPRITE_BATCH_SIZE + * @deprecated since version 4.2.0 + */ + type SPRITE_BATCH_SIZE = number; + + /** + * @static + * @constant + * @name PIXI.SPRITE_MAX_TEXTURES + * @see PIXI.settings.SPRITE_MAX_TEXTURES + * @deprecated since version 4.2.0 + */ + type SPRITE_MAX_TEXTURES = number; + + /** + * @static + * @constant + * @name PIXI.RETINA_PREFIX + * @see PIXI.settings.RETINA_PREFIX + * @deprecated since version 4.2.0 + */ + type RETINA_PREFIX = RegExp | string; + + /** + * @static + * @constant + * @name PIXI.DEFAULT_RENDER_OPTIONS + * @see PIXI.settings.RENDER_OPTIONS + * @deprecated since version 4.2.0 + */ + type DEFAULT_RENDER_OPTIONS = number; + +} + +export namespace extras { + + /** + * @class + * @name MovieClip + * @memberof PIXI.extras + * @see PIXI.extras.AnimatedSprite + * @deprecated since version 4.2.0 + */ + type MovieClip = extras.AnimatedSprite; + +} + +declare global { + namespace pixi { + export var gl: typeof glCore; + } +} + +export as namespace PIXI; diff --git a/pixi.js/pixi.js-tests.ts b/pixi.js/pixi.js-tests.ts index 7819dd9603..313ad7740e 100644 --- a/pixi.js/pixi.js-tests.ts +++ b/pixi.js/pixi.js-tests.ts @@ -31,7 +31,7 @@ namespace basics { this.bunny.position.x = 200; this.bunny.position.y = 150; - //add it to the stage + // add it to the stage this.stage.addChild(this.bunny); this.animate(); @@ -76,10 +76,10 @@ namespace basics { this.sprite.on('mousedown', this.onDown, this); this.sprite.on('touchstart', this.onDown, this); - //add it to the stage + // add it to the stage this.stage.addChild(this.sprite); - //start animatng + // start animatng this.animate(); } @@ -126,17 +126,13 @@ namespace basics { this.stage.addChild(this.container); for (var j = 0; j < 5; j++) { - for (var i = 0; i < 5; i++) { - var bunny: PIXI.Sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); bunny.x = 40 * i; bunny.y = 40 * j; this.container.addChild(bunny); - - }; - - }; + } + } /* * All the bunnies are added to the container with the addChild method @@ -226,7 +222,7 @@ namespace basics { type: '1f', value: 0 } - }) + }); } } @@ -324,18 +320,14 @@ namespace basics { this.stage.addChild(this.container); for (var j = 0; j < 5; j++) { - for (var i = 0; i < 5; i++) { - var bunny: PIXI.Sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); bunny.x = 40 * i; bunny.y = 40 * j; bunny.rotation = Math.random() * (Math.PI * 2); this.container.addChild(bunny); - - }; - - }; + } + } this.renderTexture = PIXI.RenderTexture.create(300, 200, PIXI.SCALE_MODES.LINEAR, 0.1); @@ -354,7 +346,7 @@ namespace basics { private animate = (): void => { - this.renderer.render(this.container, this.renderTexture) + this.renderer.render(this.container, this.renderTexture); requestAnimationFrame(this.animate); @@ -422,7 +414,7 @@ namespace basics { this.movie.rotation += 0.01; - //render the stage container + // render the stage container this.renderer.render(this.stage); requestAnimationFrame(this.animate); @@ -533,7 +525,7 @@ namespace basics { for (var i = 0; i < 25; i++) { this.points.push(new PIXI.Point(i * this.ropeLength, 0)); - }; + } this.strip = new PIXI.mesh.Rope(PIXI.Texture.fromImage('../../_assets/snake.png'), this.points); this.strip.position.x = -40; @@ -545,7 +537,7 @@ namespace basics { this.graphics.y = this.strip.y; this.stage.addChild(this.graphics); - //start animating + // start animating this.animate(); } @@ -554,16 +546,13 @@ namespace basics { this.count += 0.1; - //make the snake + // make the snake for (var i = 0; i < this.points.length; i++) { - this.points[i].y = Math.sin((i * 0.5) + this.count) * 30; - this.points[i].x = i * this.ropeLength + Math.cos((i * 0.3) + this.count) * 20; + } - }; - - //render the stage + // render the stage this.renderer.render(this.stage); this.renderPoints(); @@ -573,7 +562,6 @@ namespace basics { } private renderPoints(): void { - this.graphics.clear(); this.graphics.lineStyle(2, 0xffc2c2); @@ -581,14 +569,13 @@ namespace basics { for (var i = 1; i < this.points.length; i++) { this.graphics.lineTo(this.points[i].x, this.points[i].y); - }; + } for (var i = 1; i < this.points.length; i++) { this.graphics.beginFill(0xff0022); this.graphics.drawCircle(this.points[i].x, this.points[i].y, 10); this.graphics.endFill(); - }; - + } } } @@ -617,7 +604,7 @@ namespace basics { // create the root of the scene graph this.stage = new PIXI.Container(); - //create a texture from an image path + // create a texture from an image path this.texture = PIXI.Texture.fromImage('../../_assets/p2.jpeg'); /* create a tiling sprite ... @@ -674,10 +661,10 @@ namespace basics { // create the root of the scene graph this.stage = new PIXI.Container(); - //create a video texture from a path + // create a video texture from a path this.texture = PIXI.Texture.fromVideo('../../_assets/testVideo.mp4'); - //create a new sprite using the video texture (yes it's that easy) + // create a new sprite using the video texture (yes it's that easy) this.videoSprite = new PIXI.Sprite(this.texture); this.videoSprite.width = this.renderer.width; this.videoSprite.height = this.renderer.height; @@ -691,7 +678,7 @@ namespace basics { private animate = (): void => { - //render the stage + // render the stage this.renderer.render(this.stage); requestAnimationFrame(this.animate); @@ -872,9 +859,7 @@ namespace demos { private animate = (): void => { // iterate through the sprites and update their position - for (var i = 0; i < this.maggots.length; i++) { - - var dude = this.maggots[i]; + for (const dude of this.maggots) { dude.scale.y = 0.95 + Math.sin(this.tick + dude.offset) * 0.05; dude.direction += dude.turningSpeed * 0.01; dude.position.x += Math.sin(dude.direction) * (dude.speed * dude.scale.y); @@ -884,15 +869,13 @@ namespace demos { // wrap the maggots if (dude.position.x < this.dudeBounds.x) { dude.position.x += this.dudeBounds.width; - } - else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + } else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { dude.position.x -= this.dudeBounds.width; } if (dude.position.y < this.dudeBounds.y) { dude.position.y += this.dudeBounds.height; - } - else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + } else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { dude.position.y -= this.dudeBounds.height; } } @@ -1012,9 +995,7 @@ namespace demos { private animate = (): void => { // iterate through the dudes and update the positions - for (var i = 0; i < this.dudeArray.length; i++) { - - var dude = this.dudeArray[i]; + for (const dude of this.dudeArray) { dude.direction += dude.turningSpeed * 0.01; dude.position.x += Math.sin(dude.direction) * dude.speed; dude.position.y += Math.cos(dude.direction) * dude.speed; @@ -1023,15 +1004,13 @@ namespace demos { // wrap the dudes by testing their bounds... if (dude.position.x < this.dudeBounds.x) { dude.position.x += this.dudeBounds.width; - } - else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + } else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { dude.position.x -= this.dudeBounds.width; } if (dude.position.y < this.dudeBounds.y) { dude.position.y += this.dudeBounds.height; - } - else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + } else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { dude.position.y -= this.dudeBounds.height; } } @@ -1117,11 +1096,11 @@ namespace demos { this.alienContainer.cacheAsBitmap = !this.alienContainer.cacheAsBitmap; - //feel free to play with what's below - //var sprite = new PIXI.Sprite(this.alienContainer.generateTexture()); - //this.stage.addChild(sprite); - //sprite.position.x = Math.random() * 800; - //sprite.position.y = Math.random() * 600; + // feel free to play with what's below + // var sprite = new PIXI.Sprite(this.alienContainer.generateTexture()); + // this.stage.addChild(sprite); + // sprite.position.x = Math.random() * 800; + // sprite.position.y = Math.random() * 600; } @@ -1189,7 +1168,7 @@ namespace demos { export class DraggableBunny extends PIXI.Sprite { - //todo I dont know what event.data is at this time + // todo I dont know what event.data is at this time private data: any; private dragging: boolean; @@ -1239,7 +1218,7 @@ namespace demos { private onDragEnd = (event: PIXI.interaction.InteractionEvent): void => { - //set interactiondata to null + // set interactiondata to null this.data = null; this.alpha = 1; this.dragging = false; @@ -1276,7 +1255,7 @@ namespace demos { // create the root of the scene graph this.stage = new PIXI.Container(); - //create a texture from an image + // create a texture from an image this.texture = PIXI.Texture.fromImage('../../_assets/bunny.png'); for (var i = 0; i < 10; i++) { @@ -1567,10 +1546,10 @@ namespace demos { .on('mouseover', this.onButtonOver) // set the mouseout callback... - .on('mouseout', this.onButtonOut) + .on('mouseout', this.onButtonOut); // you can also listen to click and tap events : - //.on('click', this.noop) + // .on('click', this.noop) } @@ -1588,8 +1567,7 @@ namespace demos { if (this.isOver) { this.texture = this.textureButtonOver; - } - else { + } else { this.texture = this.textureButton; } } @@ -1754,8 +1732,7 @@ namespace demos { if (!this.container.mask) { this.container.mask = this.thing; - } - else { + } else { this.container.mask = null; } } @@ -1927,9 +1904,8 @@ namespace demos { private animate = (): void => { - for (var i = 0; i < this.items.length; i++) { + for (const item of this.items) { // rotate each item - var item = this.items[i]; item.rotation += 0.1; } @@ -2102,7 +2078,15 @@ namespace demos { this.spinningText.position.y = 200; // create a text object that will be updated... - this.countingText = new PIXI.Text('COUNT 4EVAR: 0', { fontWeight: 'bold', fontStyle: 'italic', fontSize: 60, fontFamily: 'Arvo', fill: '#3e1707', align: 'center', stroke: '#a4410e', strokeThickness: 7 }); + this.countingText = new PIXI.Text('COUNT 4EVAR: 0', { + fontWeight: 'bold', + fontStyle: 'italic', + fontSize: 60, fontFamily: + 'Arvo', fill: '#3e1707', + align: 'center', + stroke: '#a4410e', + strokeThickness: 7 + }); this.countingText.position.x = 310; this.countingText.position.y = 320; @@ -2161,7 +2145,7 @@ namespace demos { this.bol = false; - //an image path + // an image path this.texture = PIXI.Texture.fromImage('../../_assets/flowerTop.png'); // create a second texture @@ -2187,8 +2171,7 @@ namespace demos { if (this.bol) { this.dude.texture = this.secondTexture; - } - else { + } else { this.dude.texture = this.texture; } }); @@ -2290,9 +2273,7 @@ namespace demos { private animate = (): void => { // iterate through the dudes and update their position - for (var i = 0; i < this.aliens.length; i++) { - - var dude = this.aliens[i]; + for (const dude of this.aliens) { dude.direction += dude.turningSpeed * 0.01; dude.position.x += Math.sin(dude.direction) * dude.speed; dude.position.y += Math.cos(dude.direction) * dude.speed; @@ -2301,15 +2282,13 @@ namespace demos { // wrap the dudes by testing their bounds... if (dude.position.x < this.dudeBounds.x) { dude.position.x += this.dudeBounds.width; - } - else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + } else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { dude.position.x -= this.dudeBounds.width; } if (dude.position.y < this.dudeBounds.y) { dude.position.y += this.dudeBounds.height; - } - else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + } else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { dude.position.y -= this.dudeBounds.height; } @@ -2439,7 +2418,7 @@ namespace filters { this.count = 0; - //nimate + // nimate this.animate(); } @@ -2572,15 +2551,13 @@ namespace filters { this.ring.position.x = eventData.data.global.x - 25; this.ring.position.y = eventData.data.global.y; - }; + } private animate = (): void => { this.count += 0.05; - for (var i = 0; i < this.maggots.length; i++) { - var maggot = this.maggots[i]; - + for (const maggot of this.maggots) { maggot.direction += maggot.turnSpeed * 0.01; maggot.position.x += Math.sin(maggot.direction) * maggot.speed; maggot.position.y += Math.cos(maggot.direction) * maggot.speed; @@ -2592,15 +2569,13 @@ namespace filters { // wrap the maggots around as the crawl if (maggot.position.x < this.bounds.x) { maggot.position.x += this.bounds.width; - } - else if (maggot.position.x > this.bounds.x + this.bounds.width) { + } else if (maggot.position.x > this.bounds.x + this.bounds.width) { maggot.position.x -= this.bounds.width; } if (maggot.position.y < this.bounds.y) { maggot.position.y += this.bounds.height; - } - else if (maggot.position.y > this.bounds.y + this.bounds.height) { + } else if (maggot.position.y > this.bounds.y + this.bounds.height) { maggot.position.y -= this.bounds.height; } } @@ -2609,7 +2584,7 @@ namespace filters { requestAnimationFrame(this.animate); - }; + } } @@ -2713,7 +2688,7 @@ namespace filters { this.stage.addChild(this.help); - //nimate + // animate this.animate(); } @@ -2724,8 +2699,7 @@ namespace filters { if (!this.switchy) { this.stage.filters = [this.filter]; - } - else { + } else { this.stage.filters = null; } diff --git a/pixi.js/tslint.json b/pixi.js/tslint.json new file mode 100644 index 0000000000..56ba128af1 --- /dev/null +++ b/pixi.js/tslint.json @@ -0,0 +1,9 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false, + "interface-name": false, + "no-empty-interface": false, + "unified-signatures": false + } +} diff --git a/pixi.js/v3/index.d.ts b/pixi.js/v3/index.d.ts index 695dab82d2..aa573b2201 100644 --- a/pixi.js/v3/index.d.ts +++ b/pixi.js/v3/index.d.ts @@ -83,7 +83,7 @@ declare namespace PIXI { export function autoDetectRenderer(width: number, height: number, options?: PIXI.RendererOptions, noWebGL?: boolean): PIXI.WebGLRenderer | PIXI.CanvasRenderer; export var loader: PIXI.loaders.Loader; - //https://github.com/primus/eventemitter3 + // https://github.com/primus/eventemitter3 export class EventEmitter { listeners(event: string): Function[]; @@ -102,11 +102,11 @@ declare namespace PIXI { ////////////////////////////////CORE////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - //display + // display export class DisplayObject extends EventEmitter implements interaction.InteractiveTarget { - //begin extras.cacheAsBitmap see https://github.com/pixijs/pixi-typescript/commit/1207b7f4752d79a088d6a9a465a3ec799906b1db + // begin extras.cacheAsBitmap see https://github.com/pixijs/pixi-typescript/commit/1207b7f4752d79a088d6a9a465a3ec799906b1db protected _originalRenderWebGL: WebGLRenderer; protected _originalRenderCanvas: CanvasRenderer; protected _originalUpdateTransform: boolean; @@ -123,7 +123,7 @@ declare namespace PIXI { protected _getCachedBounds(): Rectangle; protected _destroyCachedDisplayObject(): void; protected _cacheAsBitmapDestroy(): void; - //end extras.cacheAsBitmap + // end extras.cacheAsBitmap protected _sr: number; protected _cr: number; @@ -246,7 +246,7 @@ declare namespace PIXI { } - //graphics + // graphics export class GraphicsData { @@ -297,7 +297,7 @@ declare namespace PIXI { drawEllipse(x: number, y: number, width: number, height: number): Graphics; drawPolygon(path: number[] | Point[]): Graphics; clear(): Graphics; - //todo + // todo generateTexture(renderer: WebGLRenderer | CanvasRenderer, resolution?: number, scaleMode?: number): Texture; getBounds(matrix?: Matrix): Rectangle; containsPoint(point: Point): boolean; @@ -306,13 +306,13 @@ declare namespace PIXI { } export interface GraphicsRenderer extends ObjectRenderer { - //yikes todo + // yikes todo } export interface WebGLGraphicsData { - //yikes todo! + // yikes todo! } - //math + // math export class Point { @@ -442,7 +442,7 @@ declare namespace PIXI { } - //particles + // particles export interface ParticleContainerProperties { @@ -500,7 +500,7 @@ declare namespace PIXI { } - //renderers + // renderers export interface RendererOptions { @@ -533,7 +533,7 @@ declare namespace PIXI { resolution: number; transparent: boolean; autoResize: boolean; - blendModes: any; //todo? + blendModes: any; // todo? preserveDrawingBuffer: boolean; clearBeforeRender: boolean; roundPixels: boolean; @@ -856,7 +856,7 @@ declare namespace PIXI { } - //sprites + // sprites export class Sprite extends Container { @@ -909,7 +909,7 @@ declare namespace PIXI { } - //text + // text export interface TextStyle { @@ -959,7 +959,7 @@ declare namespace PIXI { } - //textures + // textures export class BaseTexture extends EventEmitter { @@ -1100,7 +1100,7 @@ declare namespace PIXI { } - //utils + // utils export class utils { @@ -1203,9 +1203,9 @@ declare namespace PIXI { } export class TilingSprite extends Sprite { - //This is really unclean but is the only way :( - //See http://stackoverflow.com/questions/29593905/typescript-declaration-extending-class-with-static-method/29595798#29595798 - //Thanks bas! + // This is really unclean but is the only way :( + // See http://stackoverflow.com/questions/29593905/typescript-declaration-extending-class-with-static-method/29595798#29595798 + // Thanks bas! static fromFrame(frameId: string): Sprite; static fromFrame(frameId: string, width?: number, height?: number): TilingSprite; @@ -1531,7 +1531,7 @@ declare namespace PIXI { ////////////////////////////////////////////////////////////////////////////// ///////////////////////////////LOADER///////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - //https://github.com/englercj/resource-loader/blob/master/src/Loader.js + // https://github.com/englercj/resource-loader/blob/master/src/Loader.js export namespace loaders { export interface LoaderOptions { @@ -1556,7 +1556,7 @@ declare namespace PIXI { add(name: string, url: string, options?: LoaderOptions, cb?: () => void): Loader; add(url: string, options?: LoaderOptions, cb?: () => void): Loader; - //todo I am not sure of object literal notional (or its options) so just allowing any but would love to improve this + // todo I am not sure of object literal notional (or its options) so just allowing any but would love to improve this add(obj: any, options?: LoaderOptions, cb?: () => void): Loader; on(event: 'complete', fn: (loader: loaders.Loader, object: any) => void, context?: any): EventEmitter; diff --git a/pixi.js/v3/pixi.js-tests.ts b/pixi.js/v3/pixi.js-tests.ts index afb61a43d8..ec4c5329c0 100644 --- a/pixi.js/v3/pixi.js-tests.ts +++ b/pixi.js/v3/pixi.js-tests.ts @@ -30,7 +30,7 @@ namespace basics { this.bunny.position.x = 200; this.bunny.position.y = 150; - //add it to the stage + // add it to the stage this.stage.addChild(this.bunny); this.animate(); @@ -75,10 +75,10 @@ namespace basics { this.sprite.on('mousedown', this.onDown, this); this.sprite.on('touchstart', this.onDown, this); - //add it to the stage + // add it to the stage this.stage.addChild(this.sprite); - //start animatng + // start animatng this.animate(); } @@ -133,9 +133,9 @@ namespace basics { bunny.y = 40 * j; this.container.addChild(bunny); - }; + } - }; + } /* * All the bunnies are added to the container with the addChild method @@ -225,7 +225,7 @@ namespace basics { type: '1f', value: 0 } - }) + }); } } @@ -332,9 +332,9 @@ namespace basics { bunny.rotation = Math.random() * (Math.PI * 2); this.container.addChild(bunny); - }; + } - }; + } this.renderTexture = new PIXI.RenderTexture(this.renderer, 300, 200, PIXI.SCALE_MODES.LINEAR, 0.1); @@ -421,7 +421,7 @@ namespace basics { this.movie.rotation += 0.01; - //render the stage container + // render the stage container this.renderer.render(this.stage); requestAnimationFrame(this.animate); @@ -529,7 +529,7 @@ namespace basics { for (var i = 0; i < 25; i++) { this.points.push(new PIXI.Point(i * this.ropeLength, 0)); - }; + } this.strip = new PIXI.mesh.Rope(PIXI.Texture.fromImage('../../_assets/snake.png'), this.points); this.strip.position.x = -40; @@ -541,7 +541,7 @@ namespace basics { this.graphics.y = this.strip.y; this.stage.addChild(this.graphics); - //start animating + // start animating this.animate(); } @@ -550,16 +550,16 @@ namespace basics { this.count += 0.1; - //make the snake + // make the snake for (var i = 0; i < this.points.length; i++) { this.points[i].y = Math.sin((i * 0.5) + this.count) * 30; this.points[i].x = i * this.ropeLength + Math.cos((i * 0.3) + this.count) * 20; - }; + } - //render the stage + // render the stage this.renderer.render(this.stage); this.renderPoints(); @@ -577,13 +577,13 @@ namespace basics { for (var i = 1; i < this.points.length; i++) { this.graphics.lineTo(this.points[i].x, this.points[i].y); - }; + } for (var i = 1; i < this.points.length; i++) { this.graphics.beginFill(0xff0022); this.graphics.drawCircle(this.points[i].x, this.points[i].y, 10); this.graphics.endFill(); - }; + } } @@ -613,7 +613,7 @@ namespace basics { // create the root of the scene graph this.stage = new PIXI.Container(); - //create a texture from an image path + // create a texture from an image path this.texture = PIXI.Texture.fromImage('../../_assets/p2.jpeg'); /* create a tiling sprite ... @@ -670,10 +670,10 @@ namespace basics { // create the root of the scene graph this.stage = new PIXI.Container(); - //create a video texture from a path + // create a video texture from a path this.texture = PIXI.Texture.fromVideo('../../_assets/testVideo.mp4'); - //create a new sprite using the video texture (yes it's that easy) + // create a new sprite using the video texture (yes it's that easy) this.videoSprite = new PIXI.Sprite(this.texture); this.videoSprite.width = this.renderer.width; this.videoSprite.height = this.renderer.height; @@ -687,7 +687,7 @@ namespace basics { private animate = (): void => { - //render the stage + // render the stage this.renderer.render(this.stage); requestAnimationFrame(this.animate); @@ -868,9 +868,7 @@ namespace demos { private animate = (): void => { // iterate through the sprites and update their position - for (var i = 0; i < this.maggots.length; i++) { - - var dude = this.maggots[i]; + for (const dude of this.maggots) { dude.scale.y = 0.95 + Math.sin(this.tick + dude.offset) * 0.05; dude.direction += dude.turningSpeed * 0.01; dude.position.x += Math.sin(dude.direction) * (dude.speed * dude.scale.y); @@ -880,15 +878,13 @@ namespace demos { // wrap the maggots if (dude.position.x < this.dudeBounds.x) { dude.position.x += this.dudeBounds.width; - } - else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + } else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { dude.position.x -= this.dudeBounds.width; } if (dude.position.y < this.dudeBounds.y) { dude.position.y += this.dudeBounds.height; - } - else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + } else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { dude.position.y -= this.dudeBounds.height; } } @@ -1008,9 +1004,7 @@ namespace demos { private animate = (): void => { // iterate through the dudes and update the positions - for (var i = 0; i < this.dudeArray.length; i++) { - - var dude = this.dudeArray[i]; + for (const dude of this.dudeArray) { dude.direction += dude.turningSpeed * 0.01; dude.position.x += Math.sin(dude.direction) * dude.speed; dude.position.y += Math.cos(dude.direction) * dude.speed; @@ -1019,15 +1013,13 @@ namespace demos { // wrap the dudes by testing their bounds... if (dude.position.x < this.dudeBounds.x) { dude.position.x += this.dudeBounds.width; - } - else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + } else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { dude.position.x -= this.dudeBounds.width; } if (dude.position.y < this.dudeBounds.y) { dude.position.y += this.dudeBounds.height; - } - else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + } else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { dude.position.y -= this.dudeBounds.height; } } @@ -1113,11 +1105,11 @@ namespace demos { this.alienContainer.cacheAsBitmap = !this.alienContainer.cacheAsBitmap; - //feel free to play with what's below - //var sprite = new PIXI.Sprite(this.alienContainer.generateTexture()); - //this.stage.addChild(sprite); - //sprite.position.x = Math.random() * 800; - //sprite.position.y = Math.random() * 600; + // feel free to play with what's below + // var sprite = new PIXI.Sprite(this.alienContainer.generateTexture()); + // this.stage.addChild(sprite); + // sprite.position.x = Math.random() * 800; + // sprite.position.y = Math.random() * 600; } @@ -1185,7 +1177,7 @@ namespace demos { export class DraggableBunny extends PIXI.Sprite { - //todo I dont know what event.data is at this time + // todo I dont know what event.data is at this time private data: any; private dragging: boolean; @@ -1235,7 +1227,7 @@ namespace demos { private onDragEnd = (event: PIXI.interaction.InteractionEvent): void => { - //set interactiondata to null + // set interactiondata to null this.data = null; this.alpha = 1; this.dragging = false; @@ -1272,7 +1264,7 @@ namespace demos { // create the root of the scene graph this.stage = new PIXI.Container(); - //create a texture from an image + // create a texture from an image this.texture = PIXI.Texture.fromImage('../../_assets/bunny.png'); for (var i = 0; i < 10; i++) { @@ -1563,10 +1555,10 @@ namespace demos { .on('mouseover', this.onButtonOver) // set the mouseout callback... - .on('mouseout', this.onButtonOut) + .on('mouseout', this.onButtonOut); // you can also listen to click and tap events : - //.on('click', this.noop) + // .on('click', this.noop) } @@ -1584,8 +1576,7 @@ namespace demos { if (this.isOver) { this.texture = this.textureButtonOver; - } - else { + } else { this.texture = this.textureButton; } } @@ -1750,8 +1741,7 @@ namespace demos { if (!this.container.mask) { this.container.mask = this.thing; - } - else { + } else { this.container.mask = null; } } @@ -1923,9 +1913,8 @@ namespace demos { private animate = (): void => { - for (var i = 0; i < this.items.length; i++) { + for (const item of this.items) { // rotate each item - var item = this.items[i]; item.rotation += 0.1; } @@ -2157,7 +2146,7 @@ namespace demos { this.bol = false; - //an image path + // an image path this.texture = PIXI.Texture.fromImage('../../_assets/flowerTop.png'); // create a second texture @@ -2183,8 +2172,7 @@ namespace demos { if (this.bol) { this.dude.texture = this.secondTexture; - } - else { + } else { this.dude.texture = this.texture; } }); @@ -2286,9 +2274,7 @@ namespace demos { private animate = (): void => { // iterate through the dudes and update their position - for (var i = 0; i < this.aliens.length; i++) { - - var dude = this.aliens[i]; + for (const dude of this.aliens) { dude.direction += dude.turningSpeed * 0.01; dude.position.x += Math.sin(dude.direction) * dude.speed; dude.position.y += Math.cos(dude.direction) * dude.speed; @@ -2297,15 +2283,13 @@ namespace demos { // wrap the dudes by testing their bounds... if (dude.position.x < this.dudeBounds.x) { dude.position.x += this.dudeBounds.width; - } - else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + } else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { dude.position.x -= this.dudeBounds.width; } if (dude.position.y < this.dudeBounds.y) { dude.position.y += this.dudeBounds.height; - } - else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + } else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { dude.position.y -= this.dudeBounds.height; } @@ -2435,7 +2419,7 @@ namespace filters { this.count = 0; - //nimate + // nimate this.animate(); } @@ -2568,15 +2552,13 @@ namespace filters { this.ring.position.x = eventData.data.global.x - 25; this.ring.position.y = eventData.data.global.y; - }; + } private animate = (): void => { this.count += 0.05; - for (var i = 0; i < this.maggots.length; i++) { - var maggot = this.maggots[i]; - + for (const maggot of this.maggots) { maggot.direction += maggot.turnSpeed * 0.01; maggot.position.x += Math.sin(maggot.direction) * maggot.speed; maggot.position.y += Math.cos(maggot.direction) * maggot.speed; @@ -2588,15 +2570,13 @@ namespace filters { // wrap the maggots around as the crawl if (maggot.position.x < this.bounds.x) { maggot.position.x += this.bounds.width; - } - else if (maggot.position.x > this.bounds.x + this.bounds.width) { + } else if (maggot.position.x > this.bounds.x + this.bounds.width) { maggot.position.x -= this.bounds.width; } if (maggot.position.y < this.bounds.y) { maggot.position.y += this.bounds.height; - } - else if (maggot.position.y > this.bounds.y + this.bounds.height) { + } else if (maggot.position.y > this.bounds.y + this.bounds.height) { maggot.position.y -= this.bounds.height; } } @@ -2605,7 +2585,7 @@ namespace filters { requestAnimationFrame(this.animate); - }; + } } @@ -2709,7 +2689,7 @@ namespace filters { this.stage.addChild(this.help); - //nimate + // animate this.animate(); } @@ -2720,8 +2700,7 @@ namespace filters { if (!this.switchy) { this.stage.filters = [this.filter]; - } - else { + } else { this.stage.filters = null; } diff --git a/pixi.js/v3/tslint.json b/pixi.js/v3/tslint.json index ff23ef7097..dca585dadc 100644 --- a/pixi.js/v3/tslint.json +++ b/pixi.js/v3/tslint.json @@ -1,8 +1,8 @@ { - "extends": "../../tslint.json", + "extends": "../tslint.json", "rules": { "forbidden-types": false, "no-empty-interface": false, "unified-signatures": false } -} \ No newline at end of file +} diff --git a/plugapi/plugapi-tests.ts b/plugapi/plugapi-tests.ts index d9a0845997..58b88c0e2f 100644 --- a/plugapi/plugapi-tests.ts +++ b/plugapi/plugapi-tests.ts @@ -3,24 +3,24 @@ import PlugAPI = require("plugapi"); new PlugAPI({ email: "", password: "" -}, function (err, bot) { +}, (err, bot) => { if (!err) { const ROOM = "roomslug"; - bot.connect(ROOM); // The part after https://plug.dj + bot.connect(ROOM); // The part after https://plug.dj - bot.on(PlugAPI.events.ROOM_JOIN, function (room) { + bot.on(PlugAPI.events.ROOM_JOIN, room => { console.log("Joined " + room); }); - bot.on("chat", function (data) { - if (data.type == "emote") { + bot.on("chat", data => { + if (data.type === "emote") { console.log(data.from + data.message); } else { console.log(data.from + "> " + data.message); } }); - bot.on("error", function () { + bot.on("error", () => { bot.connect(ROOM); }); diff --git a/progressbar/progressbar-tests.ts b/progressbar/progressbar-tests.ts index f6cfa4dac4..46dcc60732 100644 --- a/progressbar/progressbar-tests.ts +++ b/progressbar/progressbar-tests.ts @@ -2,8 +2,8 @@ import { Progressbar, create } from 'progressbar'; let str: string = '', progressbar: Progressbar, - num: number = 1, - fn: () => void = () => {}; + num: number = 1; +const fn: () => void = () => {}; progressbar = create(); progressbar = progressbar.step(str); diff --git a/progressbar/tsconfig.json b/progressbar/tsconfig.json index 3ee0810c0f..5f8279d45a 100644 --- a/progressbar/tsconfig.json +++ b/progressbar/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "progressbar-tests.ts" ] -} +} \ No newline at end of file diff --git a/proj4/index.d.ts b/proj4/index.d.ts index d59063f51b..ff2b8334de 100644 --- a/proj4/index.d.ts +++ b/proj4/index.d.ts @@ -1,102 +1,67 @@ -// Type definitions for proj4 2.3.15 +// Type definitions for proj4 2.3 // Project: https://github.com/proj4js/proj4js // Definitions by: Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "proj4" { - const TemplateCoordinates: Array | InterfaceCoordinates; +declare namespace proj4 { + type TemplateCoordinates = number[] | InterfaceCoordinates; interface InterfaceCoordinates { - x: number, - y: number, - z?: number, - m?: number + x: number; + y: number; + z?: number; + m?: number; } interface InterfaceDatum { - datum_type: number - a: number - b: number - es: number - ep2: number + datum_type: number; + a: number; + b: number; + es: number; + ep2: number; } - interface Proj4Static { - forward(coordinates: typeof TemplateCoordinates): Array - inverse(coordinates: typeof TemplateCoordinates): Array + interface Static { + forward(coordinates: TemplateCoordinates): number[]; + inverse(coordinates: TemplateCoordinates): number[]; } interface InterfaceProjection { - datum: string - b: number - rf: number - sphere: number - es: number - e: number - ep2: number - forward(coordinates: typeof TemplateCoordinates): Array - inverse(coordinates: typeof TemplateCoordinates): Array + datum: string; + b: number; + rf: number; + sphere: number; + es: number; + e: number; + ep2: number; + forward(coordinates: TemplateCoordinates): number[]; + inverse(coordinates: TemplateCoordinates): number[]; } - namespace proj4 { - /** - * @name defaultDatum - */ - export const defaultDatum: string; + export const defaultDatum: string; - /** - * @name Proj - */ - export function Proj(srsCode:any, callback?: any): InterfaceProjection; - - /** - * @name WGS84 - */ - export const WGS84: any; + export function Proj(srsCode: any, callback?: any): InterfaceProjection; - /** - * Depecrated v3 - * @name Point - */ - export function Point(x: number, y: number, z?: number): InterfaceCoordinates; - export function Point(coordinates: Array): InterfaceCoordinates; - export function Point(coordinates: InterfaceCoordinates): InterfaceCoordinates; - export function Point(coordinates: string): InterfaceCoordinates; - - /** - * @name toPoint - */ - export function toPoint(array: Array): InterfaceCoordinates; - - /** - * @name defs - */ - export function defs(name: string): any; - export function defs(name: string, projection: string): any; - export function defs(name: Array>): any; - - /** - * @name transform - */ - export function transform(source: InterfaceProjection, dest: InterfaceProjection, point: typeof TemplateCoordinates): any; - - /** - * @name mgrs - */ - export function mgrs(coordinates: Array, accuracy: number): string; - - /** - * @name version - */ - export const version: string; - } + export const WGS84: any; /** - * @name proj4 + * Depecrated v3 */ - function proj4(fromProjection: string): Proj4Static; - function proj4(fromProjection: string, toProjection: string): Proj4Static; - function proj4(fromProjection: string, coordinates: typeof TemplateCoordinates): Array; - function proj4(fromProjection: string, toProjection: string, coordinates: typeof TemplateCoordinates): Array; - export = proj4 + export function Point(x: number, y: number, z?: number): InterfaceCoordinates; + export function Point(coordinates: TemplateCoordinates | string): InterfaceCoordinates; + + export function toPoint(array: number[]): InterfaceCoordinates; + + export function defs(name: string, projection?: string): any; + export function defs(name: string[][]): any; + + export function transform(source: InterfaceProjection, dest: InterfaceProjection, point: TemplateCoordinates): any; + + export function mgrs(coordinates: number[], accuracy: number): string; + + export const version: string; } + +declare function proj4(fromProjection: string, toProjection?: string, coordinates?: proj4.TemplateCoordinates): proj4.Static; +declare function proj4(fromProjection: string, coordinates: proj4.TemplateCoordinates): number[]; +export = proj4; diff --git a/proj4/proj4-tests.ts b/proj4/proj4-tests.ts index 72fa804c6e..2c658b8f24 100644 --- a/proj4/proj4-tests.ts +++ b/proj4/proj4-tests.ts @@ -1,49 +1,49 @@ -import * as proj4 from 'proj4' +import * as proj4 from 'proj4'; /////////////////////////////////////////// // Tests data initialisation /////////////////////////////////////////// -const name = 'WGS84' +const name = 'WGS84'; const epsg = { 4269: '+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees', 4326: '+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees', -} -const point1 = [-71, 41] -const point2 = {x: 2, y: 5} -const mgrs = "24XWT783908" +}; +const point1 = [-71, 41]; +const point2 = {x: 2, y: 5}; +const mgrs = "24XWT783908"; /////////////////////////////////////////// // Tests Measurement /////////////////////////////////////////// -proj4(epsg['4269'], epsg['4326'], point1) -proj4(epsg['4269'], point1) -proj4(epsg['4269'], epsg['4326']).forward(point2) -proj4(epsg['4269'], epsg['4326']).inverse(point2) +proj4(epsg['4269'], epsg['4326'], point1); +proj4(epsg['4269'], point1); +proj4(epsg['4269'], epsg['4326']).forward(point2); +proj4(epsg['4269'], epsg['4326']).inverse(point2); /////////////////////////////////// // Named Projections /////////////////////////////////// -proj4.defs('WGS84', epsg['4326']) +proj4.defs('WGS84', epsg['4326']); proj4.defs([ ['EPSG:4326', epsg['4326']], ['EPSG:4269', epsg['4269']] -]) -proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326')) +]); +proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326')); /////////////////////////////////// // Utils /////////////////////////////////// // WGS84 -proj4.WGS84 +proj4.WGS84; // Proj -proj4.Proj('WGS84') +proj4.Proj('WGS84'); // toPoint -proj4.toPoint([1, 2]) -proj4.toPoint([1, 2, 3]) -proj4.toPoint([1, 2, 3, 4]) +proj4.toPoint([1, 2]); +proj4.toPoint([1, 2, 3]); +proj4.toPoint([1, 2, 3, 4]); // Point // WARNING: Deprecated in v3 -proj4.Point([1, 2, 3, 4]) \ No newline at end of file +proj4.Point([1, 2, 3, 4]); \ No newline at end of file diff --git a/proj4/tslint.json b/proj4/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/proj4/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/promised-temp/index.d.ts b/promised-temp/index.d.ts new file mode 100644 index 0000000000..e7dc2556b7 --- /dev/null +++ b/promised-temp/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for promised-temp 0.1 +// Project: https://www.npmjs.com/package/promised-temp, https://github.com/mikaturunen/promised-temp +// Definitions by: Saqib Rokadia +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as fs from 'fs'; +import { AffixOptions, OpenFile, Stats } from "temp"; +export { AffixOptions, OpenFile, Stats } from "temp"; + +interface TempStatic { + dir: string; + track(value?: boolean): TempStatic; + + path(affixes?: string | AffixOptions, defaultPrefix?: string): string; + mkdir(affixes?: string | AffixOptions): Promise; + open(affixes?: string | AffixOptions): Promise; + cleanup(): Promise; + createWriteStream(affixes?: string | AffixOptions): Promise; +} + +declare var PromisedTemp: TempStatic; +export default PromisedTemp; diff --git a/promised-temp/package.json b/promised-temp/package.json new file mode 100644 index 0000000000..55849714d6 --- /dev/null +++ b/promised-temp/package.json @@ -0,0 +1,6 @@ +{ + "dependencies": { + "@types/temp": "latest", + "@types/node": "latest" + } +} diff --git a/promised-temp/promised-temp-tests.ts b/promised-temp/promised-temp-tests.ts new file mode 100644 index 0000000000..2b77184e25 --- /dev/null +++ b/promised-temp/promised-temp-tests.ts @@ -0,0 +1,59 @@ + +/// + +import * as fs from "fs"; +import temp from 'promised-temp'; +import { AffixOptions, OpenFile, Stats } from "promised-temp"; + +function testCleanup() { + temp.cleanup().then((result: boolean | Stats) => { + if (typeof result === "boolean") { + const x = result === true; + } + else { + const { files, dirs } = result; + files.toPrecision(4); + } + }); +} + +function testOpen() { + temp.open({ dir: "tempDir", prefix: "pref", suffix: "suff" }).then((result: OpenFile) => { + const { path, fd } = result; + path.length; + fd.toPrecision(5); + }); + + temp.open("strPrefix").then((result: OpenFile) => { + const { path, fd } = result; + path.length; + fd.toPrecision(5); + }); +} + +function testCreateWriteStream() { + const stream = + temp.createWriteStream("HelloStreamAffix") + .then((stream: fs.WriteStream) => stream.write("data")); + + const stream2 = temp.createWriteStream(); +} + +function testMkdir() { + temp.mkdir("prefix").then((dirPath: string) => { + dirPath.length; + }); +} + +function testPath() { + const p = temp.path({ suffix: "justSuffix" }, "defaultPrefix"); + p.length; + const p2: string = temp.path("prefix"); + const p3: string = temp.path({ prefix: "prefix" }); +} + +function testTrack() { + const tempChained = temp.track().track(true).track(false); + tempChained.dir; + tempChained.cleanup(); +} diff --git a/promised-temp/tsconfig.json b/promised-temp/tsconfig.json new file mode 100644 index 0000000000..e1c7a3aef8 --- /dev/null +++ b/promised-temp/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "promised-temp-tests.ts" + ] +} diff --git a/promised-temp/tslint.json b/promised-temp/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/promised-temp/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/protractor-browser-logs/index.d.ts b/protractor-browser-logs/index.d.ts new file mode 100644 index 0000000000..7f3a4ffa55 --- /dev/null +++ b/protractor-browser-logs/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for protractor-browser-logs 1.0 +// Project: https://www.npmjs.com/package/protractor-browser-logs, https://github.com/wix/protractor-browser-logs +// Definitions by: Saqib Rokadia +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as webdriver from 'selenium-webdriver'; +import Entry = webdriver.logging.Entry; +import { ProtractorBrowser } from 'protractor/built'; + +interface BrowserLogOptions { + reporters?: Array<(entries: Entry[]) => void>; +} + +type matchPredicateFunction = (entry: Entry) => boolean; +type matchPredicate = string | RegExp | matchPredicateFunction; +interface BrowserLogs { + ERROR: matchPredicateFunction; + WARNING: matchPredicateFunction; + DEBUG: matchPredicateFunction; + INFO: matchPredicateFunction; + LOG: matchPredicateFunction; + + or(a: matchPredicateFunction, b: matchPredicateFunction): matchPredicateFunction; + and(a: matchPredicateFunction, b: matchPredicateFunction): matchPredicateFunction; + reset(): void; + logs(): Entry[]; + verify(): void; + ignore(... matches: matchPredicate[]): matchPredicateFunction[]; + expect(... matches: matchPredicate[]): matchPredicateFunction[]; +} + +export default function browserLogs(browser: ProtractorBrowser, options?: BrowserLogOptions): BrowserLogs; diff --git a/protractor-browser-logs/package.json b/protractor-browser-logs/package.json new file mode 100644 index 0000000000..1f7874a30c --- /dev/null +++ b/protractor-browser-logs/package.json @@ -0,0 +1,6 @@ +{ + "dependencies": { + "protractor": "latest", + "@types/selenium-webdriver": "latest" + } +} diff --git a/protractor-browser-logs/protractor-browser-logs-tests.ts b/protractor-browser-logs/protractor-browser-logs-tests.ts new file mode 100644 index 0000000000..8e2e0ac015 --- /dev/null +++ b/protractor-browser-logs/protractor-browser-logs-tests.ts @@ -0,0 +1,74 @@ +import { browser } from 'protractor/built'; +import browserLogs from 'protractor-browser-logs'; +import * as webdriver from 'selenium-webdriver'; +import Entry = webdriver.logging.Entry; + +function colored(entries: Entry[]) { + let colors: any = { INFO: 35 /* magenta */, WARNING: 33 /* yellow */, SEVERE: 31 /* red */}; + entries.forEach((entry: Entry) => { + console.log('\u001b[' + (colors[entry.level.name] || 37) + 'm' + [entry.level.name, entry.message].join(': ') + '\u001b[39m'); + }); +} + +function testCreateFunction() { + let logs = browserLogs(browser); + logs = browserLogs(browser, { reporters: [] }); + logs = browserLogs(browser, { reporters: [ colored ] }); +} + +function testLogLevels() { + let logs = browserLogs(browser); + + logs.ignore(logs.ERROR); + logs.expect(logs.WARNING); + logs.ignore(logs.DEBUG); + logs.expect(logs.INFO); + logs.ignore(logs.LOG); +} + +function testPredicateFunctions() { + let logs = browserLogs(browser); + + logs.ignore(logs.or(logs.ERROR, logs.WARNING)); + logs.expect(logs.and(logs.DEBUG, logs.INFO)); +} + +function testRegExp() { + let logs = browserLogs(browser); + + logs.ignore(/foo/i); + logs.expect(new RegExp('/foo/i')); +} + +function testString() { + let logs = browserLogs(browser); + + logs.ignore('foo'); + logs.expect('foo'); +} + +function testMatchFunction() { + let logs = browserLogs(browser); + let filter = (entry: Entry) => entry.message === "foo"; + + logs.ignore(filter); + logs.expect(filter); +} + +function testReset() { + let logs = browserLogs(browser); + + logs.reset(); +} + +function testLogs() { + let logs = browserLogs(browser); + + let entries: Entry[] = logs.logs(); +} + +function testVerify() { + let logs = browserLogs(browser); + + logs.verify(); +} diff --git a/protractor-browser-logs/tsconfig.json b/protractor-browser-logs/tsconfig.json new file mode 100644 index 0000000000..76e8d82d3a --- /dev/null +++ b/protractor-browser-logs/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "protractor-browser-logs-tests.ts" + ] +} diff --git a/protractor-browser-logs/tslint.json b/protractor-browser-logs/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/protractor-browser-logs/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/pump/tsconfig.json b/pump/tsconfig.json index b7d71ceb05..80be4c4034 100644 --- a/pump/tsconfig.json +++ b/pump/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "pump-tests.ts" ] -} +} \ No newline at end of file diff --git a/python-shell/python-shell-tests.ts b/python-shell/python-shell-tests.ts index 83bca24b6e..859ea102e2 100644 --- a/python-shell/python-shell-tests.ts +++ b/python-shell/python-shell-tests.ts @@ -1,8 +1,8 @@ import * as ps from 'python-shell'; -let PythonShell = ps.PythonShell; +const PythonShell = ps.PythonShell; -ps.run('my_script.py', function (err) { +ps.run('my_script.py', err => { if (err) throw err; console.log('finished'); }); @@ -14,25 +14,25 @@ var options = { scriptPath: 'path/to/my/scripts', args: ['value1', 'value2', 'value3'] }; - -ps.run('my_script.py', options, function (err, results) { + +ps.run('my_script.py', options, (err, results) => { if (err) throw err; - // results is an array consisting of messages collected during execution + // results is an array consisting of messages collected during execution console.log('results: %j', results); }); var pyshell = new PythonShell('my_script.py'); -// sends a message to the Python script via stdin +// sends a message to the Python script via stdin pyshell.send('hello'); - -pyshell.on('message', function (message) { - // received a message sent from the Python script (a simple "print" statement) + +pyshell.on('message', message => { + // received a message sent from the Python script (a simple "print" statement) console.log(message); }); - -// end the input stream and allow the process to exit -pyshell.end(function (err) { + +// end the input stream and allow the process to exit +pyshell.end(err => { if (err) throw err; console.log('finished'); }); \ No newline at end of file diff --git a/python-shell/tslint.json b/python-shell/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/python-shell/tslint.json +++ b/python-shell/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/random-seed/random-seed-tests.ts b/random-seed/random-seed-tests.ts index 9eb399eff5..9975608d8b 100644 --- a/random-seed/random-seed-tests.ts +++ b/random-seed/random-seed-tests.ts @@ -1,12 +1,12 @@ import { RandomSeed, create } from "random-seed"; // these generators produce different numbers -let rand1: RandomSeed = create(); // method 1 +const rand1: RandomSeed = create(); // method 1 // these generators will produce // the same sequence of numbers -let seed = 'My Secret String Value'; -let rand2 = create(seed); +const seed = 'My Secret String Value'; +const rand2 = create(seed); // API rand1.addEntropy(); diff --git a/range-parser/range-parser-tests.ts b/range-parser/range-parser-tests.ts index 77dab456c1..68581e82cb 100644 --- a/range-parser/range-parser-tests.ts +++ b/range-parser/range-parser-tests.ts @@ -1,5 +1,7 @@ import * as RangeParser from 'range-parser'; +declare var console: { assert(b: boolean): void }; + console.assert(RangeParser(200, `malformed`) === RangeParser.Result.invaild); console.assert(RangeParser(200, `bytes=500-20`) === RangeParser.Result.unsatisifiable); diff --git a/range-parser/tsconfig.json b/range-parser/tsconfig.json index 7c7f4ffd03..9fb0a10c5f 100644 --- a/range-parser/tsconfig.json +++ b/range-parser/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "range-parser-tests.ts" ] -} +} \ No newline at end of file diff --git a/raven-js/index.d.ts b/raven-js/index.d.ts deleted file mode 100644 index 7b54ec7372..0000000000 --- a/raven-js/index.d.ts +++ /dev/null @@ -1,338 +0,0 @@ -// Type definitions for Raven.js -// Project: https://github.com/getsentry/raven-js -// Definitions by: Santi Albo , Benjamin Pannell , Gary Blackwood , Rich Rout , Ben Vinegar , Ilya Pirogov , Eli White , David Cramer , Connor Peet , comaz , Luca Vazzano -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -declare let Raven: RavenStatic; -export default Raven; - -interface RavenStatic { - /** Raven.js version. */ - VERSION: string; - - /** A list of currently active plugins. */ - Plugins: { [id: string]: RavenPlugin }; - - /** - * Allow Raven to be configured as soon as it is loaded. - * It uses a global RavenConfig = {dsn: '...', config: {}} - */ - afterLoad(): void; - - /** - * Allow multiple versions of Raven to be installed. - * Strip Raven from the global context and returns the instance. - */ - noConflict(): RavenStatic; - - /** - * Configure Raven with a DSN and extra options - * - * @param dsn The public Sentry DSN - * @param options Optional set of of global options - */ - config(dsn: string, options?: RavenGlobalOptions): RavenStatic; - - /** - * Set the DSN (can be called multiple times, unlike config) - * - * @param dsn The public Sentry DSN - */ - setDSN(dsn: string): RavenStatic; - - /** - * Installs a global window.onerror error handler to capture and report uncaught exceptions. - * At this point, install() is required to be called due to the way TraceKit is set up. - */ - install(): RavenStatic; - - /** - * Adds a plugin to Raven - */ - addPlugin(plugin: RavenPlugin, ...pluginArgs: any[]): RavenStatic; - - /** - * Wrap code within a context so Raven can capture errors reliably across domains that is - * executed immediately. - * - * @param options A specific set of options for this context - * @param func The callback to be immediately executed within the context - * @param args An array of arguments to be called with the callback - */ - context(func: Function, ...args: any[]): void; - context(options: RavenWrapOptions, func: Function, ...args: any[]): void; - - /** - * Wrap code within a context and returns back a new function to be executed - * - * @param options A specific set of options for this context - * @param func The function to be wrapped in a new context - * @return The newly wrapped functions with a context - */ - wrap(func: Function): Function; - wrap(options: RavenWrapOptions, func: Function): Function; - wrap(func: T): T; - wrap(options: RavenWrapOptions, func: T): T; - - /** - * Uninstalls the global error handler. - */ - uninstall(): RavenStatic; - - /** - * Manually capture an exception and send it over to Sentry - * - * @param ex An exception to be logged - * @param options A specific set of options for this error - */ - captureException(ex: Error, options?: RavenOptions): RavenStatic; - - /* - * Manually send a message to Sentry - * - * @param msg A plain message to be captured in Sentry - * @param options A specific set of options for this message - */ - captureMessage(msg: string, options?: RavenOptions): RavenStatic; - - /** - * Add a breadcrumb - * @param crumb The trail which should be added to the trail - */ - captureBreadcrumb(crumb: RavenBreadcrumb): RavenStatic; - - /** - * Set a user to be sent along with payloads. - * - * @param user The definition of the currently active user's unique identity - */ - setUserContext(user: RavenUserContext): RavenStatic; - - /** - * Clear the user context, removing the user data that would be sent to Sentry. - */ - setUserContext(): RavenStatic; - - /** - * Add arbitrary data to be sent along with the payload. - * @param extra data of an arbitrary, nested type which will be added - */ - setExtraContext(extra: { [prop: string]: any }): RavenStatic; - - /** - * Add additional tags to be sent along with payloads. - * @param tags A key/value-pair which will be added - */ - setTagsContext(tags: { [id: string]: string }): RavenStatic; - - /** - * Clear the whole currently set context. - */ - clearContext(): RavenStatic; - - /** - * Get a copy of the current context. - */ - getContext(): Object; - - /** - * Set environment of application - * @param environment Typically something like 'production' - */ - setEnvironment(environment: string): RavenStatic; - - /** - * Set release version of application - * @param release Typically something like a git SHA to identify the current version - */ - setRelease(release: string): RavenStatic; - - /** - * Specify a function that can mutate the payload right before it is being sent to Sentry. - * @param callback The function which can mutate the data - */ - setDataCallback(callback: (data: any, orig?: string) => any): RavenStatic; - - /** - * Specify a callback function that can mutate or filter breadcrumbs when they are captured. - * @param callback The function which applies the filter - */ - setBreadcrumbCallback(callback :(data: any, orig?: string) => any): RavenStatic; - - /** - * Specify a callback function that determines if the given message should be sent to Sentry. - * @param callback The function which determines if the given blob should be sent - */ - setShouldSendCallback(callback: (data: any, orig?: string) => boolean): RavenStatic; - - /** - * Override the default HTTP data transport handler. - * @param transport The function which will be invoked to handle the data transmission - */ - setTransport(transport: (options: RavenTransportOptions) => void): RavenStatic; - - /** - * Get the latest raw exception that was captured by Raven. - */ - lastException(): Error; - - /** - * Get the ID of the last Event captured by Raven. - */ - lastEventId(): string; - - /** - * Determine if Raven is setup and ready to go. - */ - isSetup(): boolean; - - /** - * Show the User Feedback Dialog of Sentry - * @param RavenReportDialogOptions Optional Options to set for the User Feedback - */ - showReportDialog(options?: RavenReportDialogOptions): void; -} - - -// --- Helper Interfaces for Options -------------- -export interface RavenBreadcrumOptions { - /** Whether to collect XHR calls, defaults to true */ - xhr?: boolean; - - /** Whether to collect console logs, defaults to true */ - console?: boolean; - - /** Whether to collect dom events, defaults to true */ - dom?: boolean; - - /** Whether to record window location and navigation, defaults to true */ - location?: boolean; -} - -export interface CommonRavenOptions { - /** The environment of the application you are monitoring with Sentry */ - environment?: string; - - /** The release version of the application you are monitoring with Sentry */ - release?: string; - - /** Additional key/value-data to be tagged onto the error. */ - tags?: { [id: string]: string }; - - /** Additional, arbitrary metadata to collect */ - extra?: { [prop: string]: any }; - - /** The name of the logger used by Sentry. Default: javascript */ - logger?: string; - - /** set to true to get the strack trace of your message */ - stacktrace?: boolean; -} - -export interface RavenOptions extends CommonRavenOptions { - /** The name of the server or device that the client is running on */ - server_name?: string; - - /** The log level associated with this event. Default: error */ - level?: string; - - /** 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[]; - - /** Number of frames to trim off the stacktrace. Default: 1 */ - trimHeadFrames?: number; - - /** The name of the device platform. Default: "javascript" */ - platform?: string; -} - -export interface RavenGlobalOptions extends CommonRavenOptions { - /** The name of the server or device that the client is running on */ - serverName?: string; - - /** Configures which breadcrumbs are collected automatically */ - autoBreadcrumbs?: boolean | RavenBreadcrumOptions; - - /** Whether to collect errors on the window via TraceKit.collectWindowErrors. Default: true. */ - collectWindowErrors?: boolean; - - /** Max number of breadcrumbs to collect. Default: 100 */ - maxBreadcrumbs?: number; - - /** Exclude messages which match one of the given RegEx-Patterns from being sent to Sentry. */ - ignoreErrors?: (RegExp | string)[]; - - /** Exclude messages which come from whole urls matching one of the given RegEx patterns. */ - ignoreUrls?: (RegExp | string)[]; - - /** Only report messages which come from whole urls matching one of the given RegEx patterns. */ - whitelistUrls?: (RegExp | string)[]; - - /** An array of RegEx patterns to indicate which urls are a part of your app. */ - includePaths?: (RegExp | string)[]; - - /** Maximum amount of stack frames to collect. Default: Infinity */ - stackTraceLimit?: number; - - /** Override the default HTTP data transport handler. */ - transport?: (options: RavenTransportOptions) => void; - - /** Limit the maxium length of a message to this number of characters. Default: Infinity */ - maxMessageLength?: number; - - /** Allows you to apply your own filters to determine if the message should be sent to Sentry. */ - shouldSendCallback?: (data: any) => boolean; - - /** A function which allows mutation of the data payload right before being sent to Sentry */ - dataCallback?: (data: any) => any; -} - -export interface RavenWrapOptions extends RavenOptions { - /** Whether to run the wrap recursively. Default: false. */ - deep?: boolean; -} - -export interface RavenTransportOptions { - url: string; - data: any; - auth: { - sentry_version: string; - sentry_client: string; - sentry_key: string; - }; - onSuccess: () => void; - onFailure: () => void; -} - -export interface RavenReportDialogOptions { - eventId?: number, - dsn?: string, - user?: { - name?: string, - email?: string - } -} - - -// --- Helper Interfaces for complex Data Structures -------------- -export interface RavenPlugin { - (raven: RavenStatic, ...args: any[]): RavenStatic; -} - -export interface RavenUserContext { - id?: string; - username?: string; - email?: string; - ip_address?: string; - extra?: { [prop: string]: any }; -} - -export interface RavenBreadcrumb { - message: string; - data: { [id: string]: string }; - category: string; - level: string; -} diff --git a/raven-js/raven-js-tests.ts b/raven-js/raven-js-tests.ts deleted file mode 100644 index bbd3285e1e..0000000000 --- a/raven-js/raven-js-tests.ts +++ /dev/null @@ -1,61 +0,0 @@ -import RavenJS from 'raven-js'; - -RavenJS.config('https://public@getsentry.com/1').install(); - - -RavenJS.config( - 'https://public@getsentry.com/1', - { - logger: 'my-logger', - ignoreUrls: [ - /graph\.facebook\.com/i - ], - ignoreErrors: [ - 'fb_xd_fragment' - ], - includePaths: [ - /https?:\/\/(www\.)?getsentry\.com/, - /https?:\/\/d3nslu0hdya83q\.cloudfront\.net/ - ] - } -).install(); - -var throwsError = () => { - throw new Error('broken'); -}; - -try { - throwsError(); -} catch(e) { - RavenJS.captureException(e); - RavenJS.captureException(e, {tags: { key: "value" }}); -} - -RavenJS.context(throwsError); -RavenJS.context({tags: { key: "value" }}, throwsError); -RavenJS.context({extra: {planet: {name: 'Earth'}}}, throwsError); - -setTimeout(RavenJS.wrap(throwsError), 1000); -RavenJS.wrap({logger: "my.module"}, throwsError)(); -RavenJS.wrap({tags: {git_commit: 'c0deb10c4'}}, throwsError)(); - -RavenJS.setUserContext({ - email: 'matt@example.com', - id: '123' -}); - -RavenJS.captureMessage('Broken!'); -RavenJS.captureMessage('Broken!', {tags: { key: "value" }}); - -RavenJS.showReportDialog({ - eventId: 0815, - dsn:'1337asdf', - user: { - name: 'DefenitelyTyped', - email: 'df@ts.ms' - } -}); - -RavenJS.setTagsContext({ key: "value" }); - -RavenJS.setExtraContext({ foo: "bar" }); diff --git a/raw-body/index.d.ts b/raw-body/index.d.ts index 44a9289e6a..bb074bac8e 100644 --- a/raw-body/index.d.ts +++ b/raw-body/index.d.ts @@ -16,11 +16,16 @@ declare namespace getRawBody { */ length?: number | string | null; /** - * The byte limit of the body. This is the number of bytes or any string format supported by `bytes`, for example `1000`, `'500kb'` or `'3mb'`. If the body ends up being larger than this limit, a `413` error code is returned. + * The byte limit of the body. + * This is the number of bytes or any string format supported by `bytes`, for example `1000`, `'500kb'` or `'3mb'`. + * If the body ends up being larger than this limit, a `413` error code is returned. */ limit?: number | string | null; /** - * The encoding to use to decode the body into a string. By default, a `Buffer` instance will be returned when no encoding is specified. Most likely, you want `utf-8`, so setting encoding to `true` will decode as `utf-8`. You can use any type of encoding supported by `iconv-lite`. + * The encoding to use to decode the body into a string. + * By default, a `Buffer` instance will be returned when no encoding is specified. + * Most likely, you want `utf-8`, so setting encoding to `true` will decode as `utf-8`. + * You can use any type of encoding supported by `iconv-lite`. */ encoding?: Encoding | null; } @@ -56,10 +61,15 @@ declare namespace getRawBody { } /** - * Gets the entire buffer of a stream either as a `Buffer` or a string. Validates the stream's length against an expected length and maximum limit. Ideal for parsing request bodies. + * Gets the entire buffer of a stream either as a `Buffer` or a string. + * Validates the stream's length against an expected length and maximum limit. + * Ideal for parsing request bodies. */ declare function getRawBody(stream: Readable, callback: (err: getRawBody.RawBodyError, body: Buffer) => void): void; -declare function getRawBody(stream: Readable, options: (getRawBody.Options & { encoding: getRawBody.Encoding }) | getRawBody.Encoding, callback: (err: getRawBody.RawBodyError, body: string) => void): void; +declare function getRawBody( + stream: Readable, + options: (getRawBody.Options & { encoding: getRawBody.Encoding }) | getRawBody.Encoding, + callback: (err: getRawBody.RawBodyError, body: string) => void): void; declare function getRawBody(stream: Readable, options: getRawBody.Options, callback: (err: getRawBody.RawBodyError, body: Buffer) => void): void; declare function getRawBody(stream: Readable, options: (getRawBody.Options & { encoding: getRawBody.Encoding }) | getRawBody.Encoding): Promise; diff --git a/raw-body/raw-body-tests.ts b/raw-body/raw-body-tests.ts index ad6065537d..8c10f430a5 100644 --- a/raw-body/raw-body-tests.ts +++ b/raw-body/raw-body-tests.ts @@ -13,7 +13,7 @@ const withOptions: Promise = getRawBody(stream, { }); getRawBody(stream, (err, res) => { - if(err) console.error(err); + if (err) console.error(err); else console.log(res); }); @@ -22,6 +22,6 @@ getRawBody(stream, { length: 1024, limit: 512 }, (err, res) => { - if(err) console.error(err); + if (err) console.error(err); else console.log(res); }); diff --git a/rc-tree/index.d.ts b/rc-tree/index.d.ts index 7af51bfe59..54968e6884 100644 --- a/rc-tree/index.d.ts +++ b/rc-tree/index.d.ts @@ -109,7 +109,9 @@ export interface TreeProps extends Props { */ defaultCheckedKeys?: string[]; /** - * Controlled checked treeNodes (After setting, defaultCheckedKeys will not work). Note: parent and children nodes are associated, if the parent node's key exists, it all children node will be checked, and vice versa. When set checkable and checkStrictly, it should be an object, which contains checked array and halfChecked array. + * Controlled checked treeNodes (After setting, defaultCheckedKeys will not work). + * Note: parent and children nodes are associated, if the parent node's key exists, it all children node will be checked, and vice versa. + * When set checkable and checkStrictly, it should be an object, which contains checked array and halfChecked array. */ checkedKeys?: string[] | { checked: string[]; halfChecked: string[] }; /** diff --git a/rc-tree/rc-tree-tests.tsx b/rc-tree/rc-tree-tests.tsx index ce528ba168..857054aa13 100644 --- a/rc-tree/rc-tree-tests.tsx +++ b/rc-tree/rc-tree-tests.tsx @@ -26,7 +26,7 @@ export class Demo extends React.Component { }; } - public static defaultProps: Props = { + static defaultProps: Props = { keys: ['0-0-0-0'], }; diff --git a/react-autosuggest/react-autosuggest-tests.tsx b/react-autosuggest/react-autosuggest-tests.tsx index 0e1a5f922b..3eaee3e4e7 100644 --- a/react-autosuggest/react-autosuggest-tests.tsx +++ b/react-autosuggest/react-autosuggest-tests.tsx @@ -1,8 +1,8 @@ -//region Imports +// region Imports import React = require('react'); import ReactDOM = require('react-dom'); import { Autosuggest, SuggestionSelectedEventData } from 'react-autosuggest'; -//endregion +// endregion interface Language { name: string; @@ -15,8 +15,8 @@ function escapeRegexCharacters(str: string): string { } export class ReactAutosuggestBasicTest extends React.Component { - //region Fields - public static languages: Language[] = [ + // region Fields + static languages: Language[] = [ {name: 'C', year: 1972}, {name: 'C#', year: 2000}, {name: 'C++', year: 1983}, @@ -32,10 +32,10 @@ export class ReactAutosuggestBasicTest extends React.Component { {name: 'Ruby', year: 1995}, {name: 'Scala', year: 2003} ]; - //endregion + // endregion - //region Constructor + // region Constructor constructor(props: any) { super(props); @@ -44,10 +44,10 @@ export class ReactAutosuggestBasicTest extends React.Component { suggestions: this.getSuggestions('') }; } - //endregion + // endregion - //region Rendering methods - public render(): JSX.Element { + // region Rendering methods + render(): JSX.Element { const {value, suggestions} = this.state; const inputProps = { placeholder: `Type 'c'`, @@ -59,7 +59,7 @@ export class ReactAutosuggestBasicTest extends React.Component { input: 'themed-input-class', container: 'themed-container-class', suggestionFocused: 'active' - } + }; return { protected renderSuggestion(suggestion: Language): JSX.Element { return {suggestion.name}; } - //endregion + // endregion - //region Event handlers + // region Event handlers protected onChange(event: React.FormEvent, {newValue, method}: any): void { this.setState({ value: newValue @@ -93,9 +93,9 @@ export class ReactAutosuggestBasicTest extends React.Component { suggestions: this.getSuggestions(value) }); } - //endregion + // endregion - //region Helper methods + // region Helper methods protected getSuggestions(value: string): Language[] { const escapedValue = escapeRegexCharacters(value.trim()); @@ -111,7 +111,7 @@ export class ReactAutosuggestBasicTest extends React.Component { protected getSuggestionValue(suggestion: Language): string { return suggestion.name; } - //endregion + // endregion } ReactDOM.render(, document.getElementById('app')); @@ -122,8 +122,8 @@ interface LanguageGroup { } export class ReactAutosuggestMultipleTest extends React.Component { - //region Fields - public static languages: LanguageGroup[] = [ + // region Fields + static languages: LanguageGroup[] = [ { title: '1970s', languages: [ @@ -164,9 +164,9 @@ export class ReactAutosuggestMultipleTest extends React.Component { ] } ]; - //endregion + // endregion - //region Constructor + // region Constructor constructor(props: any) { super(props); @@ -175,10 +175,10 @@ export class ReactAutosuggestMultipleTest extends React.Component { suggestions: this.getSuggestions('') }; } - //endregion + // endregion - //region Rendering methods - public render(): JSX.Element { + // region Rendering methods + render(): JSX.Element { const { value, suggestions } = this.state; const inputProps = { placeholder: `Type 'c'`, @@ -210,9 +210,9 @@ export class ReactAutosuggestMultipleTest extends React.Component { protected renderSectionTitle(section: LanguageGroup): JSX.Element { return {section.title}; } - //endregion + // endregion - //region Event handlers + // region Event handlers protected onChange(event: React.FormEvent, { newValue, method }: any): void { this.setState({ value: newValue @@ -224,9 +224,9 @@ export class ReactAutosuggestMultipleTest extends React.Component { suggestions: this.getSuggestions(value) }); } - //endregion + // endregion - //region Helper methods + // region Helper methods protected getSuggestions(value: string): LanguageGroup[] { const escapedValue = escapeRegexCharacters(value.trim()); @@ -253,28 +253,28 @@ export class ReactAutosuggestMultipleTest extends React.Component { protected getSectionSuggestions(section: LanguageGroup) { return section.languages; } - //endregion + // endregion } ReactDOM.render(, document.getElementById('app')); -interface IPerson { +interface Person { first: string; last: string; twitter: string; } export class ReactAutosuggestCustomTest extends React.Component { - //region Fields - public static people: IPerson[] = [ + // region Fields + static people: Person[] = [ {first: 'Charlie', last: 'Brown', twitter: 'dancounsell'}, {first: 'Charlotte', last: 'White', twitter: 'mtnmissy'}, {first: 'Chloe', last: 'Jones', twitter: 'ladylexy'}, {first: 'Cooper', last: 'King', twitter: 'steveodom'} ]; - //endregion + // endregion - //region Constructor + // region Constructor constructor(props: any) { super(props); @@ -283,10 +283,10 @@ export class ReactAutosuggestCustomTest extends React.Component { suggestions: this.getSuggestions('') }; } - //endregion + // endregion - //region Rendering methods - public render(): JSX.Element { + // region Rendering methods + render(): JSX.Element { const { value, suggestions } = this.state; const inputProps = { placeholder: "Type 'c'", @@ -301,14 +301,14 @@ export class ReactAutosuggestCustomTest extends React.Component { inputProps={inputProps} />; } - protected renderSuggestion(suggestion: IPerson, { value, valueBeforeUpDown }: any): JSX.Element { + protected renderSuggestion(suggestion: Person, { value, valueBeforeUpDown }: any): JSX.Element { const suggestionText = `${suggestion.first} ${suggestion.last}`; const query = (valueBeforeUpDown || value).trim(); const parts = suggestionText.split(' ').map((part: string) => { return { highlight: (Math.ceil(Math.random() * 10)) % 2, text: part - } + }; }); return @@ -323,9 +323,9 @@ export class ReactAutosuggestCustomTest extends React.Component { ; } - //endregion + // endregion - //region Event handlers + // region Event handlers protected onChange(event: React.FormEvent, {newValue, method}: any): void { this.setState({ value: newValue @@ -337,10 +337,10 @@ export class ReactAutosuggestCustomTest extends React.Component { suggestions: this.getSuggestions(value) }); } - //endregion + // endregion - //region Helper methods - protected getSuggestions(value: string): IPerson[] { + // region Helper methods + protected getSuggestions(value: string): Person[] { const escapedValue = escapeRegexCharacters(value.trim()); if (escapedValue === '') { @@ -352,10 +352,10 @@ export class ReactAutosuggestCustomTest extends React.Component { return ReactAutosuggestCustomTest.people.filter(person => regex.test(this.getSuggestionValue(person))); } - protected getSuggestionValue(suggestion: IPerson): string { + protected getSuggestionValue(suggestion: Person): string { return `${suggestion.first} ${suggestion.last}`; } - //endregion + // endregion } ReactDOM.render(, document.getElementById('app')); diff --git a/react-autosuggest/tslint.json b/react-autosuggest/tslint.json index 192203ab54..377cc837d4 100644 --- a/react-autosuggest/tslint.json +++ b/react-autosuggest/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/react-bootstrap-date-picker/react-bootstrap-date-picker-tests.tsx b/react-bootstrap-date-picker/react-bootstrap-date-picker-tests.tsx index dfc0b12c39..d37cde8fc7 100644 --- a/react-bootstrap-date-picker/react-bootstrap-date-picker-tests.tsx +++ b/react-bootstrap-date-picker/react-bootstrap-date-picker-tests.tsx @@ -1,14 +1,13 @@ -import * as React from "react" -import { DropdownMenu } from "react-bootstrap" -import * as DatePicker from "react-bootstrap-date-picker" +import * as React from "react"; +import { DropdownMenu } from "react-bootstrap"; +import * as DatePicker from "react-bootstrap-date-picker"; const Custom: React.StatelessComponent<{}> = () => { return (
    ); -} +}; class Test extends React.Component<{}, {}> { - - public render () { + render() { return ( {} } @@ -26,7 +25,6 @@ class Test extends React.Component<{}, {}> { showTodayButton={ true } todayButtonLabel="Today" customControl={ Custom } /> - ) + ); } - } diff --git a/react-bootstrap/index.d.ts b/react-bootstrap/index.d.ts index e211264bc7..500babd6cf 100644 --- a/react-bootstrap/index.d.ts +++ b/react-bootstrap/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-bootstrap // Project: https://github.com/react-bootstrap/react-bootstrap -// Definitions by: Walker Burgin , Vincent Siao , Danilo Barros , Batbold Gansukh , Raymond May Jr. +// Definitions by: Walker Burgin , Vincent Siao , Danilo Barros , Batbold Gansukh , Raymond May Jr. , Cheng Sieu Ly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -528,6 +528,7 @@ declare namespace ReactBootstrap { // interface NavbarToggleProps { + onClick?: React.MouseEventHandler; } type NavbarToggle = React.ClassicComponent; var NavbarToggle: React.ClassicComponentClass; @@ -535,7 +536,7 @@ declare namespace ReactBootstrap { // interface NavbarLinkProps { href: string; - onClick?: React.MouseEventHandler<{}>; + onClick?: React.MouseEventHandler; } type NavbarLink = React.ClassicComponent; const NavbarLink: React.ClassicComponentClass; @@ -615,7 +616,7 @@ declare namespace ReactBootstrap { interface TabProps extends React.HTMLProps { animation?: boolean; 'aria-labelledby'?:string; - bsClass?:string; + bsClass?:string; eventKey?: any; // TODO: Add more specific type onEnter?: Function; onEntered?: Function; @@ -766,7 +767,7 @@ declare namespace ReactBootstrap { interface GridProps extends React.HTMLProps { componentClass?: React.ReactType; fluid?: boolean; - bsClass?: string; + bsClass?: string; } type Grid = React.ClassicComponent; var Grid: React.ClassicComponentClass; @@ -866,6 +867,15 @@ declare namespace ReactBootstrap { type Image = React.ClassicComponent; var Image: React.ClassicComponentClass; + // + interface ResponsiveEmbedProps extends React.HTMLProps { + a16by9?: boolean; + a4by3?: boolean; + bsClass?: string; + } + class ResponsiveEmbed extends React.Component { + } + // interface PageHeaderProps extends React.HTMLProps { } diff --git a/react-bootstrap/react-bootstrap-tests.tsx b/react-bootstrap/react-bootstrap-tests.tsx index 00bfae517c..987203fbf8 100644 --- a/react-bootstrap/react-bootstrap-tests.tsx +++ b/react-bootstrap/react-bootstrap-tests.tsx @@ -14,7 +14,7 @@ import { Nav, NavItem, Navbar, NavDropdown, Tabs, Tab, Pager, PageItem, Pagination, Alert, Carousel, SafeAnchor, - Grid, Row, Col, Thumbnail, Image, + Grid, Row, Col, Thumbnail, Image, ResponsiveEmbed, Label, Badge, Jumbotron, PageHeader, Glyphicon, Table, Form, FormGroup, ControlLabel, FormControl, HelpBlock, @@ -528,7 +528,7 @@ export class ReactBootstrapTest extends Component { React-Bootstrap - + {} } />
    +
    +
    + + Embedded Content + + + Embedded Content + + + Embedded Content + +
    +
    +
    Example page header Subtext for header
    @@ -1218,7 +1232,7 @@ export class ReactBootstrapTest extends Component { - +
    @@ -1227,7 +1241,7 @@ export class ReactBootstrapTest extends Component { Help block message. - + 1 {' '} diff --git a/react-color/index.d.ts b/react-color/index.d.ts index bed3ae46ff..798f44d6eb 100644 --- a/react-color/index.d.ts +++ b/react-color/index.d.ts @@ -1,249 +1,58 @@ -// Type definitions for react-color v2.3.4 -// Project: https://casesandberg.github.io/react-color/ +// Type definitions for react-color 2.11 +// Project: https://github.com/casesandberg/react-color/ // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -/// +import { ComponentClass, ClassAttributes, StatelessComponent, ReactNode } from "react"; -declare namespace ReactColor { - interface HSLColor { - a?: number - h: number - l: number - s: number - } - - interface RGBColor { - a?: number - b: number - g: number - r: number - } - - type Color = string | HSLColor | RGBColor - - interface ColorResult { - hex: string - hsl: HSLColor - rgb: RGBColor - } - - type ColorChangeHandler = (color: ColorResult) => void - - interface ColorPickerProps extends React.ClassAttributes { - color?: Color - onChange?: ColorChangeHandler - onChangeComplete?: ColorChangeHandler - } - - /* Predefined pickers */ - interface AlphaPickerProps extends ColorPickerProps { - height?: string - width?: string - } - interface AlphaPicker extends React.ComponentClass {} - const AlphaPicker: AlphaPicker - - interface BlockPickerProps extends ColorPickerProps { - colors?: Array - width?: string - } - interface BlockPicker extends React.ComponentClass {} - const BlockPicker: BlockPicker - - interface ChromePickerProps extends ColorPickerProps { - disableAlpha?: boolean - } - interface ChromePicker extends React.ComponentClass {} - const ChromePicker: ChromePicker - - interface CirclePickerProps extends ColorPickerProps { - colors?: Array - width?: string - } - interface CirclePicker extends React.ComponentClass {} - const CirclePicker: CirclePicker - - interface CompactPickerProps extends ColorPickerProps { - colors?: Array - } - interface CompactPicker extends React.ComponentClass {} - const CompactPicker: CompactPicker - - interface GithubPickerProps extends ColorPickerProps { - colors?: Array - width?: string - } - interface GithubPicker extends React.ComponentClass {} - const GithubPicker: GithubPicker - - interface HuePickerProps extends ColorPickerProps { - height?: string - width?: string - } - interface HuePicker extends React.ComponentClass {} - const HuePicker: HuePicker - - interface MaterialPickerProps extends ColorPickerProps {} - interface MaterialPicker extends React.ComponentClass {} - const MaterialPicker: MaterialPicker - - interface PhotoshopPickerProps extends ColorPickerProps { - header?: string - onAccept?: ColorChangeHandler - onCancel?: ColorChangeHandler - } - interface PhotoshopPicker extends React.ComponentClass {} - const PhotoshopPicker: PhotoshopPicker - - interface SketchPickerProps extends ColorPickerProps { - disableAlpha?: boolean - presetColors?: Array - width?: string - } - interface SketchPicker extends React.ComponentClass {} - const SketchPicker: SketchPicker - - interface SliderPickerProps extends ColorPickerProps {} - interface SliderPicker extends React.ComponentClass {} - const SliderPicker: SliderPicker - - interface SwatchesPickerProps extends ColorPickerProps { - colors?: Array> - height?: number - width?: number - } - interface SwatchesPicker extends React.ComponentClass {} - const SwatchesPicker: SwatchesPicker - - interface TwitterPickerProps extends ColorPickerProps {} - interface TwitterPicker extends React.ComponentClass {} - const TwitterPicker: TwitterPicker - - /* For custom picker */ - interface InjectedColorProps { - hex?: string - hsl?: HSLColor - rgb?: RGBColor - onChange?: ColorChangeHandler - } - - function CustomPicker(component: React.ComponentClass | React.StatelessComponent): React.ComponentClass - - interface CustomPickerProps extends React.ClassAttributes { - color?: Color - pointer?: React.ReactNode - onChange?: ColorChangeHandler - } - - interface AlphaProps extends CustomPickerProps {} - interface Alpha extends React.ComponentClass {} - const Alpha: Alpha - - interface EditableInputStyles { - input?: React.CSSProperties - label?: React.CSSProperties - wrap?: React.CSSProperties - } - interface EditableInputProps extends React.ClassAttributes { - color?: Color - label?: string - onChange?: ColorChangeHandler - styles?: EditableInputStyles - value?: any - } - interface EditableInput extends React.ComponentClass {} - const EditableInput: EditableInput - - interface HueProps extends CustomPickerProps { - direction?: "horizontal" | "vertical" - } - interface Hue extends React.ComponentClass {} - const Hue: Hue - - interface SaturationProps extends CustomPickerProps {} - interface Saturation extends React.ComponentClass {} - const Saturation: Saturation - - interface CheckboardProps extends React.ClassAttributes { - grey?: string - size?: number - white?: string - } - interface Checkboard extends React.ComponentClass {} - const Checkboard: Checkboard +export interface HSLColor { + a?: number; + h: number; + l: number; + s: number; } -declare module "react-color/lib/components/common/Alpha" { export default ReactColor.Alpha } -declare module "react-color/lib/components/common/Checkboard" { export default ReactColor.Checkboard } -declare module "react-color/lib/components/common/EditableInput" { export default ReactColor.EditableInput } -declare module "react-color/lib/components/common/Hue" { export default ReactColor.Hue } -declare module "react-color/lib/components/common/Saturation" { export default ReactColor.Saturation } -declare module "react-color/lib/components/common/ColorWrap" { export default ReactColor.CustomPicker } - -declare module "react-color/lib/components/common" { - import Alpha from "react-color/lib/components/common/Alpha" - import Checkboard from "react-color/lib/components/common/Checkboard" - import EditableInput from "react-color/lib/components/common/EditableInput" - import Hue from "react-color/lib/components/common/Hue" - import Saturation from "react-color/lib/components/common/Saturation" - - export { - Alpha, - Checkboard, - EditableInput, - Hue, - Saturation - } +export interface RGBColor { + a?: number; + b: number; + g: number; + r: number; } -declare module "react-color/lib/components/alpha/Alpha" { export default ReactColor.AlphaPicker } -declare module "react-color/lib/components/block/Block" { export default ReactColor.BlockPicker } -declare module "react-color/lib/components/chrome/Chrome" { export default ReactColor.ChromePicker } -declare module "react-color/lib/components/circle/Circle" { export default ReactColor.CirclePicker } -declare module "react-color/lib/components/compact/Compact" { export default ReactColor.CompactPicker } -declare module "react-color/lib/components/github/Github" { export default ReactColor.GithubPicker } -declare module "react-color/lib/components/hue/Hue" { export default ReactColor.HuePicker } -declare module "react-color/lib/components/meterial/Material" { export default ReactColor.MaterialPicker } -declare module "react-color/lib/components/photoshop/Photoshop" { export default ReactColor.PhotoshopPicker } -declare module "react-color/lib/components/sketch/Sketch" { export default ReactColor.SketchPicker } -declare module "react-color/lib/components/slider/Slider" { export default ReactColor.SliderPicker } -declare module "react-color/lib/components/swatches/Swatches" { export default ReactColor.SwatchesPicker } -declare module "react-color/lib/components/twitter/Twitter" { export default ReactColor.TwitterPicker } +export type Color = string | HSLColor | RGBColor; -declare module "react-color" { - import AlphaPicker from "react-color/lib/components/alpha/Alpha" - import BlockPicker from "react-color/lib/components/block/Block" - import ChromePicker from "react-color/lib/components/chrome/Chrome" - import CirclePicker from "react-color/lib/components/circle/Circle" - import CompactPicker from "react-color/lib/components/compact/Compact" - import GithubPicker from "react-color/lib/components/github/Github" - import HuePicker from "react-color/lib/components/hue/Hue" - import MaterialPicker from "react-color/lib/components/meterial/Material" - import PhotoshopPicker from "react-color/lib/components/photoshop/Photoshop" - import SketchPicker from "react-color/lib/components/sketch/Sketch" - import SliderPicker from "react-color/lib/components/slider/Slider" - import SwatchesPicker from "react-color/lib/components/swatches/Swatches" - import TwitterPicker from "react-color/lib/components/twitter/Twitter" - import CustomPicker from "react-color/lib/components/common/ColorWrap" - - export type CustomPickerProps = ReactColor.CustomPickerProps - - export { - AlphaPicker, - BlockPicker, - ChromePicker, - CirclePicker, - CompactPicker, - GithubPicker, - HuePicker, - MaterialPicker, - PhotoshopPicker, - SketchPicker, - SliderPicker, - SwatchesPicker, - TwitterPicker, - CustomPicker - } +export interface ColorResult { + hex: string; + hsl: HSLColor; + rgb: RGBColor; } + +export type ColorChangeHandler = (color: ColorResult) => void; + +export interface ColorPickerProps extends ClassAttributes { + color?: Color; + onChange?: ColorChangeHandler; + onChangeComplete?: ColorChangeHandler; +} + +export interface CustomPickerProps extends ClassAttributes { + color?: Color; + pointer?: ReactNode; + onChange: ColorChangeHandler; +} + +export { default as AlphaPicker, AlphaPickerProps } from "react-color/lib/components/alpha/Alpha"; +export { default as BlockPicker, BlockPickerProps } from "react-color/lib/components/block/Block"; +export { default as ChromePicker, ChromePickerProps } from "react-color/lib/components/chrome/Chrome"; +export { default as CirclePicker, CirclePickerProps } from "react-color/lib/components/circle/Circle"; +export { default as CompactPicker, CompactPickerProps } from "react-color/lib/components/compact/Compact"; +export { default as GithubPicker, GithubPickerProps } from "react-color/lib/components/github/Github"; +export { default as HuePicker, HuePickerProps } from "react-color/lib/components/hue/Hue"; +export { default as MaterialPicker, MaterialPickerProps } from "react-color/lib/components/material/Material"; +export { default as PhotoshopPicker, PhotoshopPickerProps } from "react-color/lib/components/photoshop/Photoshop"; +export { default as SketchPicker, SketchPickerProps } from "react-color/lib/components/sketch/Sketch"; +export { default as SliderPicker, SliderPickerProps } from "react-color/lib/components/slider/Slider"; +export { default as SwatchesPicker, SwatchesPickerProps } from "react-color/lib/components/swatches/Swatches"; +export { default as TwitterPicker, TwitterPickerProps } from "react-color/lib/components/twitter/Twitter"; +export { default as CustomPicker, InjectedColorProps } from "react-color/lib/components/common/ColorWrap"; diff --git a/react-color/lib/components/alpha/Alpha.d.ts b/react-color/lib/components/alpha/Alpha.d.ts new file mode 100644 index 0000000000..2856f077b9 --- /dev/null +++ b/react-color/lib/components/alpha/Alpha.d.ts @@ -0,0 +1,9 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface AlphaPickerProps extends ColorPickerProps { + height?: string; + width?: string; +} + +export default class AlphaPicker extends Component {} diff --git a/react-color/lib/components/block/Block.d.ts b/react-color/lib/components/block/Block.d.ts new file mode 100644 index 0000000000..edb3c72347 --- /dev/null +++ b/react-color/lib/components/block/Block.d.ts @@ -0,0 +1,9 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface BlockPickerProps extends ColorPickerProps { + colors?: string[]; + width?: string; +} + +export default class BlockPicker extends Component {} diff --git a/react-color/lib/components/chrome/Chrome.d.ts b/react-color/lib/components/chrome/Chrome.d.ts new file mode 100644 index 0000000000..fa214d1b14 --- /dev/null +++ b/react-color/lib/components/chrome/Chrome.d.ts @@ -0,0 +1,8 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface ChromePickerProps extends ColorPickerProps { + disableAlpha?: boolean; +} + +export default class ChromePicker extends Component {} diff --git a/react-color/lib/components/circle/Circle.d.ts b/react-color/lib/components/circle/Circle.d.ts new file mode 100644 index 0000000000..204842d72a --- /dev/null +++ b/react-color/lib/components/circle/Circle.d.ts @@ -0,0 +1,9 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface CirclePickerProps extends ColorPickerProps { + colors?: string[]; + width?: string; +} + +export default class CirclePicker extends Component {} diff --git a/react-color/lib/components/common/Alpha.d.ts b/react-color/lib/components/common/Alpha.d.ts new file mode 100644 index 0000000000..da20010497 --- /dev/null +++ b/react-color/lib/components/common/Alpha.d.ts @@ -0,0 +1,6 @@ +import { Component } from "react"; +import { CustomPickerProps } from "react-color"; + +export type AlphaProps = CustomPickerProps; + +export default class Alpha extends Component {} diff --git a/react-color/lib/components/common/Checkboard.d.ts b/react-color/lib/components/common/Checkboard.d.ts new file mode 100644 index 0000000000..40d8f26913 --- /dev/null +++ b/react-color/lib/components/common/Checkboard.d.ts @@ -0,0 +1,9 @@ +import { Component, ClassAttributes } from "react"; + +export interface CheckboardProps extends ClassAttributes { + grey?: string; + size?: number; + white?: string; +} + +export default class Checkboard extends Component {} diff --git a/react-color/lib/components/common/ColorWrap.d.ts b/react-color/lib/components/common/ColorWrap.d.ts new file mode 100644 index 0000000000..94a8f5b789 --- /dev/null +++ b/react-color/lib/components/common/ColorWrap.d.ts @@ -0,0 +1,11 @@ +import { ComponentClass, StatelessComponent } from "react"; +import { HSLColor, RGBColor, ColorChangeHandler } from "react-color"; + +export interface InjectedColorProps { + hex?: string; + hsl?: HSLColor; + rgb?: RGBColor; + onChange?: ColorChangeHandler; +} + +export default function CustomPicker(component: ComponentClass | StatelessComponent): ComponentClass; diff --git a/react-color/lib/components/common/EditableInput.d.ts b/react-color/lib/components/common/EditableInput.d.ts new file mode 100644 index 0000000000..78df9473f2 --- /dev/null +++ b/react-color/lib/components/common/EditableInput.d.ts @@ -0,0 +1,19 @@ +import { Component, ClassAttributes, CSSProperties } from "react"; +import { Color, ColorChangeHandler } from "react-color"; + +export interface EditableInputStyles { + input?: CSSProperties; + label?: CSSProperties; + wrap?: CSSProperties; +} + +export interface EditableInputProps extends ClassAttributes { + color?: Color; + label?: string; + onChange?: ColorChangeHandler; + styles?: EditableInputStyles; + value?: any; +} + +export default class EditableInput extends Component {} + diff --git a/react-color/lib/components/common/Hue.d.ts b/react-color/lib/components/common/Hue.d.ts new file mode 100644 index 0000000000..1f61841107 --- /dev/null +++ b/react-color/lib/components/common/Hue.d.ts @@ -0,0 +1,8 @@ +import { Component } from "react"; +import { CustomPickerProps } from "react-color"; + +export interface HueProps extends CustomPickerProps { + direction?: "horizontal" | "vertical"; +} + +export default class Hue extends Component {} diff --git a/react-color/lib/components/common/Saturation.d.ts b/react-color/lib/components/common/Saturation.d.ts new file mode 100644 index 0000000000..c90a7d9685 --- /dev/null +++ b/react-color/lib/components/common/Saturation.d.ts @@ -0,0 +1,6 @@ +import { Component } from "react"; +import { CustomPickerProps } from "react-color"; + +export type SaturationProps = CustomPickerProps; + +export default class Saturation extends Component {} diff --git a/react-color/lib/components/common/index.d.ts b/react-color/lib/components/common/index.d.ts new file mode 100644 index 0000000000..ed5af44bdf --- /dev/null +++ b/react-color/lib/components/common/index.d.ts @@ -0,0 +1,5 @@ +export { default as Alpha } from "react-color/lib/components/common/Alpha"; +export { default as Checkboard } from "react-color/lib/components/common/Checkboard"; +export { default as EditableInput } from "react-color/lib/components/common/EditableInput"; +export { default as Hue } from "react-color/lib/components/common/Hue"; +export { default as Saturation } from "react-color/lib/components/common/Saturation"; diff --git a/react-color/lib/components/compact/Compact.d.ts b/react-color/lib/components/compact/Compact.d.ts new file mode 100644 index 0000000000..3f9ff74f60 --- /dev/null +++ b/react-color/lib/components/compact/Compact.d.ts @@ -0,0 +1,8 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface CompactPickerProps extends ColorPickerProps { + colors?: string[]; +} + +export default class CompactPicker extends Component {} diff --git a/react-color/lib/components/github/Github.d.ts b/react-color/lib/components/github/Github.d.ts new file mode 100644 index 0000000000..fd1479abad --- /dev/null +++ b/react-color/lib/components/github/Github.d.ts @@ -0,0 +1,9 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface GithubPickerProps extends ColorPickerProps { + colors?: string[]; + width?: string; +} + +export default class GithubPicker extends Component {} diff --git a/react-color/lib/components/hue/Hue.d.ts b/react-color/lib/components/hue/Hue.d.ts new file mode 100644 index 0000000000..6aab83baea --- /dev/null +++ b/react-color/lib/components/hue/Hue.d.ts @@ -0,0 +1,9 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface HuePickerProps extends ColorPickerProps { + height?: string; + width?: string; +} + +export default class HuePicker extends Component {} diff --git a/react-color/lib/components/material/Material.d.ts b/react-color/lib/components/material/Material.d.ts new file mode 100644 index 0000000000..4ae849b910 --- /dev/null +++ b/react-color/lib/components/material/Material.d.ts @@ -0,0 +1,6 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export type MaterialPickerProps = ColorPickerProps; + +export default class MaterialPicker extends Component {} diff --git a/react-color/lib/components/photoshop/Photoshop.d.ts b/react-color/lib/components/photoshop/Photoshop.d.ts new file mode 100644 index 0000000000..c3abaf0ccd --- /dev/null +++ b/react-color/lib/components/photoshop/Photoshop.d.ts @@ -0,0 +1,10 @@ +import { Component } from "react"; +import { ColorChangeHandler, ColorPickerProps } from "react-color"; + +export interface PhotoshopPickerProps extends ColorPickerProps { + header?: string; + onAccept?: ColorChangeHandler; + onCancel?: ColorChangeHandler; +} + +export default class PhotoshopPicker extends Component {} diff --git a/react-color/lib/components/sketch/Sketch.d.ts b/react-color/lib/components/sketch/Sketch.d.ts new file mode 100644 index 0000000000..229b2b2b51 --- /dev/null +++ b/react-color/lib/components/sketch/Sketch.d.ts @@ -0,0 +1,10 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface SketchPickerProps extends ColorPickerProps { + disableAlpha?: boolean; + presetColors?: string[]; + width?: string; +} + +export default class SketchPicker extends Component {} diff --git a/react-color/lib/components/slider/Slider.d.ts b/react-color/lib/components/slider/Slider.d.ts new file mode 100644 index 0000000000..913f30692a --- /dev/null +++ b/react-color/lib/components/slider/Slider.d.ts @@ -0,0 +1,6 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export type SliderPickerProps = ColorPickerProps; + +export default class SliderPicker extends Component {} diff --git a/react-color/lib/components/swatches/Swatches.d.ts b/react-color/lib/components/swatches/Swatches.d.ts new file mode 100644 index 0000000000..22e9d1704c --- /dev/null +++ b/react-color/lib/components/swatches/Swatches.d.ts @@ -0,0 +1,10 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface SwatchesPickerProps extends ColorPickerProps { + colors?: string[][]; + height?: number; + width?: number; +} + +export default class SwatchesPicker extends Component {} diff --git a/react-color/lib/components/twitter/Twitter.d.ts b/react-color/lib/components/twitter/Twitter.d.ts new file mode 100644 index 0000000000..b4e6bb2308 --- /dev/null +++ b/react-color/lib/components/twitter/Twitter.d.ts @@ -0,0 +1,6 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export type TwitterPickerProps = ColorPickerProps; + +export default class TwitterPicker extends Component {} diff --git a/react-color/react-color-tests.tsx b/react-color/react-color-tests.tsx index 7969047569..e4e6f2348b 100644 --- a/react-color/react-color-tests.tsx +++ b/react-color/react-color-tests.tsx @@ -5,16 +5,19 @@ import { AlphaPicker, BlockPicker, ChromePicker, CirclePicker, CompactPicker, GithubPicker, HuePicker, MaterialPicker, PhotoshopPicker, SketchPicker, SliderPicker, SwatchesPicker, - TwitterPicker, CustomPicker + TwitterPicker, CustomPicker, InjectedColorProps, ColorResult, + Color } from "react-color" import { Alpha, Checkboard, EditableInput, Hue, Saturation } from "react-color/lib/components/common" -interface CustomProps extends ReactColor.InjectedColorProps { - color?: ReactColor.Color +interface CustomProps extends InjectedColorProps { + color?: Color } var CustomComponent: StatelessComponent = (props: CustomProps) => { - function onChange (color: ReactColor.ColorResult) {} + function onChange (color: ColorResult) { + console.log(color) + } return (
    diff --git a/react-color/tsconfig.json b/react-color/tsconfig.json index a88182ffbc..26e01d85c6 100644 --- a/react-color/tsconfig.json +++ b/react-color/tsconfig.json @@ -15,10 +15,32 @@ "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true, - "jsx": "react" + "jsx": "react", + "noUnusedParameters": true, + "noUnusedLocals": true }, "files": [ "index.d.ts", + "lib/components/alpha/Alpha.d.ts", + "lib/components/block/Block.d.ts", + "lib/components/chrome/Chrome.d.ts", + "lib/components/circle/Circle.d.ts", + "lib/components/common/Alpha.d.ts", + "lib/components/common/Checkboard.d.ts", + "lib/components/common/ColorWrap.d.ts", + "lib/components/common/EditableInput.d.ts", + "lib/components/common/Hue.d.ts", + "lib/components/common/index.d.ts", + "lib/components/common/Saturation.d.ts", + "lib/components/compact/Compact.d.ts", + "lib/components/github/Github.d.ts", + "lib/components/hue/Hue.d.ts", + "lib/components/material/Material.d.ts", + "lib/components/photoshop/Photoshop.d.ts", + "lib/components/sketch/Sketch.d.ts", + "lib/components/slider/Slider.d.ts", + "lib/components/swatches/Swatches.d.ts", + "lib/components/twitter/Twitter.d.ts", "react-color-tests.tsx" ] -} \ No newline at end of file +} diff --git a/react-color/tslint.json b/react-color/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/react-color/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/react-css-modules/index.d.ts b/react-css-modules/index.d.ts index d709a69d73..d569850f99 100644 --- a/react-css-modules/index.d.ts +++ b/react-css-modules/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/gajus/react-css-modules // Definitions by: Kostya Esmukov , Tadas Dailyda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 interface TypeOptions { allowMultiple?: boolean; diff --git a/react-dates/index.d.ts b/react-dates/index.d.ts new file mode 100644 index 0000000000..e3ca801887 --- /dev/null +++ b/react-dates/index.d.ts @@ -0,0 +1,364 @@ +// Type definitions for react-dates v7.0.1 +// Project: https://github.com/airbnb/react-dates +// Definitions by: Artur Ampilogov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import * as React from "react"; +import * as moment from "moment"; + +export = ReactDates; + +declare namespace momentPropTypes{ + type momentObj = any; + type momentString = any; + type momentDurationObj = any; +} + + +declare namespace ReactDates{ + type AnchorDirectionShape = 'left' | 'right'; + type FocusedInputShape = 'startDate' | 'endDate'; + type OrientationShape = 'horizontal' | 'vertical'; + type ScrollableOrientationShape = 'horizontal' | 'vertical' | 'verticalScrollable'; + + + interface DateRangePickerShape{ + startDate?: momentPropTypes.momentObj, + endDate?: momentPropTypes.momentObj, + focusedInput?: FocusedInputShape, + screenReaderInputMessage?: string, + minimumNights?: number, + isDayBlocked?: (day: any) => boolean, + isOutsideRange?: (day: any) => boolean, + enableOutsideDays?: boolean, + reopenPickerOnClearDates?: boolean, + keepOpenOnDateSelect?: boolean, + numberOfMonths?: number, + showClearDates?: boolean, + disabled?: boolean, + required?: boolean, + showDefaultInputIcon?: boolean, + + orientation?: OrientationShape, + anchorDirection?: AnchorDirectionShape, + horizontalMargin?: number, + // portal options + withPortal?: boolean, + withFullScreenPortal?: boolean, + + startDateId?: string, + startDatePlaceholderText?: string, + endDateId?: string, + endDatePlaceholderText?: string, + + initialVisibleMonth?: () => moment.Moment, + onDatesChange?: (arg: { startDate: any, endDate: any }) => void, + onFocusChange?: (arg: FocusedInputShape) => void, + onPrevMonthClick?: (e: React.EventHandler>) => void, + onNextMonthClick?: (e: React.EventHandler>) => void, + + renderDay?: (day: any) => (string | JSX.Element), + + // i18n + displayFormat?: (string | (()=> string)), + monthFormat?: string, + phrases?: { + closeDatePicker: string | JSX.Element, + clearDates: string | JSX.Element, + } + } + + type DateRangePicker = React.ClassicComponentClass; + var DateRangePicker: React.ClassicComponentClass; + + interface SingleDatePickerShape{ + id: string, + placeholder?: string, + date?: momentPropTypes.momentObj, + focused?: boolean, + showClearDate?: boolean, + reopenPickerOnClearDates?: boolean, + keepOpenOnDateSelect?: boolean, + disabled?: boolean, + required?: boolean, + screenReaderInputMessage?: string, + + onDateChange?: (date: any) => void, + onFocusChange?: (arg: { focused: boolean | null }) => void, + + isDayBlocked?: (day: any) => boolean, + isOutsideRange?: (day: any) => boolean, + enableOutsideDays?: boolean, + numberOfMonths?: number, + orientation?: OrientationShape, + initialVisibleMonth?: () => moment.Moment, + anchorDirection?: AnchorDirectionShape, + horizontalMargin?: number, + + navPrev?: string | JSX.Element, + navNext?: string | JSX.Element, + + // portal options + withPortal?: boolean, + withFullScreenPortal?: boolean, + + onPrevMonthClick?: (e: React.EventHandler>) => void, + onNextMonthClick?: (e: React.EventHandler>) => void, + + renderDay?: (day: any) => (string | JSX.Element), + + // i18n + displayFormat?: (string | (()=> string)), + monthFormat?: string, + phrases?: { + closeDatePicker: string | JSX.Element, + }, + } + type SingleDatePicker = React.ClassicComponentClass; + var SingleDatePicker: React.ClassicComponentClass; + + + + interface DateRangePickerInputControllerShape { + startDate?: momentPropTypes.momentObj, + startDateId?: string, + startDatePlaceholderText?: string, + isStartDateFocused?: boolean, + + endDate?: momentPropTypes.momentObj, + endDateId?: string, + endDatePlaceholderText?: string, + isEndDateFocused?: boolean, + + screenReaderMessage?: string, + showClearDates?: boolean, + showCaret?: boolean, + showDefaultInputIcon?: boolean, + disabled?: boolean, + required?: boolean, + + keepOpenOnDateSelect?: boolean, + reopenPickerOnClearDates?: boolean, + withFullScreenPortal?: boolean, + isOutsideRange?: (day: any) => boolean, + displayFormat?: (string | (()=> string)), + + onFocusChange?: (arg: FocusedInputShape) => void, + onDatesChange?: (arg: { startDate: any, endDate: any }) => void, + + customInputIcon?: string | JSX.Element, + customArrowIcon?: string | JSX.Element, + + // i18n + phrases?: { + clearDates: string | JSX.Element, + } + } + type DateRangePickerInputController = React.ClassicComponentClass; + var DateRangePickerInputController: React.ClassicComponentClass; + + + + interface DateRangePickerInputShape{ + startDateId?: string, + startDatePlaceholderText?: string, + screenReaderMessage?: string, + + endDateId?: string, + endDatePlaceholderText?: string, + + onStartDateFocus?: (e: React.EventHandler>) => void, + onEndDateFocus?: (e: React.EventHandler>) => void, + onStartDateChange?: (e: React.EventHandler>) => void, + onEndDateChange?: (e: React.EventHandler>) => void, + onStartDateShiftTab?: (e: React.EventHandler>) => void, + onEndDateTab?: (e: React.EventHandler>) => void, + onClearDates?: (e: React.EventHandler>) => void, + + startDate?: string, + startDateValue?: string, + endDate?: string, + endDateValue?: string, + + isStartDateFocused?: boolean, + isEndDateFocused?: boolean, + showClearDates?: boolean, + disabled?: boolean, + required?: boolean, + showCaret?: boolean, + showDefaultInputIcon?: boolean, + customInputIcon?: string | JSX.Element, + customArrowIcon?: string | JSX.Element, + + // i18n + phrases?:{ + clearDates: string | JSX.Element, + }, + } + type DateRangePickerInput = React.ClassicComponentClass; + var DateRangePickerInput: React.ClassicComponentClass; + + + + interface SingleDatePickerInputShape{ + id: string, + placeholder?: string, // also used as label + displayValue?: string, + inputValue?: string, + screenReaderMessage?: string, + focused?: boolean, + disabled?: boolean, + required?: boolean, + showCaret?: boolean, + showClearDate?: boolean, + + onChange?: (e: React.EventHandler>) => void, + onClearDate?: (e: React.EventHandler>) => void, + onFocus?: (e: React.EventHandler>) => void, + onKeyDownShiftTab?: (e: React.EventHandler>) => void, + onKeyDownTab?: (e: React.EventHandler>) => void, + + // i18n + phrases?: { + clearDate: string | JSX.Element, + } + } + type SingleDatePickerInput = React.ClassicComponentClass; + var SingleDatePickerInput: React.ClassicComponentClass; + + + + + interface DayPickerShape{ + enableOutsideDays?: boolean, + numberOfMonths?: number, + modifiers?: any, + orientation?: ScrollableOrientationShape, + withPortal?: boolean, + hidden?: boolean, + initialVisibleMonth?: () => moment.Moment, + + navPrev?: string | JSX.Element, + navNext?: string | JSX.Element, + + onDayClick?: (day: any, e: React.EventHandler>) => void, + onDayMouseEnter?: (day: any, e: React.EventHandler>) => void, + onDayMouseLeave?: (day: any, e: React.EventHandler>) => void, + onPrevMonthClick?: (e: React.EventHandler>) => void, + onNextMonthClick?: (e: React.EventHandler>) => void, + onOutsideClick?: (e: MouseEvent) => void, + + renderDay?: (day: any) => (string | JSX.Element), + + // i18n + monthFormat?: string, + } + type DayPicker = React.ClassicComponentClass; + var DayPicker: React.ClassicComponentClass; + + + + interface DayPickerRangeControllerShape{ + startDate?: momentPropTypes.momentObj, + endDate?: momentPropTypes.momentObj, + onDatesChange?: (arg: { startDate: any, endDate: any }) => void, + + focusedInput?: FocusedInputShape, + onFocusChange?: (arg: FocusedInputShape) => void, + + keepOpenOnDateSelect?: boolean, + minimumNights?: number, + isOutsideRange?: (day: any) => boolean, + isDayBlocked?: (day: any) => boolean, + isDayHighlighted?: (day: any) => boolean, + + // DayPicker props + enableOutsideDays?: boolean, + numberOfMonths?: number, + orientation?: ScrollableOrientationShape, + withPortal?: boolean, + hidden?: boolean, + initialVisibleMonth?: () => moment.Moment, + + navPrev?: string | JSX.Element, + navNext?: string | JSX.Element, + + onPrevMonthClick?: (e: React.EventHandler>) => void, + onNextMonthClick?: (e: React.EventHandler>) => void, + onOutsideClick?: (e: MouseEvent) => void, + renderDay?: (day: any) => (string | JSX.Element), + + // i18n + monthFormat?: string, + } + type DayPickerRangeController = React.ClassicComponentClass; + var DayPickerRangeController: React.ClassicComponentClass; + + + interface CalendarMonthGridShape{ + enableOutsideDays?: boolean, + firstVisibleMonthIndex?: number, + initialMonth?: momentPropTypes.momentObj, + isAnimating?: boolean, + numberOfMonths?: number, + modifiers?: any, + orientation?: ScrollableOrientationShape, + onDayClick?: (day: any, e: React.EventHandler>) => void, + onDayMouseEnter?: (day: any, e: React.EventHandler>) => void, + onDayMouseLeave?: (day: any, e: React.EventHandler>) => void, + onMonthTransitionEnd?: ()=> void, + renderDay?: (day: any) => (string | JSX.Element), + transformValue?: string, + + // i18n + monthFormat?: string, + } + type CalendarMonthGrid = React.ClassicComponentClass; + var CalendarMonthGrid: React.ClassicComponentClass; + + + + interface CalendarMonthShape{ + month?: momentPropTypes.momentObj, + isVisible?: boolean, + enableOutsideDays?: boolean, + modifiers?: any, + orientation?: ScrollableOrientationShape, + onDayClick?: (day: any, e: React.EventHandler>) => void, + onDayMouseEnter?: (day: any, e: React.EventHandler>) => void, + onDayMouseLeave?: (day: any, e: React.EventHandler>) => void, + renderDay?: (day: any) => (string | JSX.Element), + + // i18n + monthFormat?: string, + } + type CalendarMonth = React.ClassicComponentClass; + var CalendarMonth: React.ClassicComponentClass; + + + interface CalendarDayShape{ + day?: momentPropTypes.momentObj, + isOutsideDay?: boolean, + modifiers?: any, + onDayClick?: (day: any, e: React.EventHandler>) => void, + onDayMouseEnter?: (day: any, e: React.EventHandler>) => void, + onDayMouseLeave?: (day: any, e: React.EventHandler>) => void, + renderDay?: (day: any) => (string | JSX.Element), + } + type CalendarDay = React.ClassicComponentClass; + var CalendarDay: React.ClassicComponentClass; + + + + + var isInclusivelyAfterDay: (a: moment.Moment, b: moment.Moment) => boolean; + var isInclusivelyBeforeDay: (a: moment.Moment, b: moment.Moment) => boolean; + var isNextDay: (a: moment.Moment, b: moment.Moment) => boolean; + var isSameDay: (a: moment.Moment, b: moment.Moment) => boolean; + + var toISODateString: (date: moment.MomentInput, currentFormat: moment.MomentFormatSpecification) => string | null; + var toLocalizedDateString: (date: moment.MomentInput, currentFormat: moment.MomentFormatSpecification) => string | null; + + var toMomentObject: (dateString: moment.MomentInput, customFormat: moment.MomentFormatSpecification) => moment.Moment | null; +} diff --git a/react-dates/package.json b/react-dates/package.json new file mode 100644 index 0000000000..d5ac741601 --- /dev/null +++ b/react-dates/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "moment": ">=2.17.1" + } +} \ No newline at end of file diff --git a/react-dates/react-dates-tests.tsx b/react-dates/react-dates-tests.tsx new file mode 100644 index 0000000000..b975b1124b --- /dev/null +++ b/react-dates/react-dates-tests.tsx @@ -0,0 +1,357 @@ +import * as React from "react"; +import * as moment from "moment"; + +import { + CalendarDay, + CalendarMonth, + CalendarMonthGrid, + SingleDatePickerInput, + SingleDatePicker, + DayPicker, + DayPickerRangeController, + DateRangePickerInput, + DateRangePickerInputController, + DateRangePicker, + isInclusivelyAfterDay, + isInclusivelyBeforeDay, + isNextDay, + isSameDay, + toISODateString, + toLocalizedDateString, + toMomentObject} from "react-dates"; + + +class CalendarDayRenderingMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class CalendarDayRenderingFullTest extends React.Component<{}, {}> { + render() { + return day.toString()} + onDayClick={(day,e) => {}} + onDayMouseEnter={(day,e) => {}} + onDayMouseLeave={(day,e) => {}} + /> + } +} + +class CalendarMonthMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class CalendarMonthFullTest extends React.Component<{}, {}> { + render() { + return day.toString()} + onDayClick={(day,e) => {}} + onDayMouseEnter={(day,e) => {}} + onDayMouseLeave={(day,e) => {}} + /> + } +} + + + + +class SingleDatePickerInputMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class SingleDatePickerInputFullTest extends React.Component<{}, {}> { + render() { + return {}} + onClearDate={e => {}} + onFocus={e => {}} + onKeyDownShiftTab={e => {}} + onKeyDownTab={e => {}} + phrases={{clearDate: "clear"}} + placeholder="test" + required={false} + screenReaderMessage="arial-test" + showCaret={true} + showClearDate={true} + /> + } +} + + + + +class SingleDatePickerMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class SingleDatePickerFullTest extends React.Component<{}, {}> { + render() { + return moment()} + placeholder="test" + required={false} + showClearDate={true} + isDayBlocked={(day:any)=> false} + isOutsideRange={(day:any)=> false} + keepOpenOnDateSelect={true} + navNext="next" + navPrev="prev" + withPortal={false} + onDateChange={d => {}} + focused={false} + phrases={{closeDatePicker: Close}} + reopenPickerOnClearDates={true} + screenReaderInputMessage="arial-test" + withFullScreenPortal={true} + onFocusChange={arg => {}} + onNextMonthClick={e => {}} + onPrevMonthClick={e => {}} + numberOfMonths={2} + orientation="horizontal" + monthFormat="MM" + renderDay={day => day.toString()} + /> + } +} + + + +class DayPickerRangeControllerMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class DayPickerRangeControllerFullTest extends React.Component<{}, {}> { + render() { + return moment()} + hidden={false} + isDayBlocked={(day:any)=> false} + isDayHighlighted={(day:any)=> false} + isOutsideRange={(day:any)=> false} + keepOpenOnDateSelect={true} + minimumNights={3} + navNext="next" + navPrev="prev" + withPortal={false} + onDatesChange={arg => {}} + onFocusChange={arg => {}} + onNextMonthClick={e => {}} + onPrevMonthClick={e => {}} + onOutsideClick={e => {}} + enableOutsideDays={true} + numberOfMonths={2} + orientation="horizontal" + monthFormat="MM" + renderDay={day => day.toString()} + /> + } +} + + +class DayPickerTest extends React.Component<{}, {}> { + render() { + return + } +} + +class DayPickerFullTest extends React.Component<{}, {}> { + render() { + return {}} + onDayMouseEnter={(day,e)=>{}} + onDayMouseLeave={(day,e)=>{}} + initialVisibleMonth={() => moment()} + hidden={false} + navNext="next" + navPrev="prev" + withPortal={false} + onNextMonthClick={e => {}} + onPrevMonthClick={e => {}} + onOutsideClick={e => {}} + enableOutsideDays={true} + numberOfMonths={2} + orientation="horizontal" + monthFormat="MM" + renderDay={day => day.toString()} + /> + } +} + + + + +class DateRangePickerInputMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class DateRangePickerInputFullTest extends React.Component<{}, {}> { + render() { + return {}} + onEndDateChange={e => {}} + onEndDateFocus={e => {}} + onEndDateTab={e => {}} + onStartDateChange={e => {}} + onStartDateFocus={e => {}} + onStartDateShiftTab={e => {}} + showDefaultInputIcon={true} + required={false} + screenReaderMessage="arial-test" + showCaret={true} + showClearDates={true} + phrases={{clearDates: "clear"}} + /> + } +} + + + + + +class DateRangePickerInputControllerMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class DateRangePickerInputControllerFullTest extends React.Component<{}, {}> { + render() { + return {}} + onEndDateChange={e => {}} + onEndDateFocus={e => {}} + onEndDateTab={e => {}} + onStartDateChange={e => {}} + onStartDateFocus={e => {}} + onStartDateShiftTab={e => {}} + showDefaultInputIcon={true} + required={false} + screenReaderMessage="arial-test" + showCaret={true} + showClearDates={true} + phrases={{clearDates: "clear"}} + startDate="1.1.2020" + endDate="1.1.2020" + /> + } +} + + + + + + + + + + + +class DateRangePickerMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class DateRangePickerFullTest extends React.Component<{}, {}> { + render() { + return {arg.startDate; arg.endDate;}} + displayFormat="dd.mm.yyyy" + enableOutsideDays={true} + horizontalMargin={20} + initialVisibleMonth={() => moment()} + isDayBlocked={(day:any)=> false} + isOutsideRange={(day:any)=> false} + keepOpenOnDateSelect={true} + withPortal={false} + reopenPickerOnClearDates={true} + screenReaderInputMessage="arial-test" + withFullScreenPortal={true} + onFocusChange={arg => {}} + onNextMonthClick={e => {}} + onPrevMonthClick={e => {}} + numberOfMonths={2} + orientation="horizontal" + monthFormat="MM" + renderDay={day => day.toString()} + /> + } +} + + +const isInclusivelyAfterDayResult: boolean = isInclusivelyAfterDay(moment(),moment()); +const isInclusivelyBeforeDayResult: boolean = isInclusivelyBeforeDay(moment(),moment()); +const isNextDayDayResult: boolean = isNextDay(moment(),moment()); +const isSameDayResult: boolean = isSameDay(moment(),moment()); +const toISODateStringResult: string | null = toISODateString(moment(), "dd.mm.yyyy"); +const toLocalizedDateStringResult: string | null = toLocalizedDateString(moment(), "dd.mm.yyyy"); +const toMomentObjectResult: moment.Moment | null = toMomentObject(moment(), "dd.mm.yyyy"); + + \ No newline at end of file diff --git a/react-dates/tsconfig.json b/react-dates/tsconfig.json new file mode 100644 index 0000000000..7d246baede --- /dev/null +++ b/react-dates/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-dates-tests.tsx" + ] +} diff --git a/react-dnd-html5-backend/react-dnd-html5-backend-tests.ts b/react-dnd-html5-backend/react-dnd-html5-backend-tests.ts index 670790c46a..83ee1bc9ba 100644 --- a/react-dnd-html5-backend/react-dnd-html5-backend-tests.ts +++ b/react-dnd-html5-backend/react-dnd-html5-backend-tests.ts @@ -120,7 +120,7 @@ namespace Square { style: { backgroundColor: fill } - }) + }); } } @@ -168,7 +168,7 @@ namespace BoardSquare { backgroundColor: color } }); - }; + } render() { var black = (this.props.x + this.props.y) % 2 === 1; @@ -183,9 +183,7 @@ namespace BoardSquare { height: '100%' }, children: [ - Square.create({ - black: black - }), + Square.create({ black }), isOver && !canDrop ? this._renderOverlay('red') : null, !isOver && canDrop ? this._renderOverlay('yellow') : null, isOver && canDrop ? this._renderOverlay('green') : null @@ -204,7 +202,7 @@ namespace BoardSquare { namespace CustomDragLayer { interface CustomDragLayerP extends React.Props { isDragging?: boolean; - item?: Object; + item?: {}; } function dragLayerCollect(monitor: ReactDnd.DragLayerMonitor) { @@ -240,7 +238,7 @@ namespace Board { return x === knightX && y === knightY ? Knight.create() : null; - }; + } private _renderSquare = (i: number) => { var x = i % 8; @@ -252,14 +250,11 @@ namespace Board { width: '12.5%', height: '12.5%' } - }, BoardSquare.create({ - x: x, - y: y - }, this._renderPiece(x, y))); - }; + }, BoardSquare.create({ x, y }, this._renderPiece(x, y))); + } render() { - var squares: React.ReactHTMLElement[] = []; + var squares: Array> = []; for (let i = 0; i < 64; i++) { squares.push(this._renderSquare(i)); } diff --git a/react-dnd-html5-backend/tslint.json b/react-dnd-html5-backend/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/react-dnd-html5-backend/tslint.json +++ b/react-dnd-html5-backend/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/react-event-listener/react-event-listener-tests.tsx b/react-event-listener/react-event-listener-tests.tsx index 194ab97e7f..91c48b1047 100644 --- a/react-event-listener/react-event-listener-tests.tsx +++ b/react-event-listener/react-event-listener-tests.tsx @@ -3,4 +3,4 @@ import EventListener, { withOptions } from "react-event-listener"; { }} />; { }, { passive: true, capture: true })} />; - { }}/> + { }}/>; diff --git a/react-facebook-login/react-facebook-login-tests.tsx b/react-facebook-login/react-facebook-login-tests.tsx index 0a57b598fe..7f0d89ea8f 100644 --- a/react-facebook-login/react-facebook-login-tests.tsx +++ b/react-facebook-login/react-facebook-login-tests.tsx @@ -93,7 +93,7 @@ class MyComponent2 extends React.Component { fields="name,email,picture" callback={responseFacebook} /> - ) + ); } } diff --git a/react-facebook-login/tsconfig.json b/react-facebook-login/tsconfig.json index 6803f928e3..e2bcecb743 100644 --- a/react-facebook-login/tsconfig.json +++ b/react-facebook-login/tsconfig.json @@ -1,6 +1,10 @@ { "compilerOptions": { "module": "commonjs", + "lib": [ + "es6", + "dom" + ], "target": "es6", "jsx": "react", "noImplicitAny": true, diff --git a/react-facebook-login/tslint.json b/react-facebook-login/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/react-facebook-login/tslint.json +++ b/react-facebook-login/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/react-fontawesome/index.d.ts b/react-fontawesome/index.d.ts index 76568cc43e..d866eddfad 100644 --- a/react-fontawesome/index.d.ts +++ b/react-fontawesome/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for react-fontawesome 1.1 +// Type definitions for react-fontawesome 1.5.0 // Project: https://github.com/danawoodman/react-fontawesome -// Definitions by: Timur Rustamov +// Definitions by: Timur Rustamov , Anton Kandybo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -10,21 +10,24 @@ declare module "react-fontawesome" { import React = require('react'); type FontAwesomeSize = 'lg' | '2x' | '3x' | '4x' | '5x'; + type FontAwesomeStack = "1x" | "2x"; + type FontAwesomeFlip = "horizontal" | "vertical"; interface FontAwesomeProps { - + ariaLabel?: string, border?: boolean, className?: string, + cssModule?: any, fixedWidth?: boolean, - flip?: boolean, - inverse?: boolean + flip?: FontAwesomeFlip, + inverse?: boolean, name: string, pulse?: boolean, rotate?: number, size?: FontAwesomeSize, spin?: boolean, - stack?: string, - style?: React.CSSProperties + stack?: FontAwesomeStack, + tag?: string } class FontAwesome extends React.Component {} diff --git a/react-fontawesome/react-fontawesome-tests.tsx b/react-fontawesome/react-fontawesome-tests.tsx index 69bdeaf2c1..32aad1ddb7 100644 --- a/react-fontawesome/react-fontawesome-tests.tsx +++ b/react-fontawesome/react-fontawesome-tests.tsx @@ -12,9 +12,6 @@ class TestComponent extends React.Component<{}, {}> { name="rocket" size="2x" spin - style={ - { textShadow: '0 1px 0 rgba(0, 0, 0, 0.1)' } - } /> ); } diff --git a/react-ga/index.d.ts b/react-ga/index.d.ts index 0a0973113b..1d64b23971 100644 --- a/react-ga/index.d.ts +++ b/react-ga/index.d.ts @@ -1,32 +1,26 @@ -// Type definitions for react-fa v1.4.1 +// Type definitions for react-ga 1.4 // Project: https://github.com/react-ga/react-ga // Definitions by: Tim Aldridge // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace __reactGA { - export interface EventArgs { - category: string; - action: string; - label?: string; - value?: number; - nonInteraction?: boolean; - } - - export interface InitializeOptions { - debug?: boolean; - } - - export interface FieldsObject { - [i: string]: any; - } - - export function initialize(trackingCode: string, options?: InitializeOptions): void; - export function pageview(path: string): void; - export function modalview(name: string): void; - export function event(args: EventArgs): void; - export function set(fieldsObject: FieldsObject): void; +export interface EventArgs { + category: string; + action: string; + label?: string; + value?: number; + nonInteraction?: boolean; } -declare module 'react-ga' { - export = __reactGA; +export interface InitializeOptions { + debug?: boolean; } + +export interface FieldsObject { + [i: string]: any; +} + +export function initialize(trackingCode: string, options?: InitializeOptions): void; +export function pageview(path: string): void; +export function modalview(name: string): void; +export function event(args: EventArgs): void; +export function set(fieldsObject: FieldsObject): void; diff --git a/react-ga/react-ga-tests.tsx b/react-ga/react-ga-tests.tsx index b31777fb91..10770f04f5 100644 --- a/react-ga/react-ga-tests.tsx +++ b/react-ga/react-ga-tests.tsx @@ -1,16 +1,15 @@ /// +import * as ga from "react-ga"; + describe("Testing react-ga initialize object", () => { it("Able to initialize react-ga object", () => { - let ga = __reactGA; ga.initialize("UA-65432-1"); }); it("Able to initailize react-ga object", () => { - let ga = __reactGA; - - let options: __reactGA.InitializeOptions = { + const options: ga.InitializeOptions = { debug: true, - } + }; ga.initialize("UA-65432-1", options); }); @@ -18,7 +17,6 @@ describe("Testing react-ga initialize object", () => { describe("Testing react-ga pageview calls", () => { it("Able to make pageview calls", () => { - let ga = __reactGA; ga.initialize("UA-65432-1"); ga.pageview("http://telshin.com"); @@ -27,7 +25,6 @@ describe("Testing react-ga pageview calls", () => { describe("Testing react-ga modal calls", () => { it("Able to make modal calls", () => { - let ga = __reactGA; ga.initialize("UA-65432-1"); ga.modalview("Test modal"); @@ -36,16 +33,15 @@ describe("Testing react-ga modal calls", () => { describe("Testing react-ga event calls", () => { it("Able to make event calls", () => { - let ga = __reactGA; ga.initialize("UA-65432-1"); - let options: __reactGA.EventArgs = { + const options: ga.EventArgs = { category: "Test", action: "CI", label: "Running Jasmine tests for react-ga typscript library", value: 4, nonInteraction: true, - } + }; ga.event(options); }); @@ -53,10 +49,9 @@ describe("Testing react-ga event calls", () => { describe("Testing react-ga set calls", () => { it("Able to make set calls", () => { - let ga = __reactGA; ga.initialize("UA-65432-1"); - let fieldObject: __reactGA.FieldsObject = { + const fieldObject: ga.FieldsObject = { page: '/users' }; diff --git a/react-ga/tslint.json b/react-ga/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/react-ga/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/react-gravatar/react-gravatar-tests.tsx b/react-gravatar/react-gravatar-tests.tsx index 1e52dd5f81..e3b36b7259 100644 --- a/react-gravatar/react-gravatar-tests.tsx +++ b/react-gravatar/react-gravatar-tests.tsx @@ -2,7 +2,7 @@ import * as React from "react"; import * as Gravatar from "react-gravatar"; class GravatarEmailTest extends React.Component { - public render() { + render() { return ( { } class GravatarHashTest extends React.Component { - public render() { + render() { return ( { } class GravatarMinimalTest extends React.Component { - public render() { + render() { return ; } } \ No newline at end of file diff --git a/react-highlight-words/react-highlight-words-tests.tsx b/react-highlight-words/react-highlight-words-tests.tsx index e840edfabd..51d1f82374 100644 --- a/react-highlight-words/react-highlight-words-tests.tsx +++ b/react-highlight-words/react-highlight-words-tests.tsx @@ -1,9 +1,8 @@ import React = require("react"); import Highlighter = require("react-highlight-words"); - \ No newline at end of file +/>; diff --git a/react-highlighter/index.d.ts b/react-highlighter/index.d.ts index c13670b0a2..74468c9b7c 100644 --- a/react-highlighter/index.d.ts +++ b/react-highlighter/index.d.ts @@ -1,9 +1,7 @@ -// Type definitions for react-highlighter +// Type definitions for react-highlighter 0.3 // Project: https://github.com/helior/react-highlighter // Definitions by: Pedro Pereira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "react-highlighter" { - var Highlight: any; - export = Highlight; -} \ No newline at end of file +declare var Highlight: any; +export = Highlight; diff --git a/react-highlighter/react-highlighter-tests.tsx b/react-highlighter/react-highlighter-tests.tsx index 040c4665b6..9065bd1fab 100644 --- a/react-highlighter/react-highlighter-tests.tsx +++ b/react-highlighter/react-highlighter-tests.tsx @@ -2,7 +2,7 @@ import * as React from 'react'; import * as Highlight from 'react-highlighter'; export class ReactHolderTest extends React.Component { - public render() { + render() { return (
    -
    \ No newline at end of file +
    ; diff --git a/react-joyride/react-joyride-tests.tsx b/react-joyride/react-joyride-tests.tsx index 8ff818637d..9674560f5e 100644 --- a/react-joyride/react-joyride-tests.tsx +++ b/react-joyride/react-joyride-tests.tsx @@ -49,7 +49,7 @@ class NewComponent extends React.Component { }, name: "my-name", parent: "MyParent" - }) + }); } } diff --git a/react-json-pretty/react-json-pretty-tests.tsx b/react-json-pretty/react-json-pretty-tests.tsx index 59f8eb74f3..485aaf6e68 100644 --- a/react-json-pretty/react-json-pretty-tests.tsx +++ b/react-json-pretty/react-json-pretty-tests.tsx @@ -5,7 +5,7 @@ export class Test extends React.Component { render() { const json = { foo: "bar" - } + }; return (
    diff --git a/react-json-pretty/tsconfig.json b/react-json-pretty/tsconfig.json index ddb38d587e..f2456531cf 100644 --- a/react-json-pretty/tsconfig.json +++ b/react-json-pretty/tsconfig.json @@ -1,6 +1,10 @@ { "compilerOptions": { "module": "commonjs", + "lib": [ + "es6", + "dom" + ], "target": "es6", "noImplicitAny": true, "noImplicitThis": true, diff --git a/react-leaflet/index.d.ts b/react-leaflet/index.d.ts index f98b222acd..2399947c7d 100644 --- a/react-leaflet/index.d.ts +++ b/react-leaflet/index.d.ts @@ -4,12 +4,10 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -/// - import * as Leaflet from 'leaflet'; import * as React from 'react'; -//All events need to be lowercase so they don't collide with React.DOMAttributes +// All events need to be lowercase so they don't collide with React.DOMAttributes // which already declares things with some of the same names interface LeafletLayerEvents { @@ -69,7 +67,8 @@ interface LeafletDraggingEvents { } -interface MapProps extends React.HTMLProps, LeafletLayerEvents, LeafletMapStateChangeEvents, LeafletPopupEvents, LeafletTooltipEvents, LeafletLocationEvents, LeafletInteractionEvents, LeafletOtherEvents, Leaflet.MapOptions { +interface MapProps extends React.HTMLProps, + LeafletLayerEvents, LeafletMapStateChangeEvents, LeafletPopupEvents, LeafletTooltipEvents, LeafletLocationEvents, LeafletInteractionEvents, LeafletOtherEvents, Leaflet.MapOptions { animate?: boolean; bounds?: Leaflet.LatLngBoundsExpression; boundsOptions?: Leaflet.FitBoundsOptions; @@ -94,16 +93,16 @@ interface PaneProps { declare const Pane: React.ComponentClass; -//There is no Layer class, these are the base props for all layers on the map +// There is no Layer class, these are the base props for all layers on the map interface LayerProps extends LeafletInteractionEvents { onadd?: (event: Leaflet.Event) => void; onremove?: (event: Leaflet.Event) => void; - //Popup events + // Popup events onpopupopen?: (event: Leaflet.PopupEvent) => void; onpopupclose?: (event: Leaflet.PopupEvent) => void; - //Tooltip events + // Tooltip events ontooltipopen?: (event: Leaflet.TooltipEvent) => void; ontooltipclose?: (event: Leaflet.TooltipEvent) => void; } @@ -126,7 +125,7 @@ interface PopupProps extends LayerProps, Leaflet.PopupOptions { } declare const Popup: React.ComponentClass; -//tslint:disable-next-line:no-empty-interface +// tslint:disable-next-line:no-empty-interface interface TooltipProps extends LayerProps, Leaflet.TooltipOptions { } declare const Tooltip: React.ComponentClass; @@ -159,8 +158,8 @@ interface WMSTileLayerProps extends TileLayerProps { } declare const WMSTileLayer: React.ComponentClass; -//Path is an abstract class -//tslint:disable-next-line:no-empty-interface +// Path is an abstract class +// tslint:disable-next-line:no-empty-interface interface PathProps extends LeafletLayerEvents, LeafletInteractionEvents, Leaflet.PathOptions { } @@ -193,11 +192,11 @@ interface RectangleProps extends PathProps { declare const Rectangle: React.ComponentClass; -//tslint:disable-next-line:no-empty-interface +// tslint:disable-next-line:no-empty-interface interface LayerGroupProps extends LayerProps { } declare const LayerGroup: React.ComponentClass; -//tslint:disable-next-line:no-empty-interface +// tslint:disable-next-line:no-empty-interface interface FeatureGroupProps extends LayerGroupProps, Leaflet.PathOptions { } declare const FeatureGroup: React.ComponentClass; diff --git a/react-leaflet/react-leaflet-tests.tsx b/react-leaflet/react-leaflet-tests.tsx index 4a33aa0748..bb78ac7264 100644 --- a/react-leaflet/react-leaflet-tests.tsx +++ b/react-leaflet/react-leaflet-tests.tsx @@ -23,7 +23,7 @@ import { } from 'react-leaflet'; const { BaseLayer, Overlay } = LayersControl; -///animate.js +/// animate.js export class AnimateExample extends Component { state = { animate: false, @@ -32,18 +32,18 @@ export class AnimateExample extends Component { lat: 51.505, lng: -0.09, }, - } + }; handleClick = (e: Leaflet.MouseEvent) => { this.setState({ latlng: e.latlng, - }) + }); } toggleAnimate = () => { this.setState({ animate: !this.state.animate, - }) + }); } render() { @@ -53,7 +53,7 @@ export class AnimateExample extends Component { You are here - ) : null + ) : null; return (
    @@ -64,7 +64,7 @@ export class AnimateExample extends Component { @@ -75,31 +75,31 @@ export class AnimateExample extends Component { {marker}
    - ) + ); } } -//bounds.js +// bounds.js const outer: Array<[number, number]> = [ [50.505, -29.09], [52.505, 29.09], -] +]; const inner: Array<[number, number]> = [ [49.505, -2.09], [53.505, 2.09], -] +]; export class BoundsExample extends Component { state = { bounds: outer, - } + }; onClickInner = () => { - this.setState({ bounds: inner }) + this.setState({ bounds: inner }); } onClickOuter = () => { - this.setState({ bounds: outer }) + this.setState({ bounds: outer }); } render() { @@ -120,14 +120,14 @@ export class BoundsExample extends Component { onclick={this.onClickInner} />
    - ) + ); } } -//custom-component.js +// custom-component.js const SomeFn = (asd: string) => ( asd + asd -) +); const MyPopupMarker = ({ children, position }: any) => ( @@ -145,12 +145,12 @@ const MyPopupMarker = ({ children, position }: any) => ( const MyMarkersList = ({ markers }: any) => { const items = markers.map(({ key, ...props }: any) => ( - )) - return
    {items}
    -} + )); + return
    {items}
    ; +}; (MyMarkersList as any).propTypes = { markers: PropTypes.array.isRequired, -} +}; export class CustomComponent extends Component { state = { @@ -160,13 +160,13 @@ export class CustomComponent extends Component { }; render() { - const center: [number, number] = [this.state.lat, this.state.lng] + const center: [number, number] = [this.state.lat, this.state.lng]; const markers = [ { key: 'marker1', position: [51.5, -0.1], children: 'My first popup' }, { key: 'marker2', position: [51.51, -0.1], children: 'My second popup' }, { key: 'marker3', position: [51.49, -0.05], children: 'My third popup' }, - ] + ]; return ( { /> - ) + ); } } -//draggable-marker.js +// draggable-marker.js export class DraggableExample extends Component { state = { center: { @@ -192,22 +192,22 @@ export class DraggableExample extends Component { }, zoom: 13, draggable: true, - } + }; toggleDraggable = () => { - this.setState({ draggable: !this.state.draggable }) + this.setState({ draggable: !this.state.draggable }); } updatePosition = () => { - const { lat, lng } = (this.refs['marker'] as MarkerInstance).leafletElement.getLatLng() + const { lat, lng } = (this.refs['marker'] as MarkerInstance).leafletElement.getLatLng(); this.setState({ marker: { lat, lng }, - }) + }); } render() { - const position: [number, number] = [this.state.center.lat, this.state.center.lng] - const markerPosition: [number, number] = [this.state.marker.lat, this.state.marker.lng] + const position: [number, number] = [this.state.center.lat, this.state.center.lng]; + const markerPosition: [number, number] = [this.state.marker.lat, this.state.marker.lng]; return ( @@ -227,11 +227,11 @@ export class DraggableExample extends Component {
    - ) + ); } } -//events.js +// events.js export class EventsExample extends Component { state = { hasLocation: false, @@ -239,17 +239,17 @@ export class EventsExample extends Component { lat: 51.505, lng: -0.09, }, - } + }; handleClick = () => { - (this.refs['map'] as MapInstance).leafletElement.locate() + (this.refs['map'] as MapInstance).leafletElement.locate(); } handleLocationFound = (e: Leaflet.LocationEvent) => { this.setState({ hasLocation: true, latlng: e.latlng, - }) + }); } render() { @@ -259,12 +259,12 @@ export class EventsExample extends Component { You are here - ) : null + ) : null; return ( { /> {marker} - ) + ); } } -//layers-control.js +// layers-control.js export class LayersControlExample extends Component { render() { - const center: [number, number] = [51.505, -0.09] + const center: [number, number] = [51.505, -0.09]; const rectangle: Array<[number, number]> = [ [51.49, -0.08], [51.5, -0.06], - ] + ]; return ( @@ -330,18 +330,18 @@ export class LayersControlExample extends Component { - ) + ); } } -//other-layers.js +// other-layers.js export class OtherLayersExample extends Component { render() { - const center: [number, number] = [51.505, -0.09] + const center: [number, number] = [51.505, -0.09]; const rectangle: Array<[number, number]> = [ [51.49, -0.08], [51.5, -0.06], - ] + ]; return ( @@ -364,22 +364,22 @@ export class OtherLayersExample extends Component { - ) + ); } } -//pane.js +// pane.js export class PaneExample extends Component { state = { render: true, - } + }; componentDidMount() { setInterval(() => { this.setState({ render: !this.state.render, - }) - }, 5000) + }); + }, 5000); } render() { @@ -401,20 +401,20 @@ export class PaneExample extends Component { - ) + ); } } -//simple.js +// simple.js export class SimpleExample extends Component { state = { lat: 51.505, lng: -0.09, zoom: 13, - } + }; render() { - const position: [number, number] = [this.state.lat, this.state.lng] + const position: [number, number] = [this.state.lat, this.state.lng]; return ( { - ) + ); } } -//tooltip.js +// tooltip.js export class TooltipExample extends Component { state = { clicked: 0, - } + }; onClickCircle = () => { - this.setState({ clicked: this.state.clicked + 1 }) + this.setState({ clicked: this.state.clicked + 1 }); } render() { - const center: [number, number] = [51.505, -0.09] + const center: [number, number] = [51.505, -0.09]; const multiPolygon: Array> = [ [[51.51, -0.12], [51.51, -0.13], [51.53, -0.13]], [[51.51, -0.05], [51.51, -0.07], [51.53, -0.07]], - ] + ]; const rectangle: Array<[number, number]> = [ [51.49, -0.08], [51.5, -0.06], - ] + ]; const clickedText = this.state.clicked === 0 ? 'Click this Circle to change the Tooltip text' - : `Circle click: ${this.state.clicked}` + : `Circle click: ${this.state.clicked}`; return ( @@ -485,41 +485,41 @@ export class TooltipExample extends Component { - ) + ); } } -//vector-layers.js +// vector-layers.js export class VectorLayersExample extends Component { render() { - const center: [number, number] = [51.505, -0.09] + const center: [number, number] = [51.505, -0.09]; const polyline: Array<[number, number]> = [ [51.505, -0.09], [51.51, -0.1], [51.51, -0.12], - ] + ]; const multiPolyline: Array> = [ [[51.5, -0.1], [51.5, -0.12], [51.52, -0.12]], [[51.5, -0.05], [51.5, -0.06], [51.52, -0.06]], - ] + ]; const polygon: Array<[number, number]> = [ [51.515, -0.09], [51.52, -0.1], [51.52, -0.12], - ] + ]; const multiPolygon: Array> = [ [[51.51, -0.12], [51.51, -0.13], [51.53, -0.13]], [[51.51, -0.05], [51.51, -0.07], [51.53, -0.07]], - ] + ]; const rectangle: Array<[number, number]> = [ [51.49, -0.08], [51.5, -0.06], - ] + ]; return ( @@ -539,23 +539,23 @@ export class VectorLayersExample extends Component { - ) + ); } } -//wms-tile-layer.js +// wms-tile-layer.js export class WMSTileLayerExample extends Component { state = { lat: 51.505, lng: -0.09, zoom: 5, bluemarble: false, - } + }; onClick = () => { this.setState({ bluemarble: !this.state.bluemarble, - }) + }); } render() { @@ -573,11 +573,11 @@ export class WMSTileLayerExample extends Component { url='http://demo.opengeo.org/geoserver/ows?' /> - ) + ); } } -//zoom-control.js +// zoom-control.js const ZoomControlExample = () => ( ( /> -) \ No newline at end of file +); diff --git a/react-maskedinput/react-maskedinput-tests.tsx b/react-maskedinput/react-maskedinput-tests.tsx index 609b5c8241..cdc8070415 100644 --- a/react-maskedinput/react-maskedinput-tests.tsx +++ b/react-maskedinput/react-maskedinput-tests.tsx @@ -1,22 +1,19 @@ -import * as React from "react" - -import * as MaskedInput from "react-maskedinput" +import * as React from "react"; +import * as MaskedInput from "react-maskedinput"; class Test extends React.Component { - - public render () { + render() { return ( char, transform: (char: string) => char } } } /> - ) + ); } - } diff --git a/react-modal/react-modal-tests.tsx b/react-modal/react-modal-tests.tsx index b153fa0573..c8e50a3057 100644 --- a/react-modal/react-modal-tests.tsx +++ b/react-modal/react-modal-tests.tsx @@ -3,8 +3,8 @@ import * as ReactModal from 'react-modal'; class ExampleOfUsingReactModal extends React.Component<{}, {}> { render() { - var onAfterOpenFn = () => { } - var onRequestCloseFn = () => { } + var onAfterOpenFn = () => { }; + var onRequestCloseFn = () => { }; var customStyle = { overlay: { position: 'fixed', @@ -29,7 +29,7 @@ class ExampleOfUsingReactModal extends React.Component<{}, {}> { padding: '20px' } - } + }; return ( marginLeft: 36 } }} - onDateChange={(date: string) => {this.setState({date});}} + onDateChange={(date: string) => { this.setState({date}); }} /> ); } diff --git a/react-native-fs/react-native-fs-tests.ts b/react-native-fs/react-native-fs-tests.ts index 0e7dc2b0d0..a006086a9a 100644 --- a/react-native-fs/react-native-fs-tests.ts +++ b/react-native-fs/react-native-fs-tests.ts @@ -68,46 +68,46 @@ var uploadBegin: RNFS.UploadCallbackBegin = (response) => { }; var uploadProgress: RNFS.UploadCallbackProgress = (response) => { - var percentage = Math.floor((response.totalBytesSent/response.totalBytesExpectedToSend) * 100); + var percentage = Math.floor((response.totalBytesSent / response.totalBytesExpectedToSend) * 100); console.log('UPLOAD IS ' + percentage + '% DONE!'); }; // upload files RNFS.uploadFiles({ toUrl: uploadUrl, - files: files, + files, method: 'POST', headers: { - 'Accept': 'application/json', + Accept: 'application/json', }, fields: { - 'hello': 'world', + hello: 'world', }, begin: uploadBegin, progress: uploadProgress }).promise.then((response) => { - if (response.statusCode == 200) { + if (response.statusCode === 200) { console.log('FILES UPLOADED!'); // response.statusCode, response.headers, response.body } else { console.log('SERVER ERROR'); } }) .catch((err) => { - if(err.description === "cancelled") { + if (err.description === "cancelled") { // cancelled by user } console.log(err); }); var downloadProgress: RNFS.DownloadCallbackProgress = (result) => { - result.bytesWritten === 0 - result.contentLength > 10 - result.jobId -} + result.bytesWritten === 0; + result.contentLength > 10; + result.jobId; +}; var downloadBegin: RNFS.DownloadCallbackBegin = (result) => { - result.headers === {} -} + result.headers === {}; +}; RNFS.downloadFile({ fromUrl: 'http://.txt', @@ -115,5 +115,5 @@ RNFS.downloadFile({ begin: downloadBegin, progress: downloadProgress }).promise.then((response) => { - response.statusCode === 200 -}) \ No newline at end of file + response.statusCode === 200; +}); diff --git a/react-native-fs/tslint.json b/react-native-fs/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/react-native-fs/tslint.json +++ b/react-native-fs/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/react-native-scrollable-tab-view/react-native-scrollable-tab-view-tests.tsx b/react-native-scrollable-tab-view/react-native-scrollable-tab-view-tests.tsx index be501febf9..2d79537221 100644 --- a/react-native-scrollable-tab-view/react-native-scrollable-tab-view-tests.tsx +++ b/react-native-scrollable-tab-view/react-native-scrollable-tab-view-tests.tsx @@ -10,27 +10,24 @@ interface MyTextProperties extends React.Props { text: string; } class MyText extends React.Component { - public constructor(props: MyTextProperties) { + constructor(props: MyTextProperties) { super(props); } - public render(): JSX.Element { + render(): JSX.Element { return( this.props.text ); } } -interface ScrollableTabViewDemoProperties { +class ScrollableTabViewDemo extends React.Component<{}, {}> { -} -class ScrollableTabViewDemo extends React.Component { - - public constructor(props: ScrollableTabViewDemo) { + constructor(props: ScrollableTabViewDemo) { super(props); } - - public render(): JSX.Element { + + render(): JSX.Element { return ( diff --git a/react-native-swiper/react-native-swiper-tests.tsx b/react-native-swiper/react-native-swiper-tests.tsx index 93cdfcfd18..fa214e18f0 100644 --- a/react-native-swiper/react-native-swiper-tests.tsx +++ b/react-native-swiper/react-native-swiper-tests.tsx @@ -7,18 +7,13 @@ import { } from 'react-native'; import Swiper from 'react-native-swiper'; -interface IProperties { -} -interface IState { -} - -class SwiperTest extends React.Component { - public constructor(props: IProperties) { +class SwiperTest extends React.Component<{}, {}> { + constructor(props: {}) { super(props); } - public render(): React.ReactElement { + render(): React.ReactElement { return ( diff --git a/react-native/index.d.ts b/react-native/index.d.ts index c46db449f8..d18d311fa3 100644 --- a/react-native/index.d.ts +++ b/react-native/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-native 0.37 +// Type definitions for react-native 0.42 // Project: https://github.com/facebook/react-native // Definitions by: Needs A Maintainer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -5413,11 +5413,6 @@ declare module "react" { */ onScrollAnimationEnd?: () => void - /** - * When false, the content does not scroll. The default value is true - */ - scrollEnabled?: boolean // true - /** * This controls how often the scroll event will be fired while scrolling (in events per seconds). * A higher number yields better accuracy for code that is tracking the scroll position, @@ -5452,7 +5447,7 @@ declare module "react" { * This can be used for paginating through children that have lengths smaller than the scroll view. * Used in combination with snapToAlignment. */ - snapToInterval?: number + snapToInterval?: number[] /** * An array of child indices determining which children get docked to the @@ -5489,6 +5484,15 @@ declare module "react" { */ scrollPerfTag?: string + /** + * Used to override default value of overScroll mode. + + * Possible values: + * - 'auto' - Default value, allow a user to over-scroll this view only if the content is large enough to meaningfully scroll. + * - 'always' - Always allow a user to over-scroll this view. + * - 'never' - Never allow a user to over-scroll this view. + */ + overScrollMode?: 'auto' | 'always' | 'never' } export interface ScrollViewProperties extends ViewProperties, ScrollViewPropertiesIOS, ScrollViewPropertiesAndroid, Touchable, React.Props { @@ -5524,7 +5528,7 @@ declare module "react" { * and moves in synchrony with the touch; dragging upwards cancels the * dismissal. */ - keyboardDismissMode?: string + keyboardDismissMode?: 'none' | 'interactive' | 'on-drag' /** * When false tapping outside of the focused text input when the keyboard @@ -5532,7 +5536,15 @@ declare module "react" { * taps and the keyboard will not dismiss automatically. The default value * is false. */ - keyboardShouldPersistTaps?: boolean + keyboardShouldPersistTaps?: boolean | 'always' | 'never' | 'handled' + + /** + * Called when scrollable content view of the ScrollView changes. + * Handler function is passed the content width and content height as parameters: (contentWidth, contentHeight) + * It's implemented using onLayout handler attached to the content container which this ScrollView renders. + * + */ + onContentSizeChange?: (w: number, h: number) => void /** * Fires at most once per frame during scrolling. @@ -5567,6 +5579,11 @@ declare module "react" { */ pagingEnabled?: boolean + /** + * When false, the content does not scroll. The default value is true + */ + scrollEnabled?: boolean // true + /** * Experimental: When true offscreen child views (whose `overflow` value is * `hidden`) are removed from their native backing superview when offscreen. @@ -7659,6 +7676,10 @@ declare module "react" { * Custom style applied to the card. */ cardStyle?: ViewStyle + /** + * Custom style interpolator for the card. + */ + cardStyleInterpolator?: (props: NavigationSceneRendererProps) => ViewStyle; /** * Direction of the cards movement. Value could be `horizontal` or * `vertical`. Default value is `horizontal`. diff --git a/react-notification-system-redux/react-notification-system-redux-tests.tsx b/react-notification-system-redux/react-notification-system-redux-tests.tsx index 030d7a06b7..59f1a8404f 100644 --- a/react-notification-system-redux/react-notification-system-redux-tests.tsx +++ b/react-notification-system-redux/react-notification-system-redux-tests.tsx @@ -6,7 +6,7 @@ import { reducer, show, hide, info, error, warning, success, NotificationLevel } class Test extends React.Component { - private test () { + private test() { const notification: Notification = { message : "Test" }; @@ -23,11 +23,11 @@ class Test extends React.Component { hide(123); } - public render () { + render() { const notifications: Notification[] = []; return (); } } -const store: Store = createStore(reducer) +const store: Store = createStore(reducer); diff --git a/react-notification-system/index.d.ts b/react-notification-system/index.d.ts index fcf5f41120..eb2c089286 100644 --- a/react-notification-system/index.d.ts +++ b/react-notification-system/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for React Notification System v0.2.10 +// Type definitions for React Notification System 0.2 // Project: https://www.npmjs.com/package/react-notification-system // Definitions by: Giedrius Grabauskas , Deividas Bakanas , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,8 +10,8 @@ declare namespace NotificationSystem { export interface System extends React.Component { addNotification(notification: Notification): Notification; - removeNotification(notification: Notification): void; - removeNotification(uid: number | string): void; + removeNotification(uidOrNotification: number | string | Notification): void; + clearNotifications(): void; } export type CallBackFunction = (notification: Notification) => void; diff --git a/react-notification-system/react-notification-system-tests.ts b/react-notification-system/react-notification-system-tests.ts index 908758a7af..d8e26ba60b 100644 --- a/react-notification-system/react-notification-system-tests.ts +++ b/react-notification-system/react-notification-system-tests.ts @@ -1,6 +1,3 @@ - -/// - import React = require('react'); import NotificationSystem = require('react-notification-system'); @@ -31,18 +28,18 @@ class MyComponent extends React.Component { render() { var style = { - NotificationItem: { // Override the notification item - DefaultStyle: { // Applied to every notification, regardless of the notification level + NotificationItem: { // Override the notification item + DefaultStyle: { // Applied to every notification, regardless of the notification level margin: '10px 5px 2px 1px' }, - success: { // Applied only to the success notification item + success: { // Applied only to the success notification item color: 'red' } } }; - var attributes: NotificationSystem.Attributes = { + var attributes: NotificationSystem.Attributes = { style: { Containers: { DefaultStyle: { @@ -55,7 +52,7 @@ class MyComponent extends React.Component { } } } - }; + }; return React.createElement(NotificationSystem, { title: "NotificationTitile", style: style, } as NotificationSystem.Attributes); } diff --git a/react-overlays/tslint.json b/react-overlays/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/react-overlays/tslint.json +++ b/react-overlays/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/react-redux/index.d.ts b/react-redux/index.d.ts index 2d76aaac00..8daa310b51 100644 --- a/react-redux/index.d.ts +++ b/react-redux/index.d.ts @@ -49,14 +49,9 @@ export interface InferableComponentDecorator { export declare function connect(): InferableComponentDecorator; export declare function connect( - mapStateToProps: FuncOrSelf>, - mapDispatchToProps?: FuncOrSelf | MapDispatchToPropsObject> -): ComponentDecorator; - -export declare function connect( - mapStateToProps: FuncOrSelf>, - mapDispatchToProps: FuncOrSelf | MapDispatchToPropsObject>, - mergeProps: MergeProps, + mapStateToProps?: FuncOrSelf>, + mapDispatchToProps?: FuncOrSelf | MapDispatchToPropsObject>, + mergeProps?: MergeProps, options?: Options ): ComponentDecorator; diff --git a/react-redux/react-redux-tests.tsx b/react-redux/react-redux-tests.tsx index bbe84289ff..5d1f32765f 100644 --- a/react-redux/react-redux-tests.tsx +++ b/react-redux/react-redux-tests.tsx @@ -258,8 +258,9 @@ function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProp connect(mapStateToProps2, actionCreators, mergeProps)(TodoApp); - - +//https://github.com/DefinitelyTyped/DefinitelyTyped/issues/14622#issuecomment-279820358 +//Allow for undefined mapStateToProps +connect(undefined, mapDispatchToProps6)(TodoApp); interface TestProp { property1: number; diff --git a/react-router-bootstrap/tsconfig.json b/react-router-bootstrap/tsconfig.json index 1760fc3f1a..8e586637c7 100644 --- a/react-router-bootstrap/tsconfig.json +++ b/react-router-bootstrap/tsconfig.json @@ -13,6 +13,10 @@ "typeRoots": [ "../" ], + "paths": { + "history": ["history/v3"], + "history/*": ["history/v3/*"] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/react-router-redux/index.d.ts b/react-router-redux/index.d.ts index 226b3152e3..0736359b21 100644 --- a/react-router-redux/index.d.ts +++ b/react-router-redux/index.d.ts @@ -5,8 +5,7 @@ // TypeScript Version: 2.1 import { Action, Middleware, Store } from "redux"; -import { History } from "history"; -import { Location, LocationDescriptor } from "react-router"; +import { History, Location, LocationDescriptor } from "history"; export const CALL_HISTORY_METHOD: string; export const LOCATION_CHANGE: string; @@ -52,7 +51,7 @@ export interface SyncHistoryWithStoreOptions { } export interface HistoryUnsubscribe { - unsubscribe(): void; + unsubscribe(): undefined; } export function routerReducer(state?: RouterState, action?: Action): RouterState; diff --git a/react-router-redux/react-router-redux-tests.ts b/react-router-redux/react-router-redux-tests.ts index bcf4eaaed1..963d511f13 100644 --- a/react-router-redux/react-router-redux-tests.ts +++ b/react-router-redux/react-router-redux-tests.ts @@ -1,5 +1,5 @@ import { createStore, combineReducers, applyMiddleware } from 'redux'; -import { createBrowserHistory } from 'history'; +import { createHistory } from 'history'; import { syncHistoryWithStore, routerReducer, @@ -15,7 +15,7 @@ import { const reducer = combineReducers({ routing: routerReducer }); // Apply the middleware to the store -const browserHistory = createBrowserHistory() +const browserHistory = createHistory(); const middleware = routerMiddleware(browserHistory); const store = createStore( reducer, diff --git a/react-router-redux/tsconfig.json b/react-router-redux/tsconfig.json index 0b29093460..7e9539f9dd 100644 --- a/react-router-redux/tsconfig.json +++ b/react-router-redux/tsconfig.json @@ -12,6 +12,10 @@ "typeRoots": [ "../" ], + "paths": { + "history": ["history/v3"], + "history/*": ["history/v3/*"] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/react-router-redux/v3/index.d.ts b/react-router-redux/v3/index.d.ts index 105d081f30..fdea00bbc6 100644 --- a/react-router-redux/v3/index.d.ts +++ b/react-router-redux/v3/index.d.ts @@ -19,11 +19,11 @@ export const goForward: GoBackAction; export const routeActions: RouteActions; export type LocationDescriptor = History.LocationDescriptor; -export type PushAction = (nextLocation: LocationDescriptor) => void; -export type ReplaceAction = (nextLocation: LocationDescriptor) => void; -export type GoAction = (n: number) => void; -export type GoForwardAction = () => void; -export type GoBackAction = () => void; +export type PushAction = (nextLocation: LocationDescriptor) => any; +export type ReplaceAction = (nextLocation: LocationDescriptor) => any; +export type GoAction = (n: number) => any; +export type GoForwardAction = () => any; +export type GoBackAction = () => any; export interface RouteActions { push: PushAction; @@ -34,11 +34,9 @@ export interface RouteActions { } export interface HistoryMiddleware extends Redux.Middleware { - listenForReplays(store: Redux.Store, selectLocationState?: Function): void; - unsubscribe(): void; + listenForReplays(store: Redux.Store, selectLocationState?: Function): undefined; + unsubscribe(): undefined; } export function routeReducer(state?: any, options?: any): Redux.Reducer; export function syncHistory(history: History.History): HistoryMiddleware; - - diff --git a/react-router-redux/v3/react-router-redux-tests.ts b/react-router-redux/v3/react-router-redux-tests.ts index 90d68841ff..9d7beca92b 100644 --- a/react-router-redux/v3/react-router-redux-tests.ts +++ b/react-router-redux/v3/react-router-redux-tests.ts @@ -1,11 +1,11 @@ import { createStore, combineReducers, applyMiddleware } from 'redux'; -import { createBrowserHistory } from 'history'; +import { createHistory } from 'history'; import { syncHistory, routeReducer } from 'react-router-redux'; const reducer = combineReducers({ routing: routeReducer }); // Sync dispatched route actions to the history -const browserHistory = createBrowserHistory() +const browserHistory = createHistory(); const reduxRouterMiddleware = syncHistory(browserHistory); const createStoreWithMiddleware = applyMiddleware(reduxRouterMiddleware)(createStore); diff --git a/react-router-redux/v3/tsconfig.json b/react-router-redux/v3/tsconfig.json index ee406e1759..17a9407b8a 100644 --- a/react-router-redux/v3/tsconfig.json +++ b/react-router-redux/v3/tsconfig.json @@ -13,7 +13,8 @@ "../../" ], "paths": { - "history": ["history/v2"], + "history": ["history/v3"], + "history/*": ["history/v3/*"], "react-router-redux": ["react-router-redux/v3"] }, "types": [], diff --git a/react-router-redux/v3/tslint.json b/react-router-redux/v3/tslint.json index 5e200e7d9b..d032145676 100644 --- a/react-router-redux/v3/tslint.json +++ b/react-router-redux/v3/tslint.json @@ -1,7 +1,7 @@ { - "extends": "../tslint.json", - "rules": { - "forbidden-types": false, - "no-empty-interface": false - } + "extends": "../tslint.json", + "rules": { + "forbidden-types": false, + "no-empty-interface": false + } } diff --git a/react-router/index.d.ts b/react-router/index.d.ts index 84b9f2c152..be48438489 100644 --- a/react-router/index.d.ts +++ b/react-router/index.d.ts @@ -1,30 +1,21 @@ // Type definitions for react-router 3.0 // Project: https://github.com/rackt/react-router -// Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov , John Reilly , Karol Janyst +// Definitions by: Sergey Buturlakin +// Yuichi Murata +// Václav Ostrožlík +// Nathan Brown +// Alex Wendland +// Kostya Esmukov +// John Reilly +// Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -/* Replacement from old history definitions */ -export interface HistoryOptions { - getCurrentLocation?(): Location; - getUserConfirmation?(message: string, callback: (result: boolean) => void): void; - pushLocation?(nextLocation: Location): void; - replaceLocation?(nextLocation: Location): void; - go?(n: number): void; - keyLength?: number; -} - -export type CreateHistory = (options?: HistoryOptions) => T; -export type CreateHistoryEnhancer = (createHistory: CreateHistory) => CreateHistory; - export { - Basename, ChangeHook, EnterHook, InjectedRouter, LeaveHook, - Location, - LocationDescriptor, ParseQueryString, RouteComponent, RouteComponents, @@ -34,8 +25,7 @@ export { RouterProps, RouterState, RedirectFunction, - StringifyQuery, - Query + StringifyQuery } from "react-router/lib/Router"; export { LinkProps } from "react-router/lib/Link"; export { IndexLinkProps } from "react-router/lib/IndexLink"; diff --git a/react-router/lib/IndexLink.d.ts b/react-router/lib/IndexLink.d.ts index 0c62010262..3eb022f4c3 100644 --- a/react-router/lib/IndexLink.d.ts +++ b/react-router/lib/IndexLink.d.ts @@ -1,5 +1,5 @@ import { ComponentClass, CSSProperties, HTMLProps } from "react"; -import { Location, LocationDescriptor } from "react-router/lib/Router"; +import { Location, LocationDescriptor } from "history"; type ToLocationFunction = (location: Location) => LocationDescriptor; diff --git a/react-router/lib/IndexRedirect.d.ts b/react-router/lib/IndexRedirect.d.ts index 3b8187d09b..da0b88cf34 100644 --- a/react-router/lib/IndexRedirect.d.ts +++ b/react-router/lib/IndexRedirect.d.ts @@ -1,5 +1,6 @@ import { ComponentClass, ClassAttributes } from "react"; -import { RoutePattern, Query } from "react-router"; +import { RoutePattern } from "react-router"; +import { Query } from "history"; export interface IndexRedirectProps extends ClassAttributes { to: RoutePattern; diff --git a/react-router/lib/IndexRoute.d.ts b/react-router/lib/IndexRoute.d.ts index b0574df26a..84b70d7874 100644 --- a/react-router/lib/IndexRoute.d.ts +++ b/react-router/lib/IndexRoute.d.ts @@ -9,14 +9,14 @@ import { RouterState } from "react-router"; -type ComponentCallback = (err: any, component: RouteComponent) => void; -type ComponentsCallback = (err: any, components: RouteComponents) => void; +type ComponentCallback = (err: any, component: RouteComponent) => any; +type ComponentsCallback = (err: any, components: RouteComponents) => any; export interface IndexRouteProps { component?: RouteComponent; components?: RouteComponents; - getComponent?(nextState: RouterState, callback: ComponentCallback): void; - getComponents?(nextState: RouterState, callback: ComponentsCallback): void; + getComponent?(nextState: RouterState, callback: ComponentCallback): undefined; + getComponents?(nextState: RouterState, callback: ComponentsCallback): undefined; onEnter?: EnterHook; onChange?: ChangeHook; onLeave?: LeaveHook; diff --git a/react-router/lib/Redirect.d.ts b/react-router/lib/Redirect.d.ts index bb8254b4f5..118c2264ad 100644 --- a/react-router/lib/Redirect.d.ts +++ b/react-router/lib/Redirect.d.ts @@ -1,6 +1,7 @@ import { ComponentClass, ClassAttributes } from "react"; -import { RoutePattern, Query } from "react-router"; +import { RoutePattern } from "react-router"; import { IndexRedirectProps } from "react-router/lib/IndexRedirect"; +import { Query } from "history"; export interface RedirectProps extends IndexRedirectProps { from: RoutePattern; diff --git a/react-router/lib/Route.d.ts b/react-router/lib/Route.d.ts index 15aafebc75..1c0969da51 100644 --- a/react-router/lib/Route.d.ts +++ b/react-router/lib/Route.d.ts @@ -20,12 +20,12 @@ declare const Route: Route; export default Route; -type RouteCallback = (err: any, route: PlainRoute) => void; -type RoutesCallback = (err: any, routesArray: PlainRoute[]) => void; +type RouteCallback = (err: any, route: PlainRoute) => any; +type RoutesCallback = (err: any, routesArray: PlainRoute[]) => any; export interface PlainRoute extends RouteProps { childRoutes?: PlainRoute[]; - getChildRoutes?(partialNextState: LocationState, callback: RoutesCallback): void; + getChildRoutes?(partialNextState: LocationState, callback: RoutesCallback): undefined; indexRoute?: PlainRoute; - getIndexRoute?(partialNextState: LocationState, callback: RouteCallback): void; + getIndexRoute?(partialNextState: LocationState, callback: RouteCallback): undefined; } diff --git a/react-router/lib/Router.d.ts b/react-router/lib/Router.d.ts index 3870f538fc..daae78411a 100644 --- a/react-router/lib/Router.d.ts +++ b/react-router/lib/Router.d.ts @@ -1,20 +1,19 @@ import { Component, ComponentClass, ClassAttributes, ReactNode, StatelessComponent } from "react"; import { Action, - Hash, History, Href, + Location, + LocationDescriptor, LocationKey, LocationState, Path, Pathname, + Query, Search } from "history"; import { PlainRoute } from "react-router"; -/* Replacement from old history definitions */ -export type Basename = string; -export type Query = any; export interface Params { [key: string]: string; } @@ -36,27 +35,9 @@ export type LeaveHook = (prevState: RouterState) => any; export type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback?: AnyFunction) => any; export type RouteHook = (nextLocation?: Location) => any; -export interface Location { - pathname: Pathname; - search: Search; - query: Query; - state: LocationState; - action: Action; - key: LocationKey; -} - -export interface LocationDescriptorObject { - pathname?: Pathname; - query?: Query; - hash?: Hash; - state?: LocationState; -} - -export type LocationDescriptor = Path | LocationDescriptorObject; - export interface RedirectFunction { - (location: LocationDescriptor): void; - (state: LocationState, pathname: Pathname | Path, query?: Query): void; + (location: LocationDescriptor): undefined; + (state: LocationState, pathname: Pathname | Path, query?: Query): undefined; } export interface RouterState { @@ -66,11 +47,11 @@ export interface RouterState { components: RouteComponent[]; } -type LocationFunction = (location: LocationDescriptor) => void; -type GoFunction = (n: number) => void; -type NavigateFunction = () => void; +type LocationFunction = (location: LocationDescriptor) => any; +type GoFunction = (n: number) => any; +type NavigateFunction = () => any; type ActiveFunction = (location: LocationDescriptor, indexOnly?: boolean) => boolean; -type LeaveHookFunction = (route: any, callback: RouteHook) => void; +type LeaveHookFunction = (route: any, callback: RouteHook) => any; type CreatePartFunction = (path: Path, query?: any) => Part; export interface InjectedRouter { diff --git a/react-router/lib/createMemoryHistory.d.ts b/react-router/lib/createMemoryHistory.d.ts index 038e707e6b..8d341524c7 100644 --- a/react-router/lib/createMemoryHistory.d.ts +++ b/react-router/lib/createMemoryHistory.d.ts @@ -1,6 +1,2 @@ -import { History } from "history"; -import { CreateHistory } from "react-router"; - -declare const createMemoryHistory: CreateHistory; - +import { default as createMemoryHistory } from "history/lib/createMemoryHistory"; export default createMemoryHistory; diff --git a/react-router/lib/match.d.ts b/react-router/lib/match.d.ts index 407bcc80c2..a99561e6ba 100644 --- a/react-router/lib/match.d.ts +++ b/react-router/lib/match.d.ts @@ -1,5 +1,5 @@ -import { History } from "history"; -import { Basename, LocationDescriptor, ParseQueryString, RouteConfig, StringifyQuery } from "react-router"; +import { Basename, History, LocationDescriptor } from "history"; +import { ParseQueryString, RouteConfig, StringifyQuery } from "react-router"; interface MatchArgs { routes: RouteConfig; @@ -18,7 +18,6 @@ interface MatchHistoryArgs extends MatchArgs { history: History; } -export type MatchCallback = (error: any, redirectLocation: Location, renderProps: any) => void; - -export default function match(args: MatchLocationArgs | MatchHistoryArgs, cb: MatchCallback): void; +export type MatchCallback = (error: any, redirectLocation: Location, renderProps: any) => any; +export default function match(args: MatchLocationArgs | MatchHistoryArgs, cb: MatchCallback): undefined; diff --git a/react-router/lib/useRouterHistory.d.ts b/react-router/lib/useRouterHistory.d.ts index 7dc2bdd3ab..fdc82c9981 100644 --- a/react-router/lib/useRouterHistory.d.ts +++ b/react-router/lib/useRouterHistory.d.ts @@ -1,6 +1,3 @@ -import { History } from "history"; -import { CreateHistoryEnhancer } from "react-router"; +import { CreateHistory, HistoryBasename, HistoryBasenameOptions, HistoryQueries } from "history"; -declare const useRouterHistory: CreateHistoryEnhancer; - -export default useRouterHistory; +export default function useRouterHistory(createHistory: CreateHistory): CreateHistory; diff --git a/react-router/react-router-tests.tsx b/react-router/react-router-tests.tsx index 59186914e4..f8be6c3326 100644 --- a/react-router/react-router-tests.tsx +++ b/react-router/react-router-tests.tsx @@ -9,6 +9,7 @@ import { hashHistory, match, createMemoryHistory, + useRouterHistory, withRouter, routerShape, Router, @@ -21,10 +22,27 @@ import { RedirectFunction, RouteComponentProps } from "react-router"; +import { createHistory, History } from "history"; + +const routerHistory = useRouterHistory(createHistory)({ basename: "/test" }); + +interface CustomHistory { + test(): undefined; +} + +type CombinedHistory = History & CustomHistory; + +function createCustomHistory(history: History): CombinedHistory { + return { + ...history, + test() {} + } as CombinedHistory; +} +const customHistory = createCustomHistory(browserHistory); const NavLink = (props: LinkProps) => ( -) +); interface MasterContext { router: InjectedRouter; @@ -33,7 +51,7 @@ interface MasterContext { class Master extends Component { static contextTypes: ValidationMap = { - "router": routerShape + router: routerShape }; context: MasterContext; @@ -53,14 +71,14 @@ class Master extends Component {

    Master

    Dashboard Users

    {this.props.children}

    -
    +
    ; } } interface DashboardProps { - router: InjectedRouter -}; + router: InjectedRouter; +} class Dashboard extends React.Component { @@ -77,32 +95,32 @@ class Dashboard extends React.Component { render() { return
    This is a dashboard -
    + ; } } -const DashboardWithRouter = withRouter(Dashboard) +const DashboardWithRouter = withRouter(Dashboard); class NotFound extends React.Component<{}, {}> { render() { return
    This path does not exists -
    + ; } } -interface UsersProps extends RouteComponentProps<{}, {}> { } +type UsersProps = RouteComponentProps<{}, {}>; class Users extends React.Component { render() { - const { location, params, route, routes, router, routeParams } = this.props; + const { location, params, route, routes, router, routeParams } = this.props; return
    This is a user list -
    + ; } } @@ -116,8 +134,19 @@ ReactDOM.render(( -), document.body) +), document.body); +ReactDOM.render(( + + + +), document.body); + +ReactDOM.render(( + + + +), document.body); const history = createMemoryHistory("baseurl"); const routes = ( diff --git a/react-router/tsconfig.json b/react-router/tsconfig.json index e2a4e054ad..301ed3f651 100644 --- a/react-router/tsconfig.json +++ b/react-router/tsconfig.json @@ -11,6 +11,10 @@ "jsx": "react", "baseUrl": "../", "typeRoots": ["../"], + "paths": { + "history": ["history/v3"], + "history/*": ["history/v3/*"] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/react-router/tslint.json b/react-router/tslint.json index f9e30021f4..377cc837d4 100644 --- a/react-router/tslint.json +++ b/react-router/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/react-router/v2/index.d.ts b/react-router/v2/index.d.ts index b0a96487bf..67994b6710 100644 --- a/react-router/v2/index.d.ts +++ b/react-router/v2/index.d.ts @@ -1,6 +1,11 @@ // Type definitions for react-router 2.0 // Project: https://github.com/rackt/react-router -// Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov +// Definitions by: Sergey Buturlakin +// Yuichi Murata +// Václav Ostrožlík +// Nathan Brown +// Alex Wendland +// Kostya Esmukov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 diff --git a/react-select/index.d.ts b/react-select/index.d.ts index b149fd4c47..5393888f3b 100644 --- a/react-select/index.d.ts +++ b/react-select/index.d.ts @@ -29,6 +29,11 @@ declare namespace ReactSelectClass { * @default true */ clearableValue?: boolean; + /** + * Do not allow this option to be selected + * @default false + */ + disabled?: boolean; } export interface MenuRendererProps { diff --git a/react-select/react-select-tests.tsx b/react-select/react-select-tests.tsx index 7840f2ce9e..10a3f51833 100644 --- a/react-select/react-select-tests.tsx +++ b/react-select/react-select-tests.tsx @@ -140,7 +140,15 @@ class SelectTest extends React.Component, {}> { class SelectWithStringValueTest extends React.Component, {}> { render() { - const options: Option[] = [{ label: "Foo", value: "bar" }]; + const options: Option[] = [{ + label: "Foo", + value: "bar", + }, { + label: "Foo2", + value: "bar2", + clearableValue: false, + disabled: true + }]; const onChange = (value: any) => console.log(value); const selectProps: ReactSelectProps = { diff --git a/react-sidebar/react-sidebar-tests.tsx b/react-sidebar/react-sidebar-tests.tsx index 8e08d85599..4b6dfd593e 100644 --- a/react-sidebar/react-sidebar-tests.tsx +++ b/react-sidebar/react-sidebar-tests.tsx @@ -7,6 +7,6 @@ const sidebarStyle: SidebarStyles = { content: { width: "300px" } }; -let sidebar1 = +const sidebar1 =

    Content

    ; diff --git a/react-sticky/index.d.ts b/react-sticky/index.d.ts index b3070b046a..2126d582ef 100644 --- a/react-sticky/index.d.ts +++ b/react-sticky/index.d.ts @@ -11,14 +11,14 @@ declare module "react-sticky" { export var StickyContainer: React.ComponentClass>; export interface StickyProps { - isActive: boolean; - className: string; - style: any; - stickyClassName: string; - stickyStyle: any; - topOffset: number; - bottomOffset: number; - onStickyStateChange: (isSticky: boolean) => void; + isActive?: boolean; + className?: string; + style?: any; + stickyClassName?: string; + stickyStyle?: any; + topOffset?: number; + bottomOffset?: number; + onStickyStateChange?: (isSticky: boolean) => void; } export var Sticky: React.ComponentClass; diff --git a/react-sticky/react-sticky-tests.tsx b/react-sticky/react-sticky-tests.tsx index 7ab99bf0c7..6eb9d0e0d0 100644 --- a/react-sticky/react-sticky-tests.tsx +++ b/react-sticky/react-sticky-tests.tsx @@ -1,9 +1,16 @@ import {Sticky, StickyContainer} from "react-sticky"; import * as React from "react"; -const StickyComponent: JSX.Element = +const StickyAllOptions: JSX.Element = undefined}> +
    ; +const StickyNoOptions: JSX.Element = + + +
    + + ; diff --git a/react-sticky/tslint.json b/react-sticky/tslint.json index ccdb64abf2..377cc837d4 100644 --- a/react-sticky/tslint.json +++ b/react-sticky/tslint.json @@ -1,2 +1 @@ { "extends": "../tslint.json" } - diff --git a/react-toggle/react-toggle-tests.tsx b/react-toggle/react-toggle-tests.tsx index 9bec568663..f138268174 100644 --- a/react-toggle/react-toggle-tests.tsx +++ b/react-toggle/react-toggle-tests.tsx @@ -1,8 +1,8 @@ -import * as React from "react" -import Toggle from "react-toggle" +import * as React from "react"; +import Toggle from "react-toggle"; class Test extends React.Component<{}, {}> { - public render() { + render() { return ( ); diff --git a/react/index.d.ts b/react/index.d.ts index 64879114cf..d3c254f875 100644 --- a/react/index.d.ts +++ b/react/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for React v15.0 // Project: http://facebook.github.io/react/ -// Definitions by: Asana , AssureSign , Microsoft , John Reilly , Benoit Benezech , Patricio Zavolinsky +// Definitions by: Asana , AssureSign , Microsoft , John Reilly , Benoit Benezech , Patricio Zavolinsky , Digiguru // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -242,10 +242,10 @@ declare namespace React { interface ComponentLifecycle { componentWillMount?(): void; componentDidMount?(): void; - componentWillReceiveProps?(nextProps: P, nextContext: any): void; - shouldComponentUpdate?(nextProps: P, nextState: S, nextContext: any): boolean; - componentWillUpdate?(nextProps: P, nextState: S, nextContext: any): void; - componentDidUpdate?(prevProps: P, prevState: S, prevContext: any): void; + componentWillReceiveProps?(nextProps: Readonly

    , nextContext: any): void; + shouldComponentUpdate?(nextProps: Readonly

    , nextState: Readonly, nextContext: any): boolean; + componentWillUpdate?(nextProps: Readonly

    , nextState: Readonly, nextContext: any): void; + componentDidUpdate?(prevProps: Readonly

    , prevState: Readonly, prevContext: any): void; componentWillUnmount?(): void; } @@ -371,13 +371,13 @@ declare namespace React { deltaZ: number; } - interface AnimationEvent extends SyntheticEvent<{}> { + interface AnimationEvent extends SyntheticEvent { animationName: string; pseudoElement: string; elapsedTime: number; } - interface TransitionEvent extends SyntheticEvent<{}> { + interface TransitionEvent extends SyntheticEvent { propertyName: string; pseudoElement: string; elapsedTime: number; @@ -404,8 +404,8 @@ declare namespace React { type TouchEventHandler = EventHandler>; type UIEventHandler = EventHandler>; type WheelEventHandler = EventHandler>; - type AnimationEventHandler = EventHandler; - type TransitionEventHandler = EventHandler; + type AnimationEventHandler = EventHandler>; + type TransitionEventHandler = EventHandler>; // // Props / DOM Attributes @@ -597,16 +597,16 @@ declare namespace React { onWheelCapture?: WheelEventHandler; // Animation Events - onAnimationStart?: AnimationEventHandler; - onAnimationStartCapture?: AnimationEventHandler; - onAnimationEnd?: AnimationEventHandler; - onAnimationEndCapture?: AnimationEventHandler; - onAnimationIteration?: AnimationEventHandler; - onAnimationIterationCapture?: AnimationEventHandler; + onAnimationStart?: AnimationEventHandler; + onAnimationStartCapture?: AnimationEventHandler; + onAnimationEnd?: AnimationEventHandler; + onAnimationEndCapture?: AnimationEventHandler; + onAnimationIteration?: AnimationEventHandler; + onAnimationIterationCapture?: AnimationEventHandler; // Transition Events - onTransitionEnd?: TransitionEventHandler; - onTransitionEndCapture?: TransitionEventHandler; + onTransitionEnd?: TransitionEventHandler; + onTransitionEndCapture?: TransitionEventHandler; } // See CSS 3 CSS-wide keywords https://www.w3.org/TR/css3-values/#common-keywords @@ -1296,7 +1296,7 @@ declare namespace React { * along the main-axis of their container. * See CSS justify-content property https://www.w3.org/TR/css-flexbox-1/#justify-content-property */ - justifyContent?: CSSWideKeyword | "flex-start" | "flex-end" | "center" | "space-between" | "space-around"; + justifyContent?: CSSWideKeyword | "flex-start" | "flex-end" | "center" | "space-between" | "space-around" | "space-evenly"; layoutGrid?: CSSWideKeyword | any; @@ -2146,6 +2146,7 @@ declare namespace React { shape?: string; size?: number; sizes?: string; + slot?: string; span?: number; spellCheck?: boolean; src?: string; @@ -2568,6 +2569,7 @@ declare namespace React { // SVG svg: SVGFactory; + animate: SVGFactory; circle: SVGFactory; defs: SVGFactory; ellipse: SVGFactory; @@ -2795,6 +2797,7 @@ declare global { // SVG svg: React.SVGProps; + animate: React.SVGProps; circle: React.SVGProps; clipPath: React.SVGProps; defs: React.SVGProps; diff --git a/react/test/cssProperties.tsx b/react/test/cssProperties.tsx index f037c43eb4..293f0b5374 100644 --- a/react/test/cssProperties.tsx +++ b/react/test/cssProperties.tsx @@ -21,7 +21,7 @@ const fontStyleStyleTest =

    ; const fontWeightStyle: React.CSSProperties = { fontWeight: 400 }; const fontWeightStyleTest =
    ; -const justifyContentStyle: React.CSSProperties = { justifyContent: 'space-around' }; +const justifyContentStyle: React.CSSProperties = { justifyContent: 'space-evenly' }; const justifyContentStyleTest =
    ; diff --git a/react/test/index.ts b/react/test/index.ts index 64d5d9d918..1bf6c8dcc2 100644 --- a/react/test/index.ts +++ b/react/test/index.ts @@ -317,6 +317,7 @@ var htmlAttr: React.HTMLProps = { children: children, className: "test-attr", style: divStyle, + slot: "HTMLComponent", onClick: (event: React.MouseEvent<{}>) => { event.preventDefault(); event.stopPropagation(); @@ -325,6 +326,9 @@ var htmlAttr: React.HTMLProps = { event.preventDefault(); event.stopPropagation(); }, + onAnimationStart: event => { + console.log(event.currentTarget.className); + }, dangerouslySetInnerHTML: { __html: "STRONG" } diff --git a/react/test/tsx.tsx b/react/test/tsx.tsx index 0531cb52c0..540c712596 100644 --- a/react/test/tsx.tsx +++ b/react/test/tsx.tsx @@ -30,5 +30,6 @@ StatelessComponent2.defaultProps = { Hello, world! +
    Hello again!
    ; diff --git a/readline-sync/readline-sync-tests.ts b/readline-sync/readline-sync-tests.ts index 02c8d8e952..7800fda39a 100644 --- a/readline-sync/readline-sync-tests.ts +++ b/readline-sync/readline-sync-tests.ts @@ -1,16 +1,14 @@ - - import readlineSync = require('readline-sync'); -let result:string = readlineSync.question('Which program starts do you want? ', { +const result: string = readlineSync.question('Which program starts do you want? ', { defaultInput: 'firefox' }); -let result2:string = readlineSync.prompt({prompt: '$$'}); +const result2: string = readlineSync.prompt({prompt: '$$'}); -let result3:string = readlineSync.keyIn('Press a key', { limit: '$<1-5>' }); +const result3: string = readlineSync.keyIn('Press a key', { limit: '$<1-5>' }); -let result4:{} = readlineSync.setDefaultOptions({ +const result4: {} = readlineSync.setDefaultOptions({ prompt: '$$', hideEchoBack: true, mask: '*', @@ -18,12 +16,12 @@ let result4:{} = readlineSync.setDefaultOptions({ limitMessage: 'Limit reached', defaultInput: 'English', trueValue: 2, - falseValue: (value:string) => { return true; }, + falseValue: (value: string) => true, caseSensitive: true, keepWhitespace: true, encoding: 'utf-8', bufferSize: 12, - print: (display:string, encoding:string) => { console.log(display)}, + print: (display: string, encoding: string) => { console.log(display); }, history: false, cd: true, charlist: 'abc', @@ -34,26 +32,26 @@ let result4:{} = readlineSync.setDefaultOptions({ exists: false, isFile: true, isDirectory: false, - validate: (path:string) => { return (path === '/usr/local/bin'); }, + validate: (path: string) => path === '/usr/local/bin', create: true, guide: false, }); -let result5:string = readlineSync.questionEMail('Enter email'); +const result5: string = readlineSync.questionEMail('Enter email'); -let result6:string = readlineSync.questionNewPassword('PASSWORD: ', {charlist: '$#$@%'}); +const result6: string = readlineSync.questionNewPassword('PASSWORD: ', {charlist: '$#$@%'}); -let result7:number = readlineSync.questionInt('Enter an integer', { limitMessage: 'Enter a valid integer' }); +const result7: number = readlineSync.questionInt('Enter an integer', { limitMessage: 'Enter a valid integer' }); -let result8:number = readlineSync.questionFloat('Enter a float', { limitMessage: 'Enter a valid float' }); +const result8: number = readlineSync.questionFloat('Enter a float', { limitMessage: 'Enter a valid float' }); -let result9:string = readlineSync.questionPath('Save to: ', { +const result9: string = readlineSync.questionPath('Save to: ', { isDirectory: true, exists: null, create: true }); -readlineSync.promptCL((command:string, arg1:string, arg2:string) => { +readlineSync.promptCL((command: string, arg1: string, arg2: string) => { if (command === 'add') { console.log(arg1 + ' is added.'); } else if (command === 'copy') { @@ -62,43 +60,43 @@ readlineSync.promptCL((command:string, arg1:string, arg2:string) => { }); readlineSync.promptCL({ - add: (element:string) => { // It's called by also "ADD", "Add", "aDd", etc.. + add: (element: string) => { // It's called by also "ADD", "Add", "aDd", etc.. console.log(element + ' is added.'); }, - copy: (from:string, to:string) => { + copy: (from: string, to: string) => { console.log(from + ' is copied to ' + to + '.'); } }); -readlineSync.promptLoop((input:string) => { +readlineSync.promptLoop((input: string) => { console.log('-- You said "' + input + '"'); return input === 'bye'; }); readlineSync.promptCLLoop({ - add: (element:string) => { + add: (element: string) => { console.log(element + ' is added.'); }, - copy: (from:string, to:string) => { + copy: (from: string, to: string) => { console.log(from + ' is copied to ' + to + '.'); }, - bye: () => { return true; } + bye: () => true }); -let result10:string = readlineSync.promptSimShell(); +const result10: string = readlineSync.promptSimShell(); -let result11:(boolean | string) = readlineSync.keyInYN('Do you want to install this?'); +const result11: (boolean | string) = readlineSync.keyInYN('Do you want to install this?'); -let result12:boolean = readlineSync.keyInYNStrict('Do you want to install this?', { guide: true }); +const result12: boolean = readlineSync.keyInYNStrict('Do you want to install this?', { guide: true }); -readlineSync.keyInPause({ guide:true }); +readlineSync.keyInPause({ guide: true }); -let frameworks = ['Express', 'hapi', 'flatiron', 'MEAN.JS', 'locomotive']; -let result13:number = readlineSync.keyInSelect(frameworks, 'Which framework?'); +const frameworks = ['Express', 'hapi', 'flatiron', 'MEAN.JS', 'locomotive']; +const result13: number = readlineSync.keyInSelect(frameworks, 'Which framework?'); -let result14:string = readlineSync.getRawInput(); +const result14: string = readlineSync.getRawInput(); -readlineSync.setPrint((display:string, encoding:string) => { console.log(display) }); +readlineSync.setPrint((display: string, encoding: string) => { console.log(display); }); readlineSync.setPrompt(new Date()); diff --git a/realm/tslint.json b/realm/tslint.json index ccdb64abf2..377cc837d4 100644 --- a/realm/tslint.json +++ b/realm/tslint.json @@ -1,2 +1 @@ { "extends": "../tslint.json" } - diff --git a/redis/index.d.ts b/redis/index.d.ts index 0e7e2ec4de..c20e4f1277 100644 --- a/redis/index.d.ts +++ b/redis/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for redis 0.12.1 +// Type definitions for redis 0.12.2 // Project: https://github.com/mranney/node_redis // Definitions by: Carlos Ballesteros Velasco , Peter Harris , TANAKA Koichi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -91,7 +91,12 @@ export interface RedisClient extends NodeJS.EventEmitter { offline_queue: any[]; server_info: ServerInfo; - end(): void; + /** + * Forcibly close the connection to the Redis server. Note that this does not wait until all replies have been parsed. If you want to exit cleanly, call client.quit() + * + * @param {boolean} flush You should set flush to true, if you are not absolutely sure you do not care about any other commands. If you set flush to false all still running commands will silently fail. + */ + end(flush: boolean): void; unref(): void; /** @@ -274,8 +279,8 @@ export interface RedisClient extends NodeJS.EventEmitter { hmget(...args: any[]): boolean; hincrby(args: any[], callback?: ResCallbackT): boolean; hincrby(...args: any[]): boolean; - hincrbyfloat(args:any[], callback?:ResCallbackT): boolean; - hincrbyfloat(...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; @@ -408,7 +413,7 @@ export interface RedisClient extends NodeJS.EventEmitter { zscan(args: any[], callback?: ResCallbackT): boolean; // Extras - duplicate(options?:any[], callback?:ResCallbackT): RedisClient; + duplicate(options?: any[], callback?: ResCallbackT): RedisClient; } export interface Multi { diff --git a/redis/redis-tests.ts b/redis/redis-tests.ts index e0315a809f..c1908e1089 100644 --- a/redis/redis-tests.ts +++ b/redis/redis-tests.ts @@ -31,10 +31,10 @@ client = redis.createClient(num, str, options); function retryStrategyNumber(options: redis.RetryStrategyOptions): number { // Ensure that the properties of RetryStrategyOptions are resilient to breaking change. // If the properties of the interface changes, the variables below will also need to be adapted. - var error: Error = options.error; + var error: Error = options.error; var total_retry_time: number = options.total_retry_time; - var times_connected: number = options.times_connected; - var attempt: number = options.attempt; + var times_connected: number = options.times_connected; + var attempt: number = options.attempt; return 5000; } function retryStrategyError(options: redis.RetryStrategyOptions): Error { @@ -57,7 +57,7 @@ info = client.server_info; // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- -client.end(); +client.end(true); // Connection (http://redis.io/commands#connection) client.auth(str, resCallback); @@ -98,11 +98,11 @@ client.subscribe(str); // Multi client.multi() - .scard(str) - .smembers(str) - .keys('*', resCallback) - .dbsize() - .exec(resCallback); + .scard(str) + .smembers(str) + .keys('*', resCallback) + .dbsize() + .exec(resCallback); client.multi(commandArr).exec(); diff --git a/redux-actions/index.d.ts b/redux-actions/index.d.ts index a22a0b41cc..0353318031 100644 --- a/redux-actions/index.d.ts +++ b/redux-actions/index.d.ts @@ -38,7 +38,13 @@ interface ReducerNextThrowMeta { throw?(state: State, action: ActionMeta): State; } -type ActionFunctions = ActionFunction0> | ActionFunction1> | ActionFunction2> | ActionFunction3> | ActionFunction4> | ActionFunctionAny>; +type ActionFunctions = + ActionFunction0> | + ActionFunction1> | + ActionFunction2> | + ActionFunction3> | + ActionFunction4> | + ActionFunctionAny>; type Reducer = (state: State, action: Action) => State; diff --git a/redux-actions/redux-actions-tests.ts b/redux-actions/redux-actions-tests.ts index 60923b9f10..11fa7adf13 100644 --- a/redux-actions/redux-actions-tests.ts +++ b/redux-actions/redux-actions-tests.ts @@ -26,7 +26,7 @@ const actionHandlerWithReduceMap = ReduxActions.handleAction( next(state: number, action: ReduxActions.Action) { return state * action.payload; }, - throw(state: number) { return state } + throw(state: number) { return state; } }, 0 ); @@ -34,17 +34,17 @@ const actionHandlerWithReduceMap = ReduxActions.handleAction( state = actionHandlerWithReduceMap(0, multiplyAction(10)); const actionsHandler = ReduxActions.handleActions({ - 'INCREMENT': (state: number, action: ReduxActions.Action) => state + action.payload, - 'MULTIPLY': (state: number, action: ReduxActions.Action) => state * action.payload + INCREMENT: (state: number, action: ReduxActions.Action) => state + action.payload, + MULTIPLY: (state: number, action: ReduxActions.Action) => state * action.payload }, 0); state = actionsHandler(0, { type: 'INCREMENT' }); const actionsHandlerWithInitialState = ReduxActions.handleActions({ - 'INCREMENT': { + INCREMENT: { next: (state: number, action: ReduxActions.Action) => state + action.payload, }, - 'MULTIPLY': { + MULTIPLY: { next: (state: number, action: ReduxActions.Action) => state * action.payload } }, 0); @@ -53,17 +53,17 @@ state = actionsHandlerWithInitialState(0, { type: 'INCREMENT' }); // ---------------------------------------------------------------------------------------------------- -type TypedState = { +interface TypedState { value: number; -}; +} -type TypedPayload = { +interface TypedPayload { increase: number; } -type MetaType = { - remote: boolean -}; +interface MetaType { + remote: boolean; +} let typedState: TypedState; @@ -103,37 +103,37 @@ const typedActionHandlerWithReduceMap = ReduxActions.handleAction) { return { value: state.value + action.payload.increase }; }, - throw(state: TypedState) { return state } + throw(state: TypedState) { return state; } }, {value: 1} ); typedState = typedActionHandlerWithReduceMap({ value: 0 }, typedIncrementByActionWithMeta(10)); -const act = ReduxActions.createAction('ACTION1') -act('hello').payload === 'hello' +const act = ReduxActions.createAction('ACTION1'); +act('hello').payload === 'hello'; -const act2 = ReduxActions.createAction('ACTION2', (s: {load: boolean}) => s) -act2({load: true}).payload.load == true +const act2 = ReduxActions.createAction('ACTION2', (s: {load: boolean}) => s); +act2({load: true}).payload.load === true; -const act3 = ReduxActions.createAction('ACTION3', (s: string) => ({s})) -act3('hello').payload.s == 'hello' +const act3 = ReduxActions.createAction('ACTION3', (s: string) => ({s})); +act3('hello').payload.s === 'hello'; ReduxActions.handleAction<{ hello: string }, string>(act, (state, action) => { - return { hello: action.payload } -}, {hello: 'greetings'}) + return { hello: action.payload }; +}, {hello: 'greetings'}); ReduxActions.handleAction<{ hello: { load: boolean } }, { load: boolean }>(act2, (state, action) => { - return { hello: action.payload } -}, {hello: {load: true}}) + return { hello: action.payload }; +}, {hello: {load: true}}); ReduxActions.handleAction(act3, (state, action) => { - return { hello: action.payload.s } -}, {hello: 'greetings'}) + return { hello: action.payload.s }; +}, {hello: 'greetings'}); ReduxActions.handleAction(ReduxActions.combineActions(act, act3, act2), (state, action) => { -}, 0) +}, 0); /* can't do this until it lands in 2.2, HKTs ReduxActions.handleAction(act, (state, action) => { diff --git a/redux-actions/tslint.json b/redux-actions/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/redux-actions/tslint.json +++ b/redux-actions/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/redux-batched-actions/tslint.json b/redux-batched-actions/tslint.json index 192203ab54..377cc837d4 100644 --- a/redux-batched-actions/tslint.json +++ b/redux-batched-actions/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/redux-form/index.d.ts b/redux-form/index.d.ts index 590fe3a633..f36162d684 100644 --- a/redux-form/index.d.ts +++ b/redux-form/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for redux-form v6.3.1 +// Type definitions for redux-form v6.3.3 // Project: https://github.com/erikras/redux-form -// Definitions by: Carson Full , Daniel Lytkin +// Definitions by: Carson Full // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 diff --git a/redux-form/lib/reduxForm.d.ts b/redux-form/lib/reduxForm.d.ts index 512797a39c..dc13fa9a9b 100644 --- a/redux-form/lib/reduxForm.d.ts +++ b/redux-form/lib/reduxForm.d.ts @@ -48,14 +48,14 @@ export interface Config { asyncBlurFields?: string[]; /** - * a function that takes all the form values, the dispatch function, and - * the props given to your component, and returns a Promise that will - * resolve if the validation is passed, or will reject with an object of - * validation errors in the form { field1: , field2: }. + * a function that takes all the form values, the dispatch function, + * the props given to your component and the current blurred field, + * and returns a Promise that will resolve if the validation is passed, + * or will reject with an object of validation errors in the form { field1: , field2: }. * * See Asynchronous Blur Validation Example for more details. */ - asyncValidate?(values: FormData, dispatch: Dispatch, props: P): Promise; + asyncValidate?(values: FormData, dispatch: Dispatch, props: P, blurredField: string): Promise; /** * Whether or not to automatically destroy your form's state in the Redux diff --git a/redux-localstorage-debounce/redux-localstorage-debounce-tests.ts b/redux-localstorage-debounce/redux-localstorage-debounce-tests.ts index bb15d77121..24b5a32528 100644 --- a/redux-localstorage-debounce/redux-localstorage-debounce-tests.ts +++ b/redux-localstorage-debounce/redux-localstorage-debounce-tests.ts @@ -1,21 +1,21 @@ -import { compose } from "redux" +import { compose } from "redux"; import { default as persistState -} from "redux-localstorage" -import * as adapter from "redux-localstorage/lib/adapters/localStorage" -import { default as debounce } from "redux-localstorage-debounce" +} from "redux-localstorage"; +import * as adapter from "redux-localstorage/lib/adapters/localStorage"; +import { default as debounce } from "redux-localstorage-debounce"; const storageWait = compose( debounce(100) -)(adapter(window.localStorage)) -const enhancerWait = persistState(storageWait, "test") +)(adapter(window.localStorage)); +const enhancerWait = persistState(storageWait, "test"); const storageMax = compose( debounce(100, 200) -)(adapter(window.localStorage)) -const enhancerMax = persistState(storageMax, "test") +)(adapter(window.localStorage)); +const enhancerMax = persistState(storageMax, "test"); const storageOpts = compose( debounce(100, { maxWait : 200, foo : "bar" }) -)(adapter(window.localStorage)) -const enhancerOpts = persistState(storageOpts, "test") +)(adapter(window.localStorage)); +const enhancerOpts = persistState(storageOpts, "test"); diff --git a/redux-localstorage-debounce/tslint.json b/redux-localstorage-debounce/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/redux-localstorage-debounce/tslint.json +++ b/redux-localstorage-debounce/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/redux-localstorage-filter/redux-localstorage-filter-tests.ts b/redux-localstorage-filter/redux-localstorage-filter-tests.ts index 83939ea310..5569b22345 100644 --- a/redux-localstorage-filter/redux-localstorage-filter-tests.ts +++ b/redux-localstorage-filter/redux-localstorage-filter-tests.ts @@ -1,16 +1,16 @@ -import { compose } from "redux" +import { compose } from "redux"; import { default as persistState -} from "redux-localstorage" -import * as adapter from "redux-localstorage/lib/adapters/localStorage" -import { default as filter } from "redux-localstorage-filter" +} from "redux-localstorage"; +import * as adapter from "redux-localstorage/lib/adapters/localStorage"; +import { default as filter } from "redux-localstorage-filter"; const storageSingle = compose( filter("foo") -)(adapter(window.localStorage)) -const enhancerSingle = persistState(storageSingle, "test") +)(adapter(window.localStorage)); +const enhancerSingle = persistState(storageSingle, "test"); const storageMulti = compose( filter(["foo", "bar"]) -)(adapter(window.localStorage)) -const enhancerMulti = persistState(storageMulti, "test") +)(adapter(window.localStorage)); +const enhancerMulti = persistState(storageMulti, "test"); diff --git a/redux-localstorage-filter/tslint.json b/redux-localstorage-filter/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/redux-localstorage-filter/tslint.json +++ b/redux-localstorage-filter/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/redux-localstorage/redux-localstorage-tests.ts b/redux-localstorage/redux-localstorage-tests.ts index e0e5ad4bfa..49bf442fcf 100644 --- a/redux-localstorage/redux-localstorage-tests.ts +++ b/redux-localstorage/redux-localstorage-tests.ts @@ -1,33 +1,33 @@ -import { Reducer, compose, combineReducers, createStore } from "redux" +import { Reducer, compose, combineReducers, createStore } from "redux"; import { default as persistState, mergePersistedState, actionTypes -} from "redux-localstorage" -import * as adapterAsyncStorage from "redux-localstorage/lib/adapters/AsyncStorage" -import * as adapterLocalStorage from "redux-localstorage/lib/adapters/localStorage" -import * as adapterSessionStorage from "redux-localstorage/lib/adapters/sessionStorage" +} from "redux-localstorage"; +import * as adapterAsyncStorage from "redux-localstorage/lib/adapters/AsyncStorage"; +import * as adapterLocalStorage from "redux-localstorage/lib/adapters/localStorage"; +import * as adapterSessionStorage from "redux-localstorage/lib/adapters/sessionStorage"; -const AsyncStorage: any = {} +const AsyncStorage: any = {}; -const rootReducer: Reducer = (state: any, action: any) => state +const rootReducer: Reducer = (state: any, action: any) => state; const reducer = compose( mergePersistedState() -)(rootReducer) +)(rootReducer); -const storageAsyncStorage = adapterAsyncStorage(AsyncStorage) -const storageLocalStorage = adapterLocalStorage(window.localStorage) -const storageSessionStorage = adapterSessionStorage(window.sessionStorage) +const storageAsyncStorage = adapterAsyncStorage(AsyncStorage); +const storageLocalStorage = adapterLocalStorage(window.localStorage); +const storageSessionStorage = adapterSessionStorage(window.sessionStorage); const createStoreAsyncStorage = compose( persistState(storageAsyncStorage, "foo") -)(createStore)(reducer) +)(createStore)(reducer); const createStoreLocalStorage = compose( persistState(storageLocalStorage, "foo") -)(createStore)(reducer) +)(createStore)(reducer); const createStoreSessionStorage = compose( persistState(storageSessionStorage, "foo") -)(createStore)(reducer) +)(createStore)(reducer); diff --git a/redux-localstorage/tslint.json b/redux-localstorage/tslint.json index e050abdce9..d032145676 100644 --- a/redux-localstorage/tslint.json +++ b/redux-localstorage/tslint.json @@ -4,4 +4,4 @@ "forbidden-types": false, "no-empty-interface": false } -} \ No newline at end of file +} diff --git a/redux-ui/index.d.ts b/redux-ui/index.d.ts index f38cd16ec1..3b1f8f4a58 100644 --- a/redux-ui/index.d.ts +++ b/redux-ui/index.d.ts @@ -1,53 +1,50 @@ -// Type definitions for redux-ui 0.0.15 +// Type definitions for redux-ui 0.0 // Project: https://github.com/tonyhb/redux-ui // Definitions by: Andy Shu Xin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "redux-ui" { +import * as Redux from 'redux'; - import * as Redux from 'redux'; +export interface uiParams { + // optional key which is used to determine the UI path in which state will + // be stored. if omitted this is randomly generated. + key?: string; - export interface uiParams { - // optional key which is used to determine the UI path in which state will - // be stored. if omitted this is randomly generated. - key?: string; + // optional persist, defaults to false. if set to true persist will keep UI + // state for this component after it unmounts. if set to false the UI state + // will be deleted and recreated when the component remounts + persist?: boolean; - // optional persist, defaults to false. if set to true persist will keep UI - // state for this component after it unmounts. if set to false the UI state - // will be deleted and recreated when the component remounts - persist?: boolean; + // **required**: UI state for the component + state: UIStateShape; - // **required**: UI state for the component - state: UIStateShape; + // optional mergeProps passed to react-redux' @connect + mergeProps?: (stateProps: any, dispatchProps: any, ownProps: any) => any; - // optional mergeProps passed to react-redux' @connect - mergeProps?: (stateProps: any, dispatchProps: any, ownProps: any) => any; - - // optional `options` passed to react-redux @connect - options?: { - pure?: boolean; - withRef?: boolean; - }; - } - - export interface ReduxUIProps { - // The key passed to the decorator from the decorator - // (eg. 'some-decorator' with `@ui('some-decorator')` - uiKey: string; - - // The UI state for the component's `uiKey` - ui: UIStateShape; - - // A function accepting either a name/value pair or object which updates - // state within `uiKey` - updateUI(obj: UIStateShape): void; - updateUI(key: string, value: any): void; - - // A function which resets the state within `uiKey` to its default - resetUI(): void; - } - - export const reducer: Redux.Reducer; - - export default function ui(params?: uiParams): (component: T) => T; + // optional `options` passed to react-redux @connect + options?: { + pure?: boolean; + withRef?: boolean; + }; } + +export interface ReduxUIProps { + // The key passed to the decorator from the decorator + // (eg. 'some-decorator' with `@ui('some-decorator')` + uiKey: string; + + // The UI state for the component's `uiKey` + ui: UIStateShape; + + // A function accepting either a name/value pair or object which updates + // state within `uiKey` + updateUI(obj: UIStateShape): void; + updateUI(key: string, value: any): void; + + // A function which resets the state within `uiKey` to its default + resetUI(): void; +} + +export const reducer: Redux.Reducer; + +export default function ui(params?: uiParams): (component: T) => T; diff --git a/redux-ui/redux-ui-tests.ts b/redux-ui/redux-ui-tests.ts index 63ac16c84e..352e70576d 100644 --- a/redux-ui/redux-ui-tests.ts +++ b/redux-ui/redux-ui-tests.ts @@ -1,10 +1,10 @@ -import * as React from 'react' -import * as Redux from 'redux' -import ui, { ReduxUIProps, reducer } from 'redux-ui' +import * as React from 'react'; +import * as Redux from 'redux'; +import ui, { ReduxUIProps, reducer } from 'redux-ui'; -type UIShape = { +interface UIShape { s: string; -}; +} @ui({ key: 'Root', diff --git a/redux-ui/tslint.json b/redux-ui/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/redux-ui/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/reflux/index.d.ts b/reflux/index.d.ts index 4cef17c03b..58177ee7fe 100644 --- a/reflux/index.d.ts +++ b/reflux/index.d.ts @@ -1,64 +1,59 @@ -// Type definitions for RefluxJS +// Type definitions for RefluxJS 0.4 // Project: https://github.com/reflux/refluxjs // Definitions by: Maurice de Beijer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export = RefluxCore; export as namespace Reflux; -declare module RefluxCore { - - interface StoreDefinition { - listenables?: any[], - init?: Function, - getInitialState?: Function, - [propertyName: string]: any; - } - - interface ListenFn { - (...params: any[]):any, - completed: Function, - failed: Function - } - interface Listenable { - listen: ListenFn - } - - interface Subscription { - stop: Function, - listenable: Listenable - } - - interface Store { - hasListener(listenable: Listenable): boolean, - listenToMany(listenables: Listenable[]): void, - validateListening(listenable: Listenable): string, - listenTo(listenable: Listenable, callback: Function, defaultCallback?: Function): Subscription, - stopListeningTo(listenable: Listenable): boolean, - stopListeningToAll(): void, - fetchInitialState(listenable: Listenable, defaultCallback: Function): void, - trigger(state: any):void; - listen(callback: Function, bindContext: any): Function; - } - - interface ActionsDefinition { - [index: string]:any - } - - interface Actions { - [index: string]: Listenable - } - - function createStore(definition: StoreDefinition): Store; - - function createAction(definition?: ActionsDefinition): any; - - function createActions(definition: ActionsDefinition): any; - function createActions(definitions: string[]): any; - - function connect(store: Store, key?: string):void; - function listenTo(store: Store, handler: string):void; - function setState(state: any):void; - - function ListenerMixin(): any; +interface StoreDefinition { + listenables?: any[]; + init?: Function; + getInitialState?: Function; + [propertyName: string]: any; } + +interface ListenFn { + (...params: any[]): any; + completed: Function; + failed: Function; +} +interface Listenable { + listen: ListenFn; +} + +interface Subscription { + stop: Function; + listenable: Listenable; +} + +interface Store { + hasListener(listenable: Listenable): boolean; + listenToMany(listenables: Listenable[]): void; + validateListening(listenable: Listenable): string; + listenTo(listenable: Listenable, callback: Function, defaultCallback?: Function): Subscription; + stopListeningTo(listenable: Listenable): boolean; + stopListeningToAll(): void; + fetchInitialState(listenable: Listenable, defaultCallback: Function): void; + trigger(state: any): void; + listen(callback: Function, bindContext: any): Function; +} + +interface ActionsDefinition { + [index: string]: any; +} + +interface Actions { + [index: string]: Listenable; +} + +export function createStore(definition: StoreDefinition): Store; + +export function createAction(definition?: ActionsDefinition): any; + +export function createActions(definitions: ActionsDefinition | string[]): any; + +export function connect(store: Store, key?: string): void; +export function listenTo(store: Store, handler: string): void; +export function setState(state: any): void; + +export function ListenerMixin(): any; diff --git a/reflux/reflux-tests.ts b/reflux/reflux-tests.ts index 5094ed9ecc..7a392282fa 100644 --- a/reflux/reflux-tests.ts +++ b/reflux/reflux-tests.ts @@ -1,6 +1,3 @@ - -/// - import Reflux = require("reflux"); import React = require("react"); @@ -15,7 +12,7 @@ var asyncActions = Reflux.createActions({ fireBall: {asyncResult: true} }); -asyncActions.fireBall.listen(function () { +asyncActions.fireBall.listen(function() { // Trigger async action setTimeout(() => this.completed(true), 1000); }); @@ -25,13 +22,12 @@ asyncActions.fireBall.listen(function () { var statusStore = Reflux.createStore({ // Initial setup - init: function () { - + init() { // Register statusUpdate action this.listenTo(asyncActions.fireBall, this.onFireBall); }, // Callback - onFireBall: function (flag: boolean) { + onFireBall(flag: boolean) { var status = flag ? 'ONLINE' : 'OFFLINE'; // Pass on to listeners @@ -48,13 +44,13 @@ var action = Reflux.createAction(); var actions = Reflux.createActions(["fireBall", "magicMissile"]); var Store = Reflux.createStore({ - init: function () { + init() { this.listenToMany(actions); }, - onFireBall: function () { + onFireBall() { // whoooosh! }, - onMagicMissile: function () { + onMagicMissile() { // bzzzzapp! } }); diff --git a/reflux/tslint.json b/reflux/tslint.json new file mode 100644 index 0000000000..f05741c59b --- /dev/null +++ b/reflux/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/request/index.d.ts b/request/index.d.ts index edf31b9a9b..e65c8308d6 100644 --- a/request/index.d.ts +++ b/request/index.d.ts @@ -91,6 +91,8 @@ declare namespace request { qsStringifyOptions?: any; qsParseOptions?: any; json?: any; + jsonReviver?: (key: string, value: any) => any; + jsonReplacer?: (key: string, value: any) => any; multipart?: RequestPart[] | Multipart; agent?: http.Agent | https.Agent; agentOptions?: any; @@ -143,6 +145,7 @@ declare namespace request { export interface RequestResponse extends http.IncomingMessage { request: Options; + body: any; } export interface HttpArchiveRequest { diff --git a/request/request-tests.ts b/request/request-tests.ts index b26149533b..1bd81760c8 100644 --- a/request/request-tests.ts +++ b/request/request-tests.ts @@ -91,6 +91,12 @@ var options: request.Options = { aws: aws, qs: obj, json: value, + jsonReviver: (key: string, value: any) => { + + }, + jsonReplacer: (key: string, value: any) => { + + }, multipart: value, agent: new http.Agent(), agentOptions: value, diff --git a/restify-plugins/index.d.ts b/restify-plugins/index.d.ts index 3ce557374f..68c9131c3b 100644 --- a/restify-plugins/index.d.ts +++ b/restify-plugins/index.d.ts @@ -6,7 +6,7 @@ import {RequestHandler, Server, Request, Response, Route} from 'restify'; import Logger = require('bunyan'); -//*************** This module includes the follow pre plugins, which are intended to be used prior to the routing of a request: +// *************** This module includes the follow pre plugins, which are intended to be used prior to the routing of a request: export namespace pre { /** @@ -45,7 +45,7 @@ export namespace pre { function userAgentConnection( options?: {userAgentRegExp: any} ): RequestHandler; } -//*************** This module includes the following header parser plugins: +// *************** This module includes the following header parser plugins: /** * Check the client's Accept header can be handled by this server. @@ -106,7 +106,7 @@ export function conditionalRequest(): RequestHandler[]; */ export function fullResponse(): RequestHandler; -//************ This module includes the following data parsing plugins: +// ************ This module includes the following data parsing plugins: interface BodyParserOptions { /** @@ -120,22 +120,30 @@ interface BodyParserOptions { mapParams?: boolean; /** - * If req.params should be filled with the contents of files sent through a multipart request. Formidable is used internally for parsing, and a file is denoted as a multipart part with the filename option set in its Content-Disposition. This will only be performed if mapParams is true. + * If req.params should be filled with the contents of files sent through a multipart request. + * Formidable is used internally for parsing, and a file is denoted as a multipart part with the filename option set in its Content-Disposition. + * This will only be performed if mapParams is true. */ mapFiles?: boolean; /** - * If an entry in req.params should be overwritten by the value in the body if the names are the same. For instance, if you have the route /:someval, and someone posts an x-www-form-urlencoded Content-Type with the body someval=happy to /sad, the value will be happy if overrideParams is true, sad otherwise. + * If an entry in req.params should be overwritten by the value in the body if the names are the same. + * For instance, if you have the route /:someval, and someone posts an x-www-form-urlencoded Content-Type with the body someval=happy to /sad, + * the value will be happy if overrideParams is true, sad otherwise. */ overrideParams?: boolean; /** - * A callback to handle any multipart part which is not a file. If this is omitted, the default handler is invoked which may or may not map the parts into req.params, depending on the mapParams-option. + * A callback to handle any multipart part which is not a file. + * If this is omitted, the default handler is invoked which may or may not map the parts into req.params, depending on the mapParams-option. */ multipartHandler?: () => void; /** - * A callback to handle any multipart file. It will be a file if the part have a Content-Disposition with the filename parameter set. This typically happens when a browser sends a form and there is a parameter similar to . If this is not provided, the default behaviour is to map the contents into req.params. + * A callback to handle any multipart file. + * It will be a file if the part have a Content-Disposition with the filename parameter set. + * This typically happens when a browser sends a form and there is a parameter similar to . + * If this is not provided, the default behaviour is to map the contents into req.params. */ multipartFileHandler?: () => void; @@ -263,7 +271,8 @@ interface QueryParserOptions { parseArrays?: boolean; /** - * Default false. Whether `req.query` is a "plain" object -- does not inherit from `Object`. This can be used to allow query params whose names collide with Object methods, e.g. `?hasOwnProperty=blah`. + * Default false. Whether `req.query` is a "plain" object -- does not inherit from `Object`. + * This can be used to allow query params whose names collide with Object methods, e.g. `?hasOwnProperty=blah`. */ plainObjects?: boolean; @@ -292,7 +301,7 @@ interface RequestLogger { */ export function requestLogger(options?: RequestLogger): RequestHandler; -//******************** The module includes the following response plugins: +// ******************** The module includes the following response plugins: /** * expires requests based on current time + delta diff --git a/restify/index.d.ts b/restify/index.d.ts index f53aa0eba9..8a85283d93 100644 --- a/restify/index.d.ts +++ b/restify/index.d.ts @@ -300,6 +300,7 @@ interface HandlerTiming { interface Response extends http.ServerResponse { header: (key: string, value?: any) => any; cache: (type?: any, options?: Object) => any; + noCache: () => any; status: (code: number) => any; send: (status?: any, body?: any, headers?: { [header: string]: string }) => any; json: (status?: any, body?: any, headers?: { [header: string]: string }) => any; @@ -448,6 +449,7 @@ interface Server extends http.Server { } interface ServerOptions { + ca?: string; certificate?: string; key?: string; formatters?: Object; @@ -460,6 +462,7 @@ interface ServerOptions { handleUpgrades?: boolean; router?: Router; httpsServerOptions?: any; + socketio?: boolean; } interface ClientOptions { diff --git a/restify/restify-tests.ts b/restify/restify-tests.ts index dcf7dc4ca6..aa5c7f0e91 100644 --- a/restify/restify-tests.ts +++ b/restify/restify-tests.ts @@ -18,6 +18,7 @@ var server = restify.createServer({ }); server = restify.createServer({ + ca: "test", certificate: "test", key: "test", formatters: {}, @@ -26,7 +27,8 @@ server = restify.createServer({ spdy: {}, version: "", responseTimeHeader: "", - responseTimeFormatter : (durationInMilliseconds: number) => {} + responseTimeFormatter : (durationInMilliseconds: number) => {}, + socketio: false }); server.pre(restify.pre.sanitizePath()); @@ -43,7 +45,7 @@ function send(req: restify.Request, res: restify.Response, next: restify.Next) { req.header('key') === 'val'; req.trailer('key', 'val'); req.trailer('key') === 'val'; - + req.accepts('test') === true; req.accepts(['test']) === true; req.acceptsEncoding('test') === true; @@ -343,7 +345,7 @@ client2.get('/str/mcavage', function(err: any, req: any) { }); }); }); - + client.basicAuth('test', 'password'); client2.basicAuth('test', 'password'); diff --git a/route-parser/tsconfig.json b/route-parser/tsconfig.json index 6f14fe510c..89555e3656 100644 --- a/route-parser/tsconfig.json +++ b/route-parser/tsconfig.json @@ -5,7 +5,9 @@ ], "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, @@ -17,4 +19,4 @@ "noEmit": true, "forceConsistentCasingInFileNames": true } -} +} \ No newline at end of file diff --git a/route-parser/tslint.json b/route-parser/tslint.json index 192203ab54..377cc837d4 100644 --- a/route-parser/tslint.json +++ b/route-parser/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/rrule/test/commonJs.ts b/rrule/test/commonJs.ts index e6a2c86dac..f193febe91 100644 --- a/rrule/test/commonJs.ts +++ b/rrule/test/commonJs.ts @@ -1,2 +1,2 @@ import { RRule } from "rrule"; -let rule: RRule = new RRule({ freq: RRule.WEEKLY }); +const rule: RRule = new RRule({ freq: RRule.WEEKLY }); diff --git a/rrule/test/rrule.ts b/rrule/test/rrule.ts index 733a8546db..461283c45d 100644 --- a/rrule/test/rrule.ts +++ b/rrule/test/rrule.ts @@ -10,13 +10,13 @@ let rule: RRule = new RRule({ }); let x: Date[]; -let y: string[]; +const y: string[] = []; // Get all occurrence dates (Date instances): x = rule.all(); // Get a slice: -x = rule.between(new Date(2012, 7, 1), new Date(2012, 8, 1)) +x = rule.between(new Date(2012, 7, 1), new Date(2012, 8, 1)); // Get an iCalendar RRULE string representation: // The output can be used with RRule.fromString(). @@ -28,36 +28,36 @@ y.push(rule.toText()); // Get full a string representation of all options, // including the default and inferred ones. -y.push(RRule.optionsToString(rule.options)) +y.push(RRule.optionsToString(rule.options)); // Cherry-pick only some options from an rrule: y.push(RRule.optionsToString({ freq: rule.options.freq, dtstart: rule.options.dtstart, -})) +})); -rule = RRule.fromString("FREQ=WEEKLY;DTSTART=20120201T093000Z") +rule = RRule.fromString("FREQ=WEEKLY;DTSTART=20120201T093000Z"); // This is equivalent -rule = new RRule(RRule.parseString("FREQ=WEEKLY;DTSTART=20120201T093000Z")) +rule = new RRule(RRule.parseString("FREQ=WEEKLY;DTSTART=20120201T093000Z")); -var options = RRule.parseString('FREQ=DAILY;INTERVAL=6') -options.dtstart = new Date(2000, 1, 1) -rule = new RRule(options) +var options = RRule.parseString('FREQ=DAILY;INTERVAL=6'); +options.dtstart = new Date(2000, 1, 1); +rule = new RRule(options); rule = new RRule({ freq: RRule.WEEKLY, count: 23 -}) -y.push(rule.toText()) +}); +y.push(rule.toText()); -rule = RRule.fromText('every day for 3 times') +rule = RRule.fromText('every day for 3 times'); -options = RRule.parseText('every day for 3 times') +options = RRule.parseText('every day for 3 times'); // {freq: 3, count: "3"} -options.dtstart = new Date(2000, 1, 1) -rule = new RRule(options) +options.dtstart = new Date(2000, 1, 1); +rule = new RRule(options); // Test arrays -let multipleInstance = new RRule({freq:3, byhour:[6,12,18]}) +const multipleInstance = new RRule({freq: 3, byhour: [6, 12, 18]}); diff --git a/rrule/tslint.json b/rrule/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/rrule/tslint.json +++ b/rrule/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/rsvp/index.d.ts b/rsvp/index.d.ts index f4a8fd0a1a..a831944a8f 100644 --- a/rsvp/index.d.ts +++ b/rsvp/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for RSVP 3.0.9 -// Project: github.com/tildeio/rsvp.js 3.0.9 -// Definitions by: Taylor Brown +// Type definitions for RSVP 3.3.3 +// Project: https://github.com/tildeio/rsvp.js +// Definitions by: Taylor Brown , Mikael Kohlmyr // Definitions: https://github.com/borisyankov/DefinitelyTyped // Some of this file was taken from the type definitions for es6-promise https://github.com/borisyankov/DefinitelyTyped/blob/master/es6-promise/es6-promise.d.ts @@ -220,8 +220,8 @@ declare module RSVP { * having to remember the initial order like you would with all(). * */ - export function hash(promises: Thenable[]): Promise; - export function hash(promises: any[]): Promise; + export function hash(promises: { [key: string]: Thenable }): Promise<{ [key: string]: T }>; + export function hash(promises: { [key: string]: any }): Promise<{ [key: string]: T }>; /** `RSVP.map` is similar to JavaScript's native `map` method, except that it diff --git a/rx-core-binding/index.d.ts b/rx-core-binding/index.d.ts index cf283070e9..54861eb6cb 100644 --- a/rx-core-binding/index.d.ts +++ b/rx-core-binding/index.d.ts @@ -66,7 +66,8 @@ declare namespace Rx { publish(selector: (source: ConnectableObservable) => Observable): Observable; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. - * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, + * then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.share(); @@ -80,7 +81,8 @@ declare namespace Rx { publishValue(selector: (source: ConnectableObservable) => Observable, initialValue: T): Observable; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. - * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, + * then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareValue(42); diff --git a/rx-core-binding/tslint.json b/rx-core-binding/tslint.json index c169b612d0..5e437d39a2 100644 --- a/rx-core-binding/tslint.json +++ b/rx-core-binding/tslint.json @@ -1,8 +1,8 @@ { - "extends": "../tslint.json", - "rules": { - "no-empty-interface": false, - "interface-name": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "no-empty-interface": false, + "interface-name": false, + "no-single-declare-module": false + } } diff --git a/rx-core/index.d.ts b/rx-core/index.d.ts index 62ef95ff80..15b55e93d9 100644 --- a/rx-core/index.d.ts +++ b/rx-core/index.d.ts @@ -50,8 +50,16 @@ declare namespace Rx { distinct(keySelector?: (value: T) => TKey, keySerializer?: (key: TKey) => string): Observable; groupBy(keySelector: (value: T) => TKey, skipElementSelector?: boolean, keySerializer?: (key: TKey) => string): Observable>; groupBy(keySelector: (value: T) => TKey, elementSelector: (value: T) => TElement, keySerializer?: (key: TKey) => string): Observable>; - groupByUntil(keySelector: (value: T) => TKey, skipElementSelector: boolean, durationSelector: (group: GroupedObservable) => Observable, keySerializer?: (key: TKey) => string): Observable>; - groupByUntil(keySelector: (value: T) => TKey, elementSelector: (value: T) => TElement, durationSelector: (group: GroupedObservable) => Observable, keySerializer?: (key: TKey) => string): Observable>; + groupByUntil( + keySelector: (value: T) => TKey, + skipElementSelector: boolean, + durationSelector: (group: GroupedObservable) => Observable, + keySerializer?: (key: TKey) => string): Observable>; + groupByUntil( + keySelector: (value: T) => TKey, + elementSelector: (value: T) => TElement, + durationSelector: (group: GroupedObservable) => Observable, + keySerializer?: (key: TKey) => string): Observable>; } interface ObservableStatic { diff --git a/rx-core/tslint.json b/rx-core/tslint.json index e601518a4d..915d3c55f9 100644 --- a/rx-core/tslint.json +++ b/rx-core/tslint.json @@ -1,9 +1,9 @@ { - "extends": "../tslint.json", - "rules": { - "unified-signatures": false, - "no-empty-interface": false, - "interface-name": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "unified-signatures": false, + "no-empty-interface": false, + "interface-name": false, + "no-single-declare-module": false + } } diff --git a/rx-dom/tslint.json b/rx-dom/tslint.json index 7ec0b302e1..8dd3240216 100644 --- a/rx-dom/tslint.json +++ b/rx-dom/tslint.json @@ -1,8 +1,8 @@ { - "extends": "../tslint.json", - "rules": { - // this package augments Rx with namespace level functions - // it would be particualrly strange to type these functions differently - "forbidden-types": false - } + "extends": "../tslint.json", + "rules": { + // this package augments Rx with namespace level functions + // it would be particualrly strange to type these functions differently + "forbidden-types": false + } } diff --git a/rx-lite-aggregates/index.d.ts b/rx-lite-aggregates/index.d.ts index d09a4868f2..6dd9c76387 100644 --- a/rx-lite-aggregates/index.d.ts +++ b/rx-lite-aggregates/index.d.ts @@ -12,7 +12,7 @@ declare namespace Rx { aggregate(seed: TAcc, accumulator: (acc: TAcc, value: T) => TAcc): Observable; reduce(accumulator: (acc: T, value: T) => T): Observable; - reduce(accumulator: (acc: TAcc, value: T) => TAcc, seed: TAcc): Observable; // TS0.9.5: won't work https://typescript.codeplex.com/discussions/471751 + reduce(accumulator: (acc: TAcc, value: T) => TAcc, seed: TAcc): Observable; any(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; some(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; // alias for any diff --git a/rx-lite-aggregates/tslint.json b/rx-lite-aggregates/tslint.json index bd7d2217e3..a7c18034d5 100644 --- a/rx-lite-aggregates/tslint.json +++ b/rx-lite-aggregates/tslint.json @@ -1,7 +1,7 @@ { - "extends": "../tslint.json", - "rules": { - "unified-signatures": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "unified-signatures": false, + "no-single-declare-module": false + } } diff --git a/rx-lite-async/rx-lite-async-tests.ts b/rx-lite-async/rx-lite-async-tests.ts index a8119fbb82..8c88cc135c 100644 --- a/rx-lite-async/rx-lite-async-tests.ts +++ b/rx-lite-async/rx-lite-async-tests.ts @@ -8,20 +8,20 @@ namespace Rx.Tests.Async { var sch: Rx.IScheduler; function start() { - obsNum = Rx.Observable.start(()=> 10, obsStr, sch); + obsNum = Rx.Observable.start(() => 10, obsStr, sch); obsNum = Rx.Observable.start(() => 10, obsStr); - obsNum = Rx.Observable.start(()=> 10); + obsNum = Rx.Observable.start(() => 10); } function toAsync() { - obsNum = Rx.Observable.toAsync(()=> 1, sch)(); - obsNum = Rx.Observable.toAsync((a1: number)=> a1)(1); - obsStr = Rx.Observable.toAsync((a1: string, a2: number)=> a1 + a2.toFixed(0))("", 1); - obsStr = Rx.Observable.toAsync((a1: string, a2: number, a3: Date)=> a1 + a2.toFixed(0) + a3.toDateString())("", 1, new Date()); - obsStr = Rx.Observable.toAsync((a1: string, a2: number, a3: Date, a4: boolean)=> a1 + a2.toFixed(0) + a3.toDateString() + (a4 ? 1 : 0))("", 1, new Date(), false); + obsNum = Rx.Observable.toAsync(() => 1, sch)(); + obsNum = Rx.Observable.toAsync((a1: number) => a1)(1); + obsStr = Rx.Observable.toAsync((a1: string, a2: number) => a1 + a2.toFixed(0))("", 1); + obsStr = Rx.Observable.toAsync((a1: string, a2: number, a3: Date) => a1 + a2.toFixed(0) + a3.toDateString())("", 1, new Date()); + obsStr = Rx.Observable.toAsync((a1: string, a2: number, a3: Date, a4: boolean) => a1 + a2.toFixed(0) + a3.toDateString() + (a4 ? 1 : 0))("", 1, new Date(), false); } function startAsync() { - var o: Rx.Observable = Rx.Observable.startAsync(() => >{}); + var o: Rx.Observable = Rx.Observable.startAsync(() => > {}); } } diff --git a/rx-lite-async/tslint.json b/rx-lite-async/tslint.json index cfdf2986e5..32344bf0f6 100644 --- a/rx-lite-async/tslint.json +++ b/rx-lite-async/tslint.json @@ -1,6 +1,7 @@ { - "extends": "../tslint.json", - "rules": { - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "max-line-length": false, + "no-single-declare-module": false + } } diff --git a/rx-lite-backpressure/tslint.json b/rx-lite-backpressure/tslint.json index cfdf2986e5..0b14fdec0d 100644 --- a/rx-lite-backpressure/tslint.json +++ b/rx-lite-backpressure/tslint.json @@ -1,6 +1,6 @@ { - "extends": "../tslint.json", - "rules": { - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false + } } diff --git a/rx-lite-coincidence/tslint.json b/rx-lite-coincidence/tslint.json index bd7d2217e3..a7c18034d5 100644 --- a/rx-lite-coincidence/tslint.json +++ b/rx-lite-coincidence/tslint.json @@ -1,7 +1,7 @@ { - "extends": "../tslint.json", - "rules": { - "unified-signatures": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "unified-signatures": false, + "no-single-declare-module": false + } } diff --git a/rx-lite-experimental/tslint.json b/rx-lite-experimental/tslint.json index bd7d2217e3..a7c18034d5 100644 --- a/rx-lite-experimental/tslint.json +++ b/rx-lite-experimental/tslint.json @@ -1,7 +1,7 @@ { - "extends": "../tslint.json", - "rules": { - "unified-signatures": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "unified-signatures": false, + "no-single-declare-module": false + } } diff --git a/rx-lite-joinpatterns/tslint.json b/rx-lite-joinpatterns/tslint.json index 587e1d39df..b3684af44b 100644 --- a/rx-lite-joinpatterns/tslint.json +++ b/rx-lite-joinpatterns/tslint.json @@ -1,8 +1,8 @@ { - "extends": "../tslint.json", - "rules": { - "interface-name": false, - "no-empty-interface": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "interface-name": false, + "no-empty-interface": false, + "no-single-declare-module": false + } } diff --git a/rx-lite-testing/tslint.json b/rx-lite-testing/tslint.json index cfdf2986e5..0b14fdec0d 100644 --- a/rx-lite-testing/tslint.json +++ b/rx-lite-testing/tslint.json @@ -1,6 +1,6 @@ { - "extends": "../tslint.json", - "rules": { - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false + } } diff --git a/rx-lite-time/tslint.json b/rx-lite-time/tslint.json index bd7d2217e3..a7c18034d5 100644 --- a/rx-lite-time/tslint.json +++ b/rx-lite-time/tslint.json @@ -1,7 +1,7 @@ { - "extends": "../tslint.json", - "rules": { - "unified-signatures": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "unified-signatures": false, + "no-single-declare-module": false + } } diff --git a/rx-lite-virtualtime/index.d.ts b/rx-lite-virtualtime/index.d.ts index 617282ccc6..d0907c7168 100644 --- a/rx-lite-virtualtime/index.d.ts +++ b/rx-lite-virtualtime/index.d.ts @@ -7,7 +7,7 @@ declare namespace Rx { export interface VirtualTimeScheduler extends Scheduler { - //protected constructor(initialClock: TAbsolute, comparer: (first: TAbsolute, second: TAbsolute) => number); + // protected constructor(initialClock: TAbsolute, comparer: (first: TAbsolute, second: TAbsolute) => number); advanceBy(time: TRelative): void; advanceTo(time: TAbsolute): void; diff --git a/rx-lite-virtualtime/tslint.json b/rx-lite-virtualtime/tslint.json index 587e1d39df..b3684af44b 100644 --- a/rx-lite-virtualtime/tslint.json +++ b/rx-lite-virtualtime/tslint.json @@ -1,8 +1,8 @@ { - "extends": "../tslint.json", - "rules": { - "interface-name": false, - "no-empty-interface": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "interface-name": false, + "no-empty-interface": false, + "no-single-declare-module": false + } } diff --git a/rx-lite/rx-lite-tests.ts b/rx-lite/rx-lite-tests.ts index 8422bfd9f2..d0f871fcbb 100644 --- a/rx-lite/rx-lite-tests.ts +++ b/rx-lite/rx-lite-tests.ts @@ -54,7 +54,7 @@ namespace Tests.Async { p = p.then(x => x); p = p.then(x => p); p = p.then(undefined, reason => 10); - //p = p.then(undefined, reason => p); + // p = p.then(undefined, reason => p); var ps: Rx.IPromise = p.then(undefined, reason => "error"); ps = p.then(x => ""); @@ -77,17 +77,17 @@ function test_scan() { function test_concatAll() { /* concatAll Example */ var source = Rx.Observable.range(0, 3) - .map(function (x) { return Rx.Observable.range(x, 3); }) + .map(x => Rx.Observable.range(x, 3)) .concatAll(); var subscription = source.subscribe( - function (x) { + x => { console.log('Next: %s', x); }, - function (err) { + err => { console.log('Error: %s', err); }, - function () { + () => { console.log('Completed'); }); } @@ -95,17 +95,17 @@ function test_concatAll() { function test_mergeAll() { /* mergeAll example */ var source = Rx.Observable.range(0, 3) - .map(function (x) { return Rx.Observable.range(x, 3); }) + .map(x => Rx.Observable.range(x, 3)) .mergeAll(); var subscription = source.subscribe( - function (x) { + x => { console.log('Next: %s', x); }, - function (err) { + err => { console.log('Error: %s', err); }, - function () { + () => { console.log('Completed'); }); @@ -117,7 +117,7 @@ function test_publish() { var source = interval .take(2) - .doAction(function (x) { + .doAction(x => { console.log('Side effect'); }); @@ -130,13 +130,13 @@ function test_publish() { function createObserver(tag: string) { return Rx.Observer.create( - function (x) { + x => { console.log('Next: ' + tag + x); }, - function (err) { + err => { console.log('Error: ' + err); }, - function () { + () => { console.log('Completed'); }); } diff --git a/rx-lite/tslint.json b/rx-lite/tslint.json index 9dd4e0d05f..1bec85bd5c 100644 --- a/rx-lite/tslint.json +++ b/rx-lite/tslint.json @@ -1,11 +1,12 @@ { - "extends": "../tslint.json", - "rules": { - "unified-signatures": false, - "no-empty-interface": false, - "forbidden-types": false, - "interface-name": false, - "array-type": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "unified-signatures": false, + "no-empty-interface": false, + "forbidden-types": false, + "interface-name": false, + "array-type": false, + "max-line-length": false, + "no-single-declare-module": false + } } diff --git a/rx/tslint.json b/rx/tslint.json index cfdf2986e5..0b14fdec0d 100644 --- a/rx/tslint.json +++ b/rx/tslint.json @@ -1,6 +1,6 @@ { - "extends": "../tslint.json", - "rules": { - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false + } } diff --git a/samchon-framework/index.d.ts b/samchon-framework/index.d.ts index 558efd674a..fa540e033d 100644 --- a/samchon-framework/index.d.ts +++ b/samchon-framework/index.d.ts @@ -1,10811 +1,13 @@ -// Type definitions for Samchon Framework 2.0 +// Type definitions for Samchon Framework v2.0.x // Project: https://github.com/samchon/framework // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// +// Samchon-Framework is renamed to Samchon declare module "samchon-framework" { + import samchon = require("samchon"); export = samchon; -} - -/** - * # Samchon-Framework - * - *
    - * - * - * Samchon, a OON (Object-Oriented 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 { - /** - * 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.collections { - /** - * A {@link Vector} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *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} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link Vector} - * {@link Vector Vectors}s are sequence containers representing arrays that can change in size. - * - * Just like arrays, {@link Vector}s use contiguous storage locations for their elements, which means that their - * elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in - * arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically - * by the container. - * - * Internally, {@link Vector}s use a dynamically allocated array to store their elements. This array may need to - * be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array - * and moving all elements to it. This is a relatively expensive task in terms of processing time, and thus, - * {@link Vector}s do not reallocate each time an element is added to the container. - * - * Instead, {@link Vector} containers may allocate some extra storage to accommodate for possible growth, and - * thus the container may have an actual {@link capacity} greater than the storage strictly needed to contain its - * elements (i.e., its {@link size}). Libraries can implement different strategies for growth to balance between - * memory usage and reallocations, but in any case, reallocations should only happen at logarithmically growing - * intervals of {@link size} so that the insertion of individual elements at the end of the {@link Vector} can be - * provided with amortized constant time complexity (see {@link push_back push_back()}). - * - * Therefore, compared to arrays, {@link Vector}s consume more memory in exchange for the ability to manage - * storage and grow dynamically in an efficient way. - * - * Compared to the other dynamic sequence containers ({@link Deque}s, {@link List}s), {@link Vector Vectors} are - * very efficient accessing its elements (just like arrays) and relatively efficient adding or removing elements - * from its end. For operations that involve inserting or removing elements at positions other than the end, they - * perform worse than the others, and have less consistent iterators and references than {@link List}s. - * - * - * - * - * - *

    Container properties

    - *
    - *
    Sequence
    - *
    - * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are - * accessed by their position in this sequence. - *
    - * - *
    Dynamic array
    - *
    - * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides - * relatively fast addition/removal of elements at the end of the sequence. - *
    - *
    - * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/vector/vector - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class ArrayCollection extends std.Vector implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - push(...items: T[]): number; - /** - * @inheritdoc - */ - push_back(val: T): void; - /** - * @hidden - */ - 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; - /** - * @hidden - */ - protected _Erase_by_range(first: std.VectorIterator, last: std.VectorIterator): std.VectorIterator; - /** - * @hidden - */ - private notify_insert(first, last); - /** - * @hidden - */ - private notify_erase(first, last); - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.VectorIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.VectorIterator, last: std.VectorIterator): void; - /** - * @inheritdoc - */ - 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: 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: 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: 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; - /** - * @inheritdoc - */ - unshift(...items: U[]): number; - /** - * @inheritdoc - */ - pop(): T; - /** - * @inheritdoc - */ - splice(start: number): T[]; - /** - * @inheritdoc - */ - splice(start: number, deleteCount: number, ...items: T[]): T[]; - } -} -declare namespace samchon.library { - /** - * A basic event class of Samchon Framework. - * - * @reference https://developer.mozilla.org/en-US/docs/Web/API/Event - * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-EventDispatcher - * @author Jeongho Nam - */ - class BasicEvent { - protected type_: string; - protected target_: IEventDispatcher; - private currentTarget_; - protected trusted_: boolean; - protected bubbles_: boolean; - protected cancelable_: boolean; - protected defaultPrevented_: boolean; - protected cancelBubble_: boolean; - private timeStamp_; - constructor(type: string, bubbles?: boolean, cancelable?: boolean); - /** - * @inheritdoc - */ - initEvent(type: string, bubbles: boolean, cancelable: boolean): void; - /** - * @inheritdoc - */ - /** - * @inheritdoc - */ - stopImmediatePropagation(): void; - /** - * @inheritdoc - */ - stopPropagation(): void; - /** - * @inheritdoc - */ - readonly type: string; - /** - * @inheritdoc - */ - target: IEventDispatcher; - /** - * @inheritdoc - */ - readonly currentTarget: IEventDispatcher; - /** - * @inheritdoc - */ - readonly isTrusted: boolean; - /** - * @inheritdoc - */ - readonly bubbles: boolean; - /** - * @inheritdoc - */ - readonly cancelable: boolean; - /** - * @inheritdoc - */ - readonly eventPhase: number; - /** - * @inheritdoc - */ - readonly defaultPrevented: boolean; - /** - * @inheritdoc - */ - readonly srcElement: Element; - /** - * @inheritdoc - */ - readonly cancelBubble: boolean; - /** - * @inheritdoc - */ - readonly timeStamp: number; - /** - * Don't know what it is. - */ - readonly returnValue: boolean; - } -} -declare namespace samchon.collections { - /** - * Type of function pointer for listener of {@link CollectionEvent CollectionEvents}. - */ - type CollectionEventListener = (event: CollectionEvent) => void; -} -declare namespace samchon.collections { - /** - * An event occured in a {@link ICollection collection} object. - * - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class CollectionEvent extends library.BasicEvent { - /** - * @hidden - */ - private first_; - /** - * @hidden - */ - private last_; - /** - * @hidden - */ - private temporary_container_; - /** - * @hidden - */ - private origin_first_; - /** - * Initialization Constructor. - * - * @param type Type of collection event. - * @param first An {@link Iterator} to the initial position in this {@link CollectionEvent}. - * @param last An {@link Iterator} to the final position in this {@link CollectionEvent}. - */ - 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); - /** - * Associative target, the {@link ICollection collection}. - */ - readonly target: ICollection; - /** - * An {@link Iterator} to the initial position in this {@link CollectionEvent}. - */ - readonly first: std.Iterator; - /** - * An {@link Iterator} to the final position in this {@link CollectionEvent}. - */ - readonly last: std.Iterator; - /** - * @inheritdoc - */ - preventDefault(): void; - } -} -declare namespace samchon.collections.CollectionEvent { - const INSERT: "insert"; - const ERASE: "erase"; - const REFRESH: "refresh"; -} -declare namespace samchon.collections { - /** - * A {@link Deque} who can detect element I/O events. - * - * Below is the 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} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link Deque} - * {@link Deque} (usually pronounced like "*deck*") is an irregular acronym of **d**ouble-**e**nded **q**ueue. - * Double-ended queues are sequence containers with dynamic sizes that can be expanded or contracted on both ends - * (either its front or its back). - * - * Specific libraries may implement deques in different ways, generally as some form of dynamic array. But in any - * case, they allow for the individual elements to be accessed directly through random access iterators, with - * storage handled automatically by expanding and contracting the container as needed. - * - * Therefore, they provide a functionality similar to vectors, but with efficient insertion and deletion of - * elements also at the beginning of the sequence, and not only at its end. But, unlike {@link Vector Vectors}, - * {@link Deque Deques} are not guaranteed to store all its elements in contiguous storage locations: accessing - * elements in a deque by offsetting a pointer to another element causes undefined behavior. - * - * Both {@link Vector}s and {@link Deque}s provide a very similar interface and can be used for similar purposes, - * but internally both work in quite different ways: While {@link Vector}s use a single array that needs to be - * occasionally reallocated for growth, the elements of a {@link Deque} can be scattered in different chunks of - * storage, with the container keeping the necessary information internally to provide direct access to any of its - * elements in constant time and with a uniform sequential interface (through iterators). Therefore, - * {@link Deque Deques} are a little more complex internally than {@link Vector}s, but this allows them to grow - * more efficiently under certain circumstances, especially with very long sequences, where reallocations become - * more expensive. - * - * For operations that involve frequent insertion or removals of elements at positions other than the beginning or - * the end, {@link Deque Deques} perform worse and have less consistent iterators and references than - * {@link List Lists}. - * - * - * - * - * - *

    Container properties

    - *
    - *
    Sequence
    - *
    Elements in sequence containers are ordered in a strict linear sequence. Individual elements - * are accessed by their position in this sequence.
    - * - *
    Dynamic array
    - *
    Generally implemented as a dynamic array, it allows direct access to any element in the - * sequence and provides relatively fast addition/removal of elements at the beginning or the end - * of the sequence.
    - *
    - * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/deque/deque/ - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class DequeCollection extends std.Deque implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - push(...items: T[]): number; - /** - * @inheritdoc - */ - push_back(val: T): void; - /** - * @hidden - */ - 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; - /** - * @inheritdoc - */ - pop_back(): void; - /** - * @hidden - */ - protected _Erase_by_range(first: std.DequeIterator, last: std.DequeIterator): std.DequeIterator; - /** - * @hidden - */ - private notify_insert(first, last); - /** - * @hidden - */ - private notify_erase(first, last); - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.DequeIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.DequeIterator, last: std.DequeIterator): void; - /** - * @inheritdoc - */ - 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: 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: 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: 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.collections { - /** - * A {@link HashMap} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link MapCollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link insert_or_assign} - * - {@link emplace} - * - {@link set} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link extract} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link HashMap} - * {@link HashMap HashMaps} are associative containers that store elements formed by the combination of a - * *key value* and a *mapped value*, and which allows for fast retrieval of individual elements based on their - * *keys*. - * - * In an {@link HashMap}, 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 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). - * - * {@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

    - *
    - *
    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*.
    - * - *
    Map
    - *
    Each element associates a *key* to a *mapped value*: - * *Keys* are meant to identify the elements whose main content is the *mapped value*.
    - * - *
    Unique keys
    - *
    No two elements in the container can have equivalent keys.
    - *
    - * - * @param Type of the key values. - * Each element in an {@link HashMap} is uniquely identified by its key value. - * @param Type of the mapped value. - * Each element in an {@link HashMap} is used to store some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/unordered_map/unordered_map - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class HashMapCollection extends std.HashMap implements ICollection> { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.MapIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - 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: 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: 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: 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.collections { - /** - * A {@link HashMultiMap} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link MapCollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link emplace} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link HashMultiMap} - * {@link HashMultiMap 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 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 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). - * - * 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

    - *
    - *
    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*.
    - * - *
    Map
    - *
    Each element associates a *key* to a *mapped value*: - * *Keys* are meant to identify the elements whose main content is the *mapped value*.
    - * - *
    Multiple equivalent keys
    - *
    The container can hold multiple elements with equivalent *keys*.
    - *
    - * - * @param Type of the key values. - * Each element in an {@link HashMultiMap} is identified by a key value. - * @param Type of the 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 - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class HashMultiMapCollection extends std.HashMap implements ICollection> { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.MapIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - 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: 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: 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: 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.collections { - /** - * A {@link HashMultiSet} who can detect element I/O events. - * - * Below is the 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} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link HashMultiSet} - * {@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 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 identify it. *Keys* - * are immutable, therefore, the elements in an {@link HashMultiSet} cannot be modified once in the container - - * they can be inserted and removed, though. - * - * Internally, the elements in the {@link HashMultiSet} are not sorted in any particular, 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). - * - * 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

    - *
    - *
    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.
    - * - *
    Multiple equivalent keys
    - *
    The container can hold multiple elements with equivalent *keys*.
    - *
    - * - * @param Type of the elements. - * Each element in an {@link UnorderedMultiSet} is also identified by this value.. - * - * @reference http://www.cplusplus.com/reference/unordered_set/unordered_multiset - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class HashMultiSetCollection extends std.HashMultiSet implements ICollection { - /** - * 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 - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.SetIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - 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: 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: 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: 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.collections { - /** - * A {@link HashSet} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link push} - * - {@link insert_or_assign} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link extract} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link HashSet} - * {@link HashSet HashSets} 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 - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class HashSetCollection extends std.HashSet implements ICollection { - /** - * 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 - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.SetIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - 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: 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: 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: 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; - } -} -/** - * Collections, elements I/O detectable STL containers. - * - * STL Containers | Collections - * ---------------------|------------------- - * {@link Vector} | {@link ArrayCollection} - * {@link List} | {@link ListCollection} - * {@link Deque} | {@link DequeCollection} - * | - * {@link TreeSet} | {@link TreeSetCollection} - * {@link HashSet} | {@link HashSetCollection} - * {@link TreeMultiSet} | {@link TreeMultiSetCollection} - * {@link HashMultiSet} | {@link HashMultiSetCollection} - * | - * {@link TreeMap} | {@link TreeMapCollection} - * {@link HashMap} | {@link HashMapCollection} - * {@link TreeMultiMap} | {@link TreeMultiMapCollection} - * {@link HashMultiMap} | {@link HashMultiMapCollection} - * - * @author Jeongho Nam - */ -declare namespace samchon.collections { - /** - * 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} - * - *refresh* typed events: - * - {@link refresh} - * - * @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: 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: 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: 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: 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 { - /** - * @hidden - */ - function _Dispatch_CollectionEvent(collection: ICollection, type: string, first: std.Iterator, last: std.Iterator): void; - /** - * @hidden - */ - function _Dispatch_MapCollectionEvent(collection: ICollection>, type: string, first: std.MapIterator, last: std.MapIterator): void; - } -} -declare namespace samchon.collections { - /** - * A {@link List} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *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} - * - *refresh* typed events: - * - {@link refresh} - * - {@link sort} - * - * #### [Inherited] {@link List} - * {@link List Lists} are sequence containers that allow constant time insert and erase operations anywhere within - * the sequence, and iteration in both directions. - * - * List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they - * contain in different and unrelated storage locations. The ordering is kept internally by the association to - * each element of a link to the element preceding it and a link to the element following it. - * - * They are very similar to forward_list: The main difference being that forward_list objects are single-linked - * lists, and thus they can only be iterated forwards, in exchange for being somewhat smaller and more efficient. - * - * Compared to other base standard sequence containers (array, vector and deque), lists perform generally better - * in inserting, extracting and moving elements in any position within the container for which an iterator has - * already been obtained, and therefore also in algorithms that make intensive use of these, like sorting - * algorithms. - * - * The main drawback of lists and forward_lists compared to these other sequence containers is that they lack - * direct access to the elements by their position; For example, to access the sixth element in a list, one has to - * iterate from a known position (like the beginning or the end) to that position, which takes linear time in the - * 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

    - *
    - *
    Sequence
    - *
    Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by - * their position in this sequence.
    - * - *
    Doubly-linked list
    - *
    Each element keeps information on how to locate the next and the previous elements, allowing constant time - * insert and erase operations before or after a specific element (even of entire ranges), but no direct random - * access.
    - *
    - * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/list/list/ - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class ListCollection extends std.List implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - push(...items: T[]): number; - /** - * @inheritdoc - */ - push_front(val: T): void; - /** - * @inheritdoc - */ - push_back(val: T): void; - /** - * @hidden - */ - 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; - /** - * @inheritdoc - */ - pop_front(): void; - /** - * @inheritdoc - */ - pop_back(): void; - /** - * @hidden - */ - protected _Erase_by_range(first: std.ListIterator, last: std.ListIterator): std.ListIterator; - /** - * @hidden - */ - private notify_insert(first, last); - /** - * @hidden - */ - private notify_erase(first, last); - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.ListIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.ListIterator, last: std.ListIterator): void; - /** - * @inheritdoc - */ - 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: 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: 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: 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.collections { - type MapCollectionEventListener = (event: MapCollectionEvent) => void; - /** - * An event occured in a {@link MapContainer map container} object. - * - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class MapCollectionEvent extends CollectionEvent> { - /** - * @inheritdoc - */ - readonly first: std.MapIterator; - /** - * @inheritdoc - */ - readonly last: std.MapIterator; - } -} -declare namespace samchon.collections { - /** - * A {@link TreeMap} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link MapCollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link insert_or_assign} - * - {@link emplace} - * - {@link set} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link extract} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link TreeMap} - * {@link TreeMap TreeMaps} are associative containers that store elements formed by a combination of a - * *key value* (*Key*) and a *mapped value* (*T*), following order. - * - * In a {@link TreeMap}, the *key values* are generally used to sort and uniquely identify the elements, while the - * *mapped values* store the content associated to this key. The types of *key* and *mapped value* may differ, and - * are grouped together in member type *value_type*, which is a {@link Pair} type combining both: - * - * ```typedef Pair value_type;``` - * - * Internally, the elements in a {@link TreeMap} are always sorted by its *key* following a *strict weak ordering* - * criterion indicated by its internal comparison method {@link less}. - * - * {@link TreeMap} containers are generally slower than {@link HashMap HashMap} containers to access individual - * elements by their *key*, but they allow the direct iteration on subsets based on their order. - * - * {@link TreeMap}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.
    - * - *
    Map
    - *
    Each element associates a *key* to a *mapped value*: - * *Keys* are meant to identify the elements whose main content is the *mapped value*.
    - * - *
    Unique keys
    - *
    No two elements in the container can have equivalent *keys*.
    - *
    - * - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/map/map - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class TreeMapCollection extends std.TreeMap implements ICollection> { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.MapIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - 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: 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: 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: 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.collections { - /** - * A {@link TreeMultiMap} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link MapCollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link emplace} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link TreeMultiMap} - * {@link TreeMultiMap TreeMultiMaps} are associative containers that store elements formed by a combination of a - * *key value* and a *mapped value*, following a specific order, and where multiple elements can have equivalent - * keys. - * - * In a {@link TreeMultiMap}, the *key values* are generally used to sort and uniquely identify the elements, - * while the *mapped values* store the content associated to this *key*. The types of *key* and *mapped value* may - * differ, and are grouped together in member type ```value_type```, which is a {@link Pair} type combining both: - * - * ```typedef Pair value_type;``` - * - * Internally, the elements in a {@link TreeMultiMap}are always sorted by its key following a strict weak ordering - * criterion indicated by its internal comparison method (of {@link less}). - * - * {@link TreeMultiMap}containers are generally slower than {@link HashMap} containers to access individual - * elements by their *key*, but they allow the direct iteration on subsets based on their order. - * - * {@link TreeMultiMap TreeMultiMaps} are typically implemented as binary search trees. - * - * < - * img src="http://samchon.github.io/typescript-stl/images/design/class_diagram/map_containers.png" style="max-width: 100%" /> - * - * - *

    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. - *
    - * - *
    Map
    - *
    - * Each element associates a *key* to a *mapped value*: - * *Keys* are meant to identify the elements whose main content is the *mapped value*. - *
    - * - *
    Multiple equivalent keys
    - *
    Multiple elements in the container can have equivalent *keys*.
    - *
    - * - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/map/multimap - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class TreeMultiMapCollection extends std.TreeMultiMap implements ICollection> { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.MapIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - 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: 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: 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: 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.collections { - /** - * A {@link TreeMultiSet} who can detect element I/O events. - * - * Below is the 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} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link TreeMultiSet} - * {@link TreeMultiSet TreeMultiSets} are containers that store elements following a specific order, and where - * multiple elements can have equivalent values. - * - * In a {@link TreeMultiSet}, the value of an element also identifies it (the value is itself the *key*, of type - * *T*). The value of the elements in a {@link TreeMultiSet} cannot be modified once in the container (the - * elements are always const), but they can be inserted or removed from the container. - * - * Internally, the elements in a {@link TreeMultiSet TreeMultiSets} are always sorted following a strict weak - * ordering criterion indicated by its internal comparison method (of {@link IComparable.less less}). - * - * {@link TreeMultiSet} containers are generally slower than {@link HashMultiSet} containers to access individual - * elements by their *key*, but they allow the direct iteration on subsets based on their order. - * - *

    {@link TreeMultiSet TreeMultiSets} 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.
    - * - *
    Multiple equivalent keys
    - *
    Multiple elements in the container can have equivalent *keys*.
    - *
    - * - * @param Type of the elements. Each element in a {@link TreeMultiSet} container is also identified - * by this value (each value is itself also the element's *key*). - * - * @reference http://www.cplusplus.com/reference/set/multiset - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class TreeMultiSetCollection extends std.TreeMultiSet implements ICollection { - /** - * 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 - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.SetIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - 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: 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: 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: 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.collections { - /** - * A {@link TreeMap} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link insert_or_assign} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link extract} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link TreeSet} - * {@link TreeSet TreeSets} 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 container. - * - * 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 - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class TreeSetCollection extends std.TreeSet implements ICollection { - /** - * 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 - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.SetIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - 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: 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: 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: 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.library { - /** - * Case generator. - * - * {@link CaseGenerator} is an abstract case generator being used like a matrix. - *
      - *
    • n��r(n^r) -> {@link CombinedPermutationGenerator}
    • - *
    • nPr -> {@link PermutationGenerator}
    • - *
    • n! -> {@link FactorialGenerator}
    • - *
    - * - * @author Jeongho Nam - */ - abstract class CaseGenerator { - /** - * Size, the number of all cases. - */ - protected size_: number; - /** - * N, size of the candidates. - */ - protected n_: number; - /** - * R, size of elements of each case. - */ - protected r_: number; - /** - * Construct from size of N and R. - * - * @param n Size of candidates. - * @param r Size of elements of each case. - */ - constructor(n: number, r: number); - /** - * Get size of all cases. - * - * @return Get a number of the all cases. - */ - size(): number; - /** - * Get size of the N. - */ - n(): number; - /** - * Get size of the R. - */ - r(): number; - /** - * Get index'th case. - * - * @param index Index number - * @return The row of the index'th in combined permuation case - */ - abstract at(index: number): number[]; - } - /** - * A combined-permutation case generator. - * - * n��r - * - * @author Jeongho Nam - */ - class CombinedPermutationGenerator extends CaseGenerator { - /** - * An array using for dividing each element index. - */ - private divider_array; - /** - * Construct from size of N and R. - * - * @param n Size of candidates. - * @param r Size of elements of each case. - */ - constructor(n: number, r: number); - at(index: number): number[]; - } - /** - * A permutation case generator. - * - * nPr - * - * @author Jeongho Nam - */ - class PermuationGenerator extends CaseGenerator { - /** - * Construct from size of N and R. - * - * @param n Size of candidates. - * @param r Size of elements of each case. - */ - constructor(n: number, r: number); - /** - * @inheritdoc - */ - at(index: number): number[]; - } - /** - * Factorial case generator. - * - * n! = nPn - * - * @author Jeongho Nam - */ - class FactorialGenerator extends PermuationGenerator { - /** - * Construct from factorial size N. - * - * @param n Factoria size N. - */ - constructor(n: number); - } -} -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. - * - * The event 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 target node; and the bubbling phase - * includes any subsequent nodes encountered on the return trip to the root of the display list. - * - * In general, the easiest way for a user-defined class to gain event dispatching capabilities is to extend - * {@link EventDispatcher}. If this is impossible (that is, if the class is already extending another class), you - * can instead implement the {@link IEventDispatcher} interface, create an {@link EventDispatcher} member, and - * write simple hooks to route calls into the aggregated {@link EventDispatcher}. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/IEventDispatcher.html - * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-EventDispatcher - * @author Migrated by Jeongho Nam - */ - interface IEventDispatcher { - /** - * Checks whether the {@link EventDispatcher} object has any listeners registered for a specific type of event. - * This allows you to determine where an {@link EventDispatcher} object has altered handling of an event type - * in the event flow hierarchy. To determine whether a specific event type actually triggers an event listener, - * use {@link willTrigger willTrigger()}. - * - * The difference between {@link hasEventListener hasEventListener()} and {@link willTrigger willTrigger()} is - * that {@link hasEventListener} examines only the object to which it belongs, whereas {@link willTrigger} - * examines the entire event flow for the event specified by the type parameter. - * - * @param type The type of event. - */ - hasEventListener(type: string): boolean; - /** - * Dispatches an event into the event flow. - * - * The event target is the {@link EventDispatcher} object upon which the {@link dispatchEvent dispatchEvent()} - * method is called. - * - * @param event The {@link BasicEvent} object that is dispatched into the event flow. If the event is being - * redispatched, a clone of the event is created automatically. After an event is dispatched, its - * target property cannot be changed, so you must create a new copy - * of the event for redispatching to work. - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * Registers an event listener object with an {@link 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 {@link addEventListener addEventListener()|} To change a listener's priority, you must first call - * {@link removeEventListener 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 {@link 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 {@link 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 {@link 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 {@link EventDispatcher} instance does not copy the event listeners attached to it. (If your n - * ewly created node needs an event listener, you must attach the listener after creating the node.) However, - * if you move an {@link 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. - * @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: string, listener: library.BasicEventListener): void; - /** - * Registers an event listener object with an {@link 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 {@link addEventListener addEventListener()|} To change a listener's priority, you must first call - * {@link removeEventListener 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 {@link 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 {@link 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 {@link 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 {@link EventDispatcher} instance does not copy the event listeners attached to it. (If your n - * ewly created node needs an event listener, you must attach the listener after creating the node.) However, - * if you move an {@link 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. - * @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: library.BasicEventListener, thisArg: Object): void; - /** - * Removes a listener from the {@link EventDispatcher} object. If there is no matching listener registered - * with the {@link EventDispatcher} object, a call to this method has no effect. - * - * @param type The type of event. - * @param listener The listener object to remove. - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - /** - * Removes a listener from the {@link EventDispatcher} object. If there is no matching listener registered - * with the {@link EventDispatcher} object, a call to this method has no effect. - * - * @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: library.BasicEventListener, thisArg: Object): void; - } - /** - * The {@link EventDispatcher} class is the base class for all classes that dispatch events. The - * {@link EventDispatcher} class implements the {@link IEventDispatcher} interface and is the base class for the - * {@link DisplayObject} class. The {@link EventDispatcher} class allows any object on the display list to be an - * event target and as such, to use the methods of the {@link IEventDispatcher} interface. - * - * The event 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 target node; and the bubbling phase - * includes any subsequent nodes encountered on the return trip to the root of the display list. - * - * In general, the easiest way for a user-defined class to gain event dispatching capabilities is to extend - * {@link EventDispatcher}. If this is impossible (that is, if the class is already extending another class), you - * can instead implement the {@link IEventDispatcher} interface, create an {@link EventDispatcher} member, and - * write simple hooks to route calls into the aggregated {@link EventDispatcher}. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/EventDispatcher.html - * @author Migrated by Jeongho Nam - */ - class EventDispatcher implements IEventDispatcher { - /** - * @hidden - */ - private event_dispatcher_; - /** - * @hidden - */ - private event_listeners_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from the origin event dispatcher. - * - * @param dispatcher The origin object who issuing events. - */ - constructor(dispatcher: IEventDispatcher); - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - } -} -declare namespace samchon.library { - /** - * The {@link FileReference} class provides a means to load and save files in browser level. - * - * The {@link FileReference} class provides a means to {@link load} and {@link save} files in browser level. A - * browser-system dialog box prompts the user to select a file to {@link load} or a location for {@link svae}. Each - * {@link FileReference} object refers to a single file on the user's disk and has properties that contain - * information about the file's size, type, name, creation date, modification date, and creator type (Macintosh only). - * - * - * FileReference instances are created in the following ways: - *
      - *
    • - * When you use the new operator with the {@link FileReference} constructor: - * let myFileReference: FileReference = new FileReference(); - *
    • - *
    • - * When you call the {@link FileReferenceList.browse} method, which creates an array of {@link FileReference} - * objects. - *
    • - *
    - * - * During a load operation, all the properties of a {@link FileReference} object are populated by calls to the - * {@link FileReference.browse} or {@link FileReferenceList.browse} methods. During a save operation, the name - * property is populated when the select event is dispatched; all other properties are populated when the complete - * event is dispatched. - * - * The {@link browse browse()} method opens an browser-system dialog box that prompts the user to select a file - * for {@link load}. The {@link FileReference.browse} method lets the user select a single file; the - * {@link FileReferenceList.browse} method lets the user select multiple files. After a successful call to the - * {@link browse browse()} method, call the {@link FileReference.load} method to load one file at a time. The - * {@link FileReference.save} method prompts the user for a location to save the file and initiates downloading from - * a binary or string data. - * - * The {@link FileReference} and {@link FileReferenceList} classes do not let you set the default file location - * for the dialog box that the {@link browse} or {@link save} methods generate. The default location shown in the - * dialog box is the most recently browsed folder, if that location can be determined, or the desktop. The classes do - * not allow you to read from or write to the transferred file. They do not allow the browser that initiated the - * {@link load} or {@link save} to access the loaded or saved file or the file's location on the user's disk. - * - * @references http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html - * @author Jeongho Nam - */ - class FileReference extends EventDispatcher { - /** - * @hidden - */ - private file_; - /** - * @hidden - */ - private data_; - /** - * Default Constructor. - */ - constructor(); - /** - * The data from the loaded file after a successful call to the {@link load load()} method. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly data: any; - /** - * The name of the file on the local disk. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly name: string; - /** - * The filename extension. - * - * A file's extension is the part of the name following (and not including) the final dot ("."). If - * there is no dot in the filename, the extension is null. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly extension: string; - /** - * The file type, metadata of the {@link extension}. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly type: string; - /** - * The size of the file on the local disk in bytes. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly size: number; - /** - * The date that the file on the local disk was last modified. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly modificationDate: Date; - /** - * 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 - * example, through a UNC path on Windows. - * - * When you call this method and the user successfully selects a file, the properties of this - * {@link FileReference} object are populated with the properties of that file. Each subsequent time that the - * {@link FileReference.browse} method is called, the {@link FileReference} object's properties are reset to - * the file that the user selects in the dialog box. Only one {@link browse browse()} can be performed at a time - * (because only one dialog box can be invoked at a time). - * - * Using the *typeFilter parameter*, you can determine which files the dialog box displays. - * - * @param typeFilter An array of filter strings used to filter the files that are displayed in the dialog box. - * If you omit this parameter, all files are displayed. - */ - browse(...typeFilter: string[]): void; - /** - * Starts the load of a local file selected by a user. - * - * You must call the {@link FileReference.browse} or {@link FileReferenceList.browse} method before you call - * the {@link load load()} method. - * - * Listeners receive events to indicate the progress, success, or failure of the load. Although you can use - * the {@link FileReferenceList} object to let users select multiple files to load, you must {@link load} the - * {@link FileReferenceList files} one by one. To {@link load} the files one by one, iterate through the - * {@link FileReferenceList.fileList} array of {@link FileReference} objects. - * - * If the file finishes loading successfully, its contents are stored in the {@link data} property. - */ - load(): 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. - */ - 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 - * {@link FileReference.load loading}. A {@link FileReferenceList} object represents a group of one or more local - * files on the user's disk as an array of {@link FileReference} objects. For detailed information and important - * considerations about {@link FileReference} objects and the FileReference class, which you use with - * {@link FileReferenceList}, see the {@link FileReference} class. - * - * To work with the {@link FileReferenceList} class: - *
      - *
    • Instantiate the class: var myFileRef = new FileReferenceList();
    • - *
    • - * Call the {@link FileReferenceList.browse} method, which opens a dialog box that lets the user select one or - * more files for upload: myFileRef.browse(); - *
    • - *
    • - * After the {@link browse browse()} method is called successfully, the {@link fileList} property of the - * {@link FileReferenceList} object is populated with an array of {@link FileReference} objects. - *
    • - *
    • Call {@link FileReference.load} on each element in the {@link fileList} array.
    • - *
    - * - * The {@link FileReferenceList} class includes a {@link browse browse()} method and a {@link fileList} property - * for working with multiple files. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReferenceList.html - * @author Jeongho Nam - */ - class FileReferenceList extends EventDispatcher { - /** - * @hidden - */ - file_list: std.Vector; - /** - * Default Constructor. - */ - constructor(); - /** - * An array of {@link FileReference} objects. - * - * When the {@link FileReferenceList.browse} method is called and the user has selected one or more files - * from the dialog box that the {@link browse browse()} method opens, this property is populated with an array of - * {@link FileReference} objects, each of which represents the files the user selected. - * - * The {@link fileList} property is populated anew each time {@link browse browse()} is called on that - * {@link FileReferenceList} object. - */ - readonly fileList: std.Vector; - /** - * Displays a file-browsing dialog box that lets the user select one or more local files to upload. The - * dialog box is native to the user's browser system. - * - * When you call this method and the user successfully selects files, the {@link fileList} property of this - * {@link FileReferenceList} object is populated with an array of {@link FileReference} objects, one for each - * file that the user selects. Each subsequent time that the {@link FileReferenceList.browse} method is called, - * the {@link FileReferenceList.fileList} property is reset to the file(s) that the user selects in the dialog - * box. - * - * Using the *typeFilter* parameter, you can determine which files the dialog box displays. - * - * Only one {@link FileReference.browse}, {@link FileReference.load}, or {@link FileReferenceList.browse} - * session can be performed at a time on a {@link FileReferenceList} object (because only one dialog box can be - * opened at a time). - * - * @param typeFilter An array of filter strings used to filter the files that are displayed in the dialog box. - * If you omit this parameter, all files are displayed. - */ - browse(...typeFilter: string[]): void; - } -} -declare namespace samchon.library { - /** - * A genetic algorithm class. - * - * 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); - children(): std.Vector; - /** - * 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. - * 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 { - /** - * Generate a substring. - * - * Extracts a substring consisting of the characters from specified start to end. - * It's same with str.substring( ? = (str.find(start) + start.size()), str.find(end, ?) ) - * - * ```typescript - * let str: string = StringUtil.between("ABCD(EFGH)IJK", "(", ")"); - * console.log(str); // PRINTS "EFGH" - * ``` - * - * - If start is not specified, extracts from begin of the string to end. - * - If end is not specified, extracts from start to end of the string. - * - 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. - * - * @return substring by specified terms. - */ - static between(str: string, start?: string, end?: string): string; - /** - * Fetch substrings. - * - * Splits a string into an array of substrings dividing by specified delimeters of start and end. - * It's the array of substrings adjusted the between. - * - *
      - *
    • If startStr is omitted, it's same with the split by endStr not having last item.
    • - *
    • If endStr is omitted, it's same with the split by startStr not having first item.
    • - *
    • If startStr and endStar are all omitted, returns *str*.
    • - *
    - * - * @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. - * @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. - */ - static betweens(str: string, start?: string, end?: string): Array; - /** - * An array containing whitespaces. - */ - private static SPACE_ARRAY; - /** - * Remove all designated characters from the beginning and end of the specified string. - * - * @param str The string whose designated characters should be trimmed. - * @param args Designated character(s). - * - * @return Updated string where designated characters was removed from the beginning and end. - */ - static trim(str: string, ...args: string[]): string; - /** - * Remove all designated characters from the beginning of the specified string. - * - * @param str The string should be trimmed. - * @param delims Designated character(s). - * - * @return Updated string where designated characters was removed from the beginning - */ - static ltrim(str: string, ...args: string[]): string; - /** - * Remove all designated characters from the end of the specified string. - * - * @param str The string should be trimmed. - * @param delims Designated character(s). - * - * @return Updated string where designated characters was removed from the end. - */ - static rtrim(str: string, ...args: string[]): string; - /** - * Substitute {n} tokens within the specified string. - * - * @param format The string to make substitutions in. This string can contain special tokens of the form - * {n}, where n is a zero based index, that will be replaced with the - * additional parameters found at that index if specified. - * @param args Additional parameters that can be substituted in the *format* parameter at each - * {n} location, where n is an integer (zero based) index value into - * the array of values specified. - * - * @return New string with all of the {n} tokens replaced with the respective arguments specified. - */ - static substitute(format: string, ...args: any[]): string; - /** - * Returns a string specified word is replaced. - * - * @param str Target string to replace - * @param before Specific word you want to be replaced - * @param after Specific word you want to replace - * - * @return A string specified word is replaced - */ - static replaceAll(str: string, before: string, after: string): string; - /** - * Returns a string specified words are replaced. - * - * @param str Target string to replace - * @param pairs A specific word's pairs you want to replace and to be replaced - * - * @return A string specified words are replaced - */ - static replaceAll(str: string, ...pairs: std.Pair[]): 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. - * - * {@link URLVariables} class allows you to transfer variables between an application and server. - * - * When transfering, {@link 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.library { - /** - * A tree-structured XML object. - * - * The {@link XML| class contains methods and properties for working with XML objects. The {@link XML} class (along - * with the {@link XMLList}) implements the powerful XML-handling standards defined in ECMAScript for XML (E4X) - * specification (ECMA-357 edition 2). - * - * An XML object, it is composed with three members; {@link getTag tag}, {@link getProperty properties} and - * {@link getValue value}. As you know, XML is a tree structured data expression method. The tree-stucture; - * {@link XML} class realizes it by extending ```std.HashMap```. Child {@link XML} objects are - * contained in the matched {@link XMLList} object being grouped by their {@link getTag tag name}. The - * {@link XMLList} objects, they're stored in the {@link std.HashMap} ({@link XML} itself) with its **key**; common - * {@link getTag tag name} of children {@link XML} objects. - * - * ```typescript - * class XML extends std.HashMap - * { - * private tag_: string; - * private properties_: std.HashMap; - * private value_: string; - * } - * ``` - * - * ```xml - * - * - * - * {value} - * {value} - * {value} - * - * - * - * - * ``` - * - * Use the {@link toString toString()} method to return a string representation of the {@link XML} object regardless - * of whether the {@link XML} object has simple content or complex content. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/XML.html - * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-XML - * @author Jeongho Nam - */ - class XML extends std.HashMap { - /** - * @hidden - */ - private tag_; - /** - * @hidden - */ - private value_; - /** - * @hidden - */ - private property_map_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from string. - * - * Creates {@link XML} object by parsing a string who represents xml structure. - * - * @param str A string represents XML structure. - */ - constructor(str: string); - /** - * @hidden - */ - private parse(str); - /** - * @hidden - */ - private parse_tag(str); - /** - * @hidden - */ - private parse_properties(str); - /** - * @hidden - */ - private parse_value(str); - /** - * @hidden - */ - private parse_children(str); - /** - * Get tag. - * - * ```xml - * {value} - * ``` - * - * @return tag. - */ - getTag(): string; - /** - * Get value. - * - * ```xml - * {VALUE} - * ``` - * - * @return value. - */ - getValue(): string; - /** - * Get iterator to property element. - * - * Searches the {@link getPropertyMap properties} for an element with a identifier equivalent to key - * and returns an iterator to it if found, otherwise it returns an iterator to {@link HashMap.end end()}. - * - *

    Two keys are considered equivalent if the properties' comparison object returns false reflexively - * (i.e., no matter the order in which the elements are passed as arguments).

    - * - * Another member function, {@link hasProperty hasProperty()} can be used to just check whether a particular - * key exists. - * - * ```xml - * {value} - * ``` - * - * @param key Key to be searched for - * @return An iterator to the element, if an element with specified key is found, or - * {@link end HashMap.end()} otherwise. - */ - findProperty(key: string): std.MapIterator; - /** - * Test whether a property exists. - * - * ```xml - * {value} - * ``` - * - * @return Whether a property has the *key* exists or not. - */ - hasProperty(key: string): boolean; - /** - * Get property. - * - * Get property by its *key*, property name. If the matched *key* does not exist, then exception - * {@link std.OutOfRange} is thrown. Thus, it would better to test whether the *key* exits or not by calling the - * {@link hasProperty hasProperty()} method before calling this {@link getProperty getProperty()}. - * - * This method can be substituted by {@link getPropertyMap getPropertyMap()} such below: - * - ```getPropertyMap().get(key, value);``` - * - ```getPropertyMap().find(key).second;``` - * - * ```xml - * {value} - * ``` - * - * @return Value of the matched property. - */ - getProperty(key: string): string; - /** - * Get property map. - * - * ```xml - * {value} - * ``` - * - * @return {@link HashMap} containing properties' keys and values. - */ - getPropertyMap(): std.HashMap; - /** - * Set tag. - * - * Set tag name, identifier of this {@link XML} object. - * - * If this {@link XML} object is belonged to, a child of, an {@link XMLList} and its related {@link XML} objects, - * then calling this {@link setTag setTag()} method direclty is not recommended. Erase this {@link XML} object - * from parent objects and insert this object again. - * - * ```xml - * {value} - * ``` - * - * @param val To be new {@link getTag tag}. - */ - setTag(val: string): void; - /** - * Set value. - * - * ```xml - * {VALUE} - * ``` - * - * @param val To be new {@link getValue value}. - */ - setValue(val: string): void; - /** - * Set property. - * - * Set a property *value* with its *key*. If the *key* already exists, then the *value* will be overwritten to - * the property. Otherwise the *key* is not exist yet, then insert the *key* and *value* {@link Pair pair} to - * {@link getPropertyMao property map}. - * - * This method can be substituted by {@link getPropertyMap getPropertyMap()} such below: - * - ```getPropertyMap().set(key, value);``` - * - ```getPropertyMap().emplace(key, value);``` - * - ```getPropertyMap().insert([key, value]);``` - * - ```getPropertyMap().insert(std.make_pair(key, value));``` - * - * ```xml - * {value} - * ``` - * - * @param key Key, identifier of property to be newly inserted. - * @param value Value of new property to be newly inserted. - */ - setProperty(key: string, value: string): void; - /** - * Erase property. - * - * Erases a property by its *key*, property name. If the matched *key* does not exist, then exception - * {@link std.OutOfRange} is thrown. Thus, it would better to test whether the *key* exits or not by calling the - * {@link hasProperty hasProperty()} method before calling this {@link eraseProperty eraseProperty()}. - * - * This method can be substituted by ``getPropertyMap().erase(key)````. - * - * ```xml - * {value} - * ``` - * - * @param key Key of the property to erase - * @throw {@link std.OutOfRange} - */ - eraseProperty(key: string): void; - /** - * @hidden - */ - push(...args: std.Pair[]): number; - /** - * @hidden - */ - push(...args: [string, XMLList][]): number; - push(...xmls: XML[]): number; - push(...xmlLists: XMLList[]): number; - /** - * Add all properties from other {@link XML} object. - * - * All the properties in the *obj* are copied to this {@link XML} object. If this {@link XML} object has same - * property key in the *obj*, then value of the property will be replaced to *obj*'s own. If you don't want to - * overwrite properties with same key, then use {@link getPropertyMap getPropertyMap()} method. - * - * ```typescript - * let x: library.XML; - * let y: library.XML; - * - * x.addAllProperties(y); // duplicated key exists, then overwrites - * x.getPropertyMap().insert(y.getPropertyMap().begin(), y.getPropertyMap().end()); - * // ducpliated key, then ignores. only non-duplicateds are copied. - * ``` - * - * ```xml - * {value} - * ``` - * - * @param obj Target {@link XML} object to copy properties. - */ - insertAllProperties(obj: XML): void; - /** - * Clear properties. - * - * Remove all properties. It's same with calling ```getPropertyMap().clear()```. - * - * ```xml - * {value} - * ``` - */ - clearProperties(): void; - /** - * @hidden - */ - private compute_min_index(...args); - /** - * @hidden - */ - private decode_value(str); - /** - * @hidden - */ - private encode_value(str); - /** - * @hidden - */ - private decode_property(str); - /** - * @hidden - */ - private encode_property(str); - /** - * {@link XML} object to xml string. - * - * Returns a string representation of the {@link XML} object. - * - * @param tab Number of tabs to spacing. - * @return The string representation of the {@link XML} object. - */ - toString(tab?: number): string; - } -} -declare namespace samchon.library { - /** - * List of {@link XML} objects with same tag. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/XMLList.html - * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-XML - * @author Jeongho Nam - */ - class XMLList extends std.Deque { - /** - * Get tag. - */ - getTag(): string; - /** - * {@link XMLList XML objects} to string. - * - * Returns a string representation of the {@link XMLList XML objects}. - * - * @param tab Number of tabs to spacing. - * @return The string representation of the {@link XMLList XML objects}. - */ - toString(level?: number): string; - } -} -declare namespace samchon.protocol { - /** - * An interface of entity. - * - * Entity is a class for standardization of expression method using on network I/O by XML. If - * Invoke is a standard message protocol of Samchon Framework which must be kept, Entity is a - * recommended semi-protocol of message for expressing a data class. Following the semi-protocol - * Entity is not imposed but encouraged. - * - * As we could get advantages from standardization of message for network I/O with Invoke, - * we can get additional advantage from standardizing expression method of data class with Entity. - * We do not need to know a part of network communication. Thus, with the Entity, we can only - * concentrate on entity's own logics and relationships between another entities. Entity does not - * need to how network communications are being done. - * - * I say repeatedly. Expression method of Entity is recommended, but not imposed. It's a semi - * protocol for network I/O but not a essential protocol must be kept. The expression method of - * Entity, using on network I/O, is expressed by XML string. - * - * If your own network system has a critical performance issue on communication data class, - * it would be better to using binary communication (with ByteArray). - * Don't worry about the problem! Invoke also provides methods for binary data (ByteArray). - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) - * - * @author Jeongho Nam - */ - interface IEntity { - /** - * Construct data of the Entity from a XML object. - * - * Overrides the construct() method and fetch data of member variables from the XML. - * - * By recommended guidance, data representing member variables are contained in properties - * of the put XML object. - * - * @param xml An xml used to contruct data of entity. - */ - 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 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; - /** - * Get a XML object represents the Entity. - * - * A member variable (not object, but atomic value like number, string or date) is categorized - * as a property within the framework of entity side. Thus, when overriding a toXML() method and - * archiving member variables to an XML object to return, puts each variable to be a property - * belongs to only a XML object. - * - * Don't archive the member variable of atomic value to XML::value causing enormouse creation - * of XML objects to number of member variables. An Entity must be represented by only a XML - * instance (tag). - * - *

    Standard Usage.

    - * - * - * - * - * - * - * - *

    Non-standard usage abusing value.

    - * - * - * jhnam88 - * Jeongho Nam - * 1988-03-11 - * - * - * master - * Administartor - * 2011-07-28 - * - * - * - * @return An XML object representing the Entity. - */ - 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. - * - * Entity is a class for standardization of expression method using on network I/O by XML. If - * Invoke is a standard message protocol of Samchon Framework which must be kept, Entity is a - * recommended semi-protocol of message for expressing a data class. Following the semi-protocol - * Entity is not imposed but encouraged. - * - * As we could get advantages from standardization of message for network I/O with Invoke, - * we can get additional advantage from standardizing expression method of data class with Entity. - * We do not need to know a part of network communication. Thus, with the Entity, we can only - * concentrate on entity's own logics and relationships between another entities. Entity does not - * need to how network communications are being done. - * - * I say repeatedly. Expression method of Entity is recommended, but not imposed. It's a semi - * protocol for network I/O but not a essential protocol must be kept. The expression method of - * Entity, using on network I/O, is expressed by XML string. - * - * If your own network system has a critical performance issue on communication data class, - * it would be better to using binary communication (with ByteArray). - * Don't worry about the problem! Invoke also provides methods for binary data (ByteArray). - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) - * - * @author Jeongho Nam - */ - abstract class Entity implements IEntity { - /** - * Default Constructor. - */ - constructor(); - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - interface IEntityCollection extends IEntityGroup, collections.ICollection { - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityArrayCollection extends collections.ArrayCollection implements IEntityCollection { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityListCollection extends collections.ListCollection implements IEntityCollection { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityDequeCollection extends collections.DequeCollection implements IEntityCollection { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -/** - * A template for External Systems Manager. - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ -declare namespace samchon.templates.external { - /** - * An array and manager of {@link ExternalSystem external system drivers}. - * - * The {@link ExternalSystemArray} is an abstract class containing and managing external system drivers, - * {@link ExternalSystem} objects. Within framewokr of network, {@link ExternalSystemArray} represents your system - * and children {@link ExternalSystem} objects represent remote, external systems connected with your system. - * With this {@link ExternalSystemArray}, you can manage multiple external systems as a group. - * - * You can specify this {@link ExternalSystemArray} class to be *a server accepting external clients* or - * *a client connecting to external servers*. Even both of them is also possible. - * - * - {@link ExternalClientArray}: A server accepting {@link ExternalSystem external clients}. - * - {@link ExternalServerArray}: A client connecting to {@link ExternalServer external servers}. - * - {@link ExternalServerClientArray}: Both of them. Accepts {@link ExternalSystem external clients} and connects to - * {@link ExternalServer external servers} 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*.
    • - *
    - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalSystemArray extends protocol.EntityDequeCollection implements protocol.IProtocol { - /** - * Default Constructor. - */ - constructor(); - /** - * @hidden - */ - private handle_system_erase(event); - /** - * Test whether the role exists. - * - * @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: protocol.Invoke): void; - /** - * Handle an {@Invoke} message have received. - * - * @param invoke An {@link Invoke} message have received. - */ - replyData(invoke: protocol.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; - } -} -/** - * A template for Parallel Processing System. - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ -declare namespace samchon.templates.parallel { - /** - * Master of Parallel Processing System. - * - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to **slave** systems and the - * children {@link ParallelSystem} objects represent the remote **slave** systems, who is being requested the - * *parallel processes*. - * - * You can specify this {@link ParallelSystemArray} class to be *a server accepting parallel clients* or - * *a client connecting to parallel servers*. Even both of them is possible. Extends one of them below and overrides - * abstract factory method(s) creating the child {@link ParallelSystem} object. - * - * - {@link ParallelClientArray}: A server accepting {@link ParallelSystem parallel clients}. - * - {@link ParallelServerArray}: A client connecting to {@link ParallelServer parallel servers}. - * - {@link ParallelServerClientArray}: Both of them. Accepts {@link ParallelSystem parallel clients} and connects to - * {@link ParallelServer parallel servers} at the same time. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelSystemArray extends external.ExternalSystemArray { - /** - * @hidden - */ - private history_sequence_; - /** - * Default Constructor. - */ - constructor(); - /** - * Send an {@link Invoke} message with segment size. - * - * Sends an {@link Invoke} message requesting a **parallel process** with its *segment size*. The {@link Invoke} - * message will be delivered to children {@link ParallelSystem} objects with the *piece size*, which is divided - * from the *segment size*, basis on their {@link ParallelSystem.getPerformance performance indices}. - * - * - If segment size is 100, - * - The segment will be allocated such below: - * - * Name | Performance index | Number of pieces to be allocated | Formula - * --------|-------------------|----------------------------------|-------------- - * Snail | 1 | 10 | 100 / 10 * 1 - * Cheetah | 4 | 40 | 100 / 10 * 4 - * Rabbit | 3 | 30 | 100 / 10 * 3 - * Turtle | 2 | 20 | 100 / 10 * 2 - * - * When the **parallel process** has completed, then this {@link ParallelSystemArraY} will estimate - * {@link ParallelSystem.getPerformance performance indices} of {@link ParallelSystem} objects basis on their - * execution time. - * - * @param invoke An {@link Invoke} message requesting parallel process. - * @param size Number of pieces to segment. - * - * @return Number of {@link ParallelSystem slave systems} participating in the *Parallel Process*. - * - * @see {@link sendPieceData}, {@link ParallelSystem.getPerformacen} - */ - sendSegmentData(invoke: protocol.Invoke, size: number): number; - /** - * Send an {@link Invoke} message with range of pieces. - * - * Sends an {@link Invoke} message requesting a **parallel process** with its *range of pieces [first, last)*. - * The {@link Invoke} will be delivered to children {@link ParallelSystem} objects with the newly computed - * *range of sub-pieces*, which is divided from the *range of pieces (first to last)*, basis on their - * {@link ParallelSystem.getPerformance performance indices}. - * - * - If indices of pieces are 0 to 50, - * - The sub-pieces will be allocated such below: - * - * Name | Performance index | Range of sub-pieces to be allocated | Formula - * --------|-------------------|-------------------------------------|------------------------ - * Snail | 1 | ( 0, 5] | (50 - 0) / 10 * 1 - * Cheetah | 4 | ( 5, 25] | (50 - 0) / 10 * 4 + 5 - * Rabbit | 3 | (25, 40] | (50 - 0) / 10 * 3 + 25 - * Turtle | 2 | (40, 50] | (50 - 0) / 10 * 2 + 40 - * - * When the **parallel process** has completed, then this {@link ParallelSystemArraY} will estimate - * {@link ParallelSystem.getPerformance performance indices} of {@link ParallelSystem} objects basis on their - * execution time. - * - * @param invoke An {@link Invoke} message requesting parallel process. - * @param first Initial piece's index in a section. - * @param last Final piece's index in a section. The range 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*. - * - * @return Number of {@link ParallelSystem slave systems} participating in the *Parallel Process*. - * - * @see {@link sendSegmentData}, {@link ParallelSystem.getPerformacen} - */ - sendPieceData(invoke: protocol.Invoke, first: number, last: number): number; - /** - * @hidden - */ - protected _Complete_history(history: protocol.InvokeHistory): boolean; - /** - * @hidden - */ - protected _Normalize_performance(): void; - } -} -/** - * A template for Distributed Processing System. - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ -declare namespace samchon.templates.distributed { - /** - * Master of Distributed Processing System. - * - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * You can specify this {@link DistributedSystemArray} class to be *a server accepting distributed clients* or - * *a client connecting to distributed servers*. Even both of them is possible. Extends one of them below and overrides - * abstract factory method(s) creating the child {@link DistributedSystem} object. - * - * - {@link DistributedClientArray}: A server accepting {@link DistributedSystem distributed clients}. - * - {@link DistributedServerArray}: A client connecting to {@link DistributedServer distributed servers}. - * - {@link DistributedServerClientArray}: Both of them. Accepts {@link DistributedSystem distributed clients} and - * connects to {@link DistributedServer distributed servers} at the same time. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedSystemArray extends parallel.ParallelSystemArray { - /** - * @hidden - */ - private process_map_; - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * Factory method creating a child {@link DistributedProcess process} object. - * - * @param xml {@link XML} represents the {@link DistributedProcess child} object. - * @return A new {@link DistributedProcess} object. - */ - protected abstract createProcess(xml: library.XML): DistributedProcess; - /** - * Get process map. - * - * Gets an {@link HashMap} containing {@link DistributedProcess} objects with their *key*. - * - * @return An {@link HasmMap> containing pairs of string and {@link DistributedProcess} object. - */ - getProcessMap(): std.HashMap; - /** - * Test whether the process exists. - * - * @param name Name, identifier of target {@link DistributedProcess process}. - * - * @return Whether the process has or not. - */ - hasProcess(name: string): boolean; - /** - * Get a process. - * - * @param name Name, identifier of target {@link DistributedProcess process}. - * - * @return The specified process. - */ - getProcess(name: string): DistributedProcess; - /** - * Insert a process. - * - * @param process A process to be inserted. - * @return Success flag. - */ - insertProcess(process: DistributedProcess): boolean; - /** - * Erase a process. - * - * @param name Name, identifier of target {@link DistributedProcess process}. - */ - eraseProcess(name: string): boolean; - /** - * @hidden - */ - protected _Complete_history(history: protocol.InvokeHistory): boolean; - /** - * @hidden - */ - private estimate_process_resource(history); - /** - * @hidden - */ - private estimate_system_performance(history); - /** - * @hidden - */ - protected _Normalize_performance(): void; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.templates.distributed { - /** - * Mediator of Distributed Processing System. - * - * The {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a slave to its master - * system at the same time. This {@link DistributedSystemArrayMediator} be a master system, containing and managing - * {@link DistributedSystem} objects, which represent distributed slave systems, by extending - * {@link DistributedSystemArray} class. Also, be a slave system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a master, you can specify this {@link DistributedSystemArrayMediator} class to be a master server accepting - * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one - * of them below and overrides abstract factory method(s) creating the child {@link DistributedSystem} object. - * - * - {@link DistributedClientArrayMediator}: A server accepting {@link DistributedSystem distributed clients}. - * - {@link DistributedServerArrayMediator}: A client connecting to {@link DistributedServer distributed servers}. - * - {@link DistributedServerClientArrayMediator}: Both of them. Accepts {@link DistributedSystem distributed clients} and - * connects to {@link DistributedServer distributed servers} at the same time. - * - * As a slave, you can specify this {@link DistributedSystemArrayMediator} to be a client slave connecting to master - * server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedSystemArrayMediator extends DistributedSystemArray { - /** - * @hidden - */ - private mediator_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating a {@link MediatorSystem} object. - * - * The {@link createMediator createMediator()} is an abstract method creating the {@link MediatorSystem} object. - * - * You know what? this {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a - * slave to its master system at the same time. The {@link MediatorSystem} object makes it possible; be a slave - * system. This {@link createMediator} determines specific type of the {@link MediatorSystem}. - * - * Overrides the {@link createMediator createMediator()} method to create and return one of them following which - * protocol and which type of remote connection (server or client) will be used: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * @return A newly created {@link MediatorSystem} object. - */ - protected abstract createMediator(): parallel.MediatorSystem; - /** - * Start mediator. - * - * If the {@link getMediator mediator} is a type of server, then opens the server accepting master client. - * Otherwise, the {@link getMediator mediator} is a type of client, then connects the master server. - */ - protected startMediator(): void; - /** - * Get {@link MediatorSystem} object. - * - * When you need to send an {@link Invoke} message to the master system of this - * {@link DistributedSystemArrayMediator}, then send to the {@link MediatorSystem} through this - * {@link getMediator}. - * - * ```typescript - * this.getMediator().sendData(...); - * ``` - * - * @return The {@link MediatorSystem} object. - */ - getMediator(): parallel.MediatorSystem; - /** - * @hidden - */ - protected _Complete_history(history: parallel.PRInvokeHistory): boolean; - } -} -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 - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link IClientDriver}, {@link IServerConnector}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - interface ICommunicator extends IProtocol { - /** - * Callback function for connection closed. - */ - onClose: Function; - /** - * Close connection. - */ - close(): void; - /** - * Test connection. - * - * Test whether this {@link ICommunicator communicator} object is connected with the remote system. If the - * connection is alive, then returns ```true```. Otherwise, the connection is not alive or this - * {@link ICommunicator communicator has not connected with the remote system yet, then returns ```false```. - * - * @return true if connected, otherwise false. - */ - isConnected(): boolean; - /** - * Send message. - * - * Send {@link Invoke} message to remote system. - * - * @param invoke An {@link Invoke} message to send. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle replied message. - * - * Handles replied {@link Invoke} message recived from remove system. The {@link Invoke} message will be shifted - * to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} by this method. - * - * @param invoke An {@link Invoke} message received from remote system. - */ - replyData(invoke: protocol.Invoke): void; - } -} -declare namespace samchon.protocol { - /** - * An abstract, basic class for communicators. - * - * {@link CommunicatorBase} is an abstract class implemented from the {@link ICommunicator}. Mechanism of converting - * raw data to {@link Invoke} messag has realized in this abstract class. Type of this {@link CommunicatorBase} class - * is specified to as below following which protocol is used. - * - * - {@link Communicator}: Samchon Framework's own protocool. - * - {@link WebCommunicator}: Web-socket protocol - * - {@link SharedWorkerCommunicator}: SharedWorker's message protocol. - * - * #### [Inherited] {@link ICommunicator} - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link IClientDriver}, {@link IServerConnector}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - abstract class CommunicatorBase implements ICommunicator { - /** - * @hidden - */ - protected listener_: IProtocol; - /** - * @inheritdoc - */ - onClose: Function; - /** - * @hidden - */ - protected connected_: boolean; - /** - * @hidden - */ - private binary_invoke_; - /** - * @hidden - */ - private binary_parameters_; - /** - * @hidden - */ - private unhandled_invokes; - /** - * 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; - /** - * @hidden - */ - protected is_binary_invoke(): boolean; - /** - * @inheritdoc - */ - abstract sendData(invoke: Invoke): void; - /** - * @inheritdoc - */ - replyData(invoke: Invoke): void; - /** - * @hidden - */ - protected handle_string(str: string): void; - /** - * @hidden - */ - protected handle_binary(binary: Uint8Array): void; - } -} -declare namespace samchon.protocol { - /** - * A communicator following Samchon Framework's own protocol. - * - * {@link Communicator} is an abstract class following Samchon Framework's own protocol. This {@link Communicator} - * class is specified to {@link ServerConnector} and {@link ClientDriver} whether the remote system is a server (that - * my system is connecting to) or a client (a client conneting to to my server). - * - * Note that, if one of this or remote system is web-browser based, then you don't have to use this - * {@link Communicator} class who follows Samchon Framework's own protocol. Web-browser supports only Web-socket - * protocol. Thus in that case, you have to use {@link WebCommunicator} instead. - * - * #### [Inherited] {@link ICommunicator} - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link ClientDriver}, {@link ServerConnector}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - abstract 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 { - /** - * A communicator following Web-socket protocol. - * - * {@link WebCommunicator} is an abstract class following Web-socket protocol. This {@link WebCommunicator} class is - * specified to {@link WebServerConnector} and {@link WebClientDriver} whether the remote system is a server (that my - * system is connecting to) or a client (a client conneting to to my server). - * - * Note that, one of this or remote system is web-browser based, then there's not any alternative choice. Web browser - * supports only Web-socket protocol. In that case, you've use this {@link WebCommunicator} class. - * - * #### [Inherited] {@link ICommunicator} - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link WebClientDriver}, {@link WebServerConnector}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - abstract class WebCommunicator extends CommunicatorBase { - /** - * @hidden - */ - protected connection_: websocket.connection; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - /** - * @hidden - */ - protected handle_message(message: websocket.IMessage): void; - /** - * @hidden - */ - protected handle_close(): void; - } -} -declare namespace samchon.protocol { - /** - * A communicator for shared worker. - * - * {@link DedicatedWorkerCommunicator} is an abstract class for communication between DedicatedWorker and Web-browser. - * This {@link DedicatedWorkerCommunicator} is specified to {@link DedicatedWorkerServerConnector} and - * {@link DedicatedWorkerClientDriver} whether the remote system is a server (that my system is connecting to) or a - * client (a client conneting to to my server). - * - * #### Why DedicatedWorker be a server? - * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the - * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the - * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network - * communication? Furthermore, there's not any difference between the worker communication and network communication. - * It's the reason why Samchon Framework considers the **Worker** as a network node. - * - * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a - * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the - * server and clients with this {@link DedicatedWorkerCommunicator}. - * - * #### [Inherited] {@link ICommunicator} - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link DedicatedWorkerClientDriver}, {@link DedicatedWorkerServerConnector}, {@link IProtocol} - * @reference https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorker - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - abstract class DedicatedWorkerCommunicator extends CommunicatorBase { - /** - * @hidden - */ - protected handle_message(event: MessageEvent): void; - } -} -declare namespace samchon.protocol { - /** - * A communicator for shared worker. - * - * {@link SharedWorkerCommunicator} is an abstract class for communication between SharedWorker and Web-browser. This - * {@link SharedWorkerCommunicator} is specified to {@link SharedWorkerServerConnector} and - * {@link SharedWorkerClientDriver} whether the remote system is a server (that my system is connecting to) or a client - * (a client conneting to to my server). - * - * Note that, SharedWorker is a conception only existed in web-browser. This {@link SharedWorkerCommunicator} is not - * supported in NodeJS. Only web-browser environment can utilize this {@link SharedWorkerCommunicator}. - * - * #### Why SharedWorker be a server? - * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser - * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship - * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as - * clients. - * - * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a - * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the - * server and clients with this {@link SharedWorkerCommunicator}. - * - * #### [Inherited] {@link ICommunicator} - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link SharedWorkerClientDriver}, {@link SharedWorkerServerConnector}, {@link IProtocol} - * @reference https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - abstract class SharedWorkerCommunicator extends CommunicatorBase { - /** - * @hidden - */ - protected port_: MessagePort; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - /** - * @hidden - */ - protected handle_message(event: MessageEvent): void; - } -} -declare namespace samchon.protocol { - /** - * An interface for communicator with remote client. - * - * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has - * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. - * - * The {@link IClientDriver} object is created and delivered from {@link IServer} and - * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being - * created by the matched {@link IServer} object. - * - * Protocol | Derived Type | Created By - * ------------------------|-------------------------------------|---------------------------- - * Samchon Framework's own | {@link ClientDriver} | {@link Server} - * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} - * - * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then - * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes - * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object - * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * Below code is an example specifying and managing the {@link IProtocol listener} objects. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - * - * - * - * - * @see {@link IServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-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} object. - */ - listen(listener: IProtocol): void; - } -} -declare namespace samchon.protocol { - /** - * Communicator with remote client. - * - * {@link ClientDriver} is a class taking full charge of network communication with remote client who follows Samchon - * Framework's own protocol. This {@link ClientDriver} object is always created by {@link Server} class. When you got - * this {@link ClientDriver} object from the {@link Server.addClient Server.addClient()}, then specify - * {@link IProtocol listener} with the {@link ClientDriver.listen ClientDriver.listen()} method. - * - * #### [Inherited] {@link IClientDriver} - * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has - * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. - * - * The {@link IClientDriver} object is created and delivered from {@link IServer} and - * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being - * created by the matched {@link IServer} object. - * - * Protocol | Derived Type | Created By - * ------------------------|-------------------------------------|---------------------------- - * Samchon Framework's own | {@link ClientDriver} | {@link Server} - * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} - * - * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then - * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes - * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object - * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * Below code is an example specifying and managing the {@link IProtocol listener} objects. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - * - * - * - * - * @see {@link Server}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iclientdriver) - * @author Jeongho Nam - */ - class ClientDriver extends Communicator implements IClientDriver { - /** - * Construct from a socket. - */ - constructor(socket: socket.socket); - /** - * @inheritdoc - */ - listen(listener: IProtocol): void; - } -} -declare namespace samchon.protocol { - /** - * Communicator with remote web-client. - * - * {@link WebClientDriver} is a class taking full charge of network communication with remote client who follows - * Web-socket protocol. This {@link WebClientDriver} object is always created by {@link WebServer} class. When you - * got this {@link WebClientDriver} object from the {@link WebServer.addClient WebServer.addClient()}, then specify - * {@link IProtocol listener} with the {@link WebClientDriver.listen WebClientDriver.listen()} method. - * - * Unlike other protocol, Web-socket protocol's clients notify two parameters on their connection; - * {@link getSessionID session-id} and {@link getPath path}. The {@link getSessionID session-id} can be used to - * identify *user* of each client, and the {@link getPath path} can be used which type of *service* that client wants. - * In {@link service} module, you can see the best utilization case of them. - * - {@link service.User}: utlization of the {@link getSessionID session-id}. - * - {@link service.Service}: utilization of the {@link getPath path}. - * - * #### [Inherited] {@link IClientDriver} - * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has - * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. - * - * The {@link IClientDriver} object is created and delivered from {@link IServer} and - * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being - * created by the matched {@link IServer} object. - * - * Protocol | Derived Type | Created By - * ------------------------|-------------------------------------|---------------------------- - * Samchon Framework's own | {@link ClientDriver} | {@link Server} - * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} - * - * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then - * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes - * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object - * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * Below code is an example specifying and managing the {@link IProtocol listener} objects. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - * - * - * - * - * @see {@link WebServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iclientdriver) - * @author Jeongho Nam - */ - class WebClientDriver extends WebCommunicator implements IClientDriver { - /** - * @hidden - */ - private path_; - /** - * @hidden - */ - private session_id_; - /** - * @hidden - */ - 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 { - /** - * Communicator with master web-browser. - * - * {@link DedicatedWorkerClientDriver} is a class taking full charge of network communication with web browsers. This - * {@link DedicatedWorkerClientDriver} object is always created by {@link DedicatedWorkerServer} class. When you got - * this {@link DedicatedWorkerClientDriver} object from - * {@link DedicatedWorkerServer.addClient DedicatedWorkerServer.addClient()}, then specify {@link IProtocol listener} - * with the {@link DedicatedWorkerClientDriver.listen DedicatedWorkerClientDriver.listen()} method. - * - * #### Why DedicatedWorker be a server? - * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the - * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the - * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network - * communication? Furthermore, there's not any difference between the worker communication and network communication. - * It's the reason why Samchon Framework considers the **Worker** as a network node. - * - * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a - * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the - * server and clients with this {@link DedicatedWorkerCommunicator}. - * - * #### [Inherited] {@link IClientDriver} - * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has - * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. - * - * The {@link IClientDriver} object is created and delivered from {@link IServer} and - * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being - * created by the matched {@link IServer} object. - * - * Protocol | Derived Type | Created By - * ------------------------|-------------------------------------|---------------------------- - * Samchon Framework's own | {@link ClientDriver} | {@link Server} - * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} - * - * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then - * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes - * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object - * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * Below code is an example specifying and managing the {@link IProtocol listener} objects. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - * - * - * - * - * @see {@link DedicatedWorkerServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iclientdriver) - * @author Jeongho Nam - */ - class DedicatedWorkerClientDriver extends DedicatedWorkerCommunicator implements IClientDriver { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - listen(listener: IProtocol): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - } -} -declare namespace samchon.protocol { - /** - * Communicator with remote web-browser. - * - * {@link SharedWorkerClientDriver} is a class taking full charge of network communication with web browsers. This - * {@link SharedWorkerClientDriver} object is always created by {@link SharedWorkerServer} class. When you got this - * {@link SharedWorkerClientDriver} object from {@link SharedWorkerServer.addClient SharedWorkerServer.addClient()}, - * then specify {@link IProtocol listener} with the - * {@link SharedWorkerClientDriver.listen SharedWorkerClientDriver.listen()} method. - * - * #### Why SharedWorker be a server? - * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser - * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship - * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as - * clients. - * - * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a - * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the - * server and clients with this {@link SharedWorkerCommunicator}. - * - * #### [Inherited] {@link IClientDriver} - * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has - * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. - * - * The {@link IClientDriver} object is created and delivered from {@link IServer} and - * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being - * created by the matched {@link IServer} object. - * - * Protocol | Derived Type | Created By - * ------------------------|-------------------------------------|---------------------------- - * Samchon Framework's own | {@link ClientDriver} | {@link Server} - * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} - * - * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then - * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes - * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object - * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * Below code is an example specifying and managing the {@link IProtocol listener} objects. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - * - * - * - * - * @see {@link SharedWorkerServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iclientdriver) - * @author Jeongho Nam - */ - class SharedWorkerClientDriver extends SharedWorkerCommunicator implements IClientDriver { - private listening_; - /** - * Construct from a MessagePort object. - */ - constructor(port: MessagePort); - /** - * @inheritdoc - */ - listen(listener: IProtocol): void; - } -} -declare namespace samchon.protocol { - /** - * A container of entity, and it's a type of entity, too. - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) - * - * @handbook [Protocol - Standard Message](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Standard_Message) - * @author Jeongho Nam - */ - interface IEntityGroup extends IEntity, std.base.IContainer { - /** - * Construct data of the Entity from an XML object. - * - * Constructs the EntityArray's own member variables only from the input XML object. - * - * Do not consider about constructing children Entity objects' data in EntityArray::construct(). - * Those children Entity objects' data will constructed by their own construct() method. Even insertion - * of XML objects representing children are done by abstract method of EntityArray::toXML(). - * - * Constructs only data of EntityArray's own. - */ - 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. - */ - createChild(xml: library.XML): T; - /** - * Get iterator to element. - * - * Searches the container for an element with a identifier equivalent to *key* and returns an - * iterator to it if found, otherwise it returns an iterator to {@link end end()}. - * - * Two keys are considered equivalent if the container's comparison object returns false reflexively - * (i.e., no matter the order in which the elements are passed as arguments). - * - * Another member functions, {@link has has()} and {@link count count()}, can be used to just check - * whether a particular *key* exists. - * - * @param key Key to be searched for - * @return An iterator to the element, if an element with specified *key* is found, or - * {@link end end()} otherwise. - */ - /** - * Whether have the item or not. - * - * Indicates whether a map has an item having the specified identifier. - * - * @param key Key value of the element whose mapped value is accessed. - * - * @return Whether the map has an item having the specified identifier. - */ - has(key: any): boolean; - /** - * Count elements with a specific key. - * - * Searches the container for elements whose key is *key* and returns the number of elements found. - * - * @param key Key value to be searched for. - * - * @return The number of elements in the container with a *key*. - */ - count(key: any): number; - /** - * Get an element - * - * Returns a reference to the mapped value of the element identified with *key*. - * - * @param key Key value of the element whose mapped value is accessed. - * - * @throw exception out of range - * - * @return A reference object of the mapped value (_Ty) - */ - get(key: any): T; - /** - * A tag name of children objects. - */ - CHILD_TAG(): string; - /** - * Get an XML object represents the EntityArray. - * - * Archives the EntityArray's own member variables only to the returned XML object. - * - * Do not consider about archiving children Entity objects' data in EntityArray::toXML(). - * Those children Entity objects will converted to XML object by their own toXML() method. The - * insertion of XML objects representing children are done by abstract method of - * EntityArray::toXML(). - * - * Archives only data of EntityArray's own. - */ - 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 - */ - abstract class EntityArray extends std.Vector implements IEntityGroup { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityList extends std.List implements IEntityGroup { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityDeque extends std.Deque implements IEntityGroup { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * Standard message of network I/O. - * - * {@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 - * network I/O. - * - * The greatest advantage is that we can make any type of network system, even how the system - * is enourmously complicated. As network communication message is standardized, we only need to - * concentrate on logical relationships between network systems. We can handle each network system - * 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 componenets - * (IProtocol, IServer and ICommunicator) by implemens or inherits them, like designing - * classes of S/W architecture. - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) - * - * @see {@link IProtocol} - * @author Jeongho Nam - */ - class Invoke extends EntityArray { - /** - * Listener, represent function's name. - */ - private listener; - /** - * Default Constructor. - */ - constructor(); - constructor(listener: string); - /** - * Copy Constructor. - * - * @param invoke - */ - constructor(invoke: Invoke); - /** - * Construct from listener and parametric values. - * - * @param listener - * @param parameters - */ - constructor(listener: string, ...parameters: Array); - /** - * @inheritdoc - */ - createChild(xml: library.XML): InvokeParameter; - /** - * Get listener. - */ - getListener(): string; - /** - * Get arguments for Function.apply(). - * - * @return An array containing values of the contained parameters. - */ - getArguments(): Array; - /** - * Apply to a matched function. - * - * @param obj Target {@link IProtocol} object to find matched function. - * @return Whether succeded to find matched function. - */ - apply(obj: IProtocol): boolean; - /** - * Apply to a function. - * - * @param thisArg Owner of the function. - * @param func Function to call. - */ - apply(thisArg: IProtocol, func: Function): void; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - CHILD_TAG(): string; - } -} -declare namespace samchon.protocol { - /** - * A parameter belongs to an Invoke. - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) - * - * @author Jeongho Nam - */ - class InvokeParameter extends Entity { - /** - * Name of the parameter. - * - * @details Optional property, can be omitted. - */ - protected name: string; - /** - * Type of the parameter. - */ - protected type: string; - /** - * Value of the parameter. - */ - protected value: string | number | library.XML | Uint8Array; - /** - * Default Constructor. - */ - constructor(); - constructor(val: number); - constructor(val: string); - constructor(val: library.XML); - constructor(val: Uint8Array); - /** - * Construct from variable name and number value. - * - * @param name - * @param val - */ - 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: number): void; - setValue(value: string): void; - setValue(value: library.XML): void; - setValue(value: Uint8Array): void; - /** - * @inheritdoc - */ - key(): any; - /** - * Get name. - */ - getName(): string; - /** - * Get type. - */ - getType(): string; - /** - * Get value. - */ - getValue(): any; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * History of an {@link Invoke} message. - * - * The {@link InvokeHistory} is a class archiving history log of an {@link Invoke} message with elapsed time. This - * {@link InvokeHistory} class is used to report elapsed time of handling a requested process from **slave** to - * **master** system. - * - * The **master** system utilizes derived {@link InvokeHistory} objects to compute performance indices. - * - {@link ParallelSytem.getPerformance} - * - {@link DistributedProcess.getResource} - * - * @author Jeongho Nam - */ - class InvokeHistory extends protocol.Entity { - /** - * @hidden - */ - private uid; - /** - * @hidden - */ - private listener; - /** - * @hidden - */ - private start_time_; - /** - * @hidden - */ - private end_time_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from an {@link Invoke} message. - * - * @param invoke An {@link Invoke} message requesting a *parallel or distributed process*. - */ - constructor(invoke: protocol.Invoke); - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * Complete the history. - * - * Completes the history and determines the {@link getEndTime end time}. - */ - complete(): void; - key(): number; - /** - * Get unique ID. - */ - getUID(): number; - /** - * Get {@link Invoke.getListener listener} of the {@link Invoke} message. - */ - getListener(): string; - /** - * Get start time. - */ - getStartTime(): Date; - /** - * Get end time. - */ - getEndTime(): Date; - /** - * Compute elapsed time. - * - * @return nanoseconds. - */ - computeElapsedTime(): number; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - /** - * Convert to an {@link Invoke} message. - * - * Creates and returns an {@link Invoke} message that is used to reporting to the **master**. - */ - toInvoke(): protocol.Invoke; - } -} -declare namespace samchon.protocol { - /** - * An interface for {@link Invoke} message chain. - * - * {@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. - * - * Implements {@link IProtocol} if the class sends and handles {@link Invoke} messages. Looking around source codes of - * the *Samchon Framework*, especially *Templates*, you can find out that all the classes and modules handling - * {@link Invoke} messages are always implementing this {@link IProtocol}. - * - * - * - * - * - * @see {@link Invoke} - * @handbook https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iprotocol - * @author Jeongho Nam - */ - interface IProtocol { - /** - * Sending message. - * - * Sends message to related system or shifts the responsibility to chain. - * - * @param invoke Invoke message to send - */ - replyData(invoke: Invoke): void; - /** - * Handling replied message. - * - * Handles replied message or shifts the responsibility to chain. - * - * @param invoke An {@link Invoke} message has received. - */ - sendData(invoke: Invoke): void; - } -} -declare namespace samchon.protocol { - /** - * An interface for a server. - * - * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and - * {@link IClientDriver accepting clients}. - * - * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, - * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} - * object. Then at last, call {@link open open()} method with specified port number. - * - * Protocol | Derived Type | Related {@link IClientDriver} - * ------------------------|-------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} - * - * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server} - * - {@link external.ExternalClientArray} - * - {@link slave.SlaveServer} - * - * If you're embarrased because your class already extended another one, then use {@link IServerBase}. - * - * - * - * - * - * @see {@link IClientDriver}, {@link IServerBase} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) - * @author Jeongho Nam - */ - interface IServer { - /** - * Open server. - * - * @param port Port number to open. - */ - open(port: number): void; - /** - * Close server. - * - * Close opened server. All remote clients, have connected with this server, are also closed and their call back - * functions, for closed connection, {@link IClientDriver.onClose} are also called. - */ - close(): void; - /** - * Add a newly connected remote client. - * - * The {@link addClient addClient()} is an abstract method being called when a remote client is newly connected - * with {@link IClientDriver} object who communicates with the remote system. Overrides this method and defines - * what to do with the *driver*, a newly connected remote client. - * - * Below methods and example codes may be good for comprehending how to utilize this {@link addClient} method. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server.addClient} - * - {@link external.ExternalClientArray.addClient} - * - {@link slave.SlaveServer.addClient} - * - * @param driver A {@link ICommunicator communicator} with (newly connected) remote client. - */ - addClient(driver: IClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * A server. - * - * The {@link Server} is an abstract class designed to open a server and accept clients who are following Samchon - * Framework's own protocol. Extends this {@link Server} class and overrides {@link addClient addClient()} method to - * define what to do with newly connected {@link ClientDriver remote clients}. - * - * #### [Inherited] {@link IServer} - * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and - * {@link IClientDriver accepting clients}. - * - * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, - * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} - * object. Then at last, call {@link open open()} method with specified port number. - * - * Protocol | Derived Type | Related {@link IClientDriver} - * ------------------------|-------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} - * - * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server} - * - {@link external.ExternalClientArray} - * - {@link slave.SlaveServer} - * - * If you're embarrased because your class already extended another one, then use {@link IServerBase}. - * - * - * - * - * - * @see {@link ClientDriver}, {@link ServerBase} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) - * @author Jeongho Nam - */ - abstract class Server implements IServer { - /** - * @hidden - */ - private server; - /** - * @inheritdoc - */ - abstract addClient(driver: ClientDriver): void; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @hidden - */ - private handle_connect(socket); - } -} -declare namespace samchon.protocol { - /** - * A web server. - * - * The {@link WebServer} is an abstract class designed to open a server and accept clients who are following - * web-socket protocol. Extends this {@link WebServer} class and overrides {@link addClient addClient()} method to - * define what to do with newly connected {@link WebClientDriver remote clients}. - * - * #### [Inherited] {@link IServer} - * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and - * {@link IClientDriver accepting clients}. - * - * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, - * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} - * object. Then at last, call {@link open open()} method with specified port number. - * - * Protocol | Derived Type | Related {@link IClientDriver} - * ------------------------|-------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} - * - * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server} - * - {@link external.ExternalClientArray} - * - {@link slave.SlaveServer} - * - * If you're embarrased because your class already extended another one, then use {@link IServerBase}. - * - * - * - * - * - * @see {@link WebClientDriver}, {@link WebServerBase} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) - * @author Jeongho Nam - */ - abstract class WebServer implements IServer { - /** - * @hidden - */ - private http_server_; - /** - * @hidden - */ - private sequence_; - /** - * @hidden - */ - private my_port_; - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - abstract addClient(driver: WebClientDriver): void; - /** - * @hidden - */ - private handle_request(request); - /** - * @hidden - */ - private get_session_id(cookies); - /** - * @hidden - */ - private issue_session_id(); - } -} -declare namespace samchon.protocol { - /** - * A SharedWorker server. - * - * The {@link DedicatedWorkerServer} is an abstract class is realized to open a DedicatedWorker server and accept - * web-browser client (master). Extends this {@link DedicatedWorkerServer} class and overrides - * {@link addClient addClient()} method to define what to do with a newly connected - * {@link DedicatedWorkerClientDriver remote client}. - * - * #### Why DedicatedWorker be a server? - * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the - * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the - * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network - * communication? Furthermore, there's not any difference between the worker communication and network communication. - * It's the reason why Samchon Framework considers the **Worker** as a network node. - * - * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a - * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the - * server and clients with this {@link DedicatedWorkerCommunicator}. - * - * #### [Inherited] {@link IServer} - * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and - * {@link IClientDriver accepting clients}. - * - * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, - * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} - * object. Then at last, call {@link open open()} method with specified port number. - * - * Protocol | Derived Type | Related {@link IClientDriver} - * ------------------------|-------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} - * - * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server} - * - {@link external.ExternalClientArray} - * - {@link slave.SlaveServer} - * - * If you're embarrased because your class already extended another one, then use {@link IServerBase}. - * - * - * - * - * - * @see {@link DedicatedWorkerClientDriver}, {@link DedicatedWorkerServerBase} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) - * @author Jeongho Nam - */ - abstract class DedicatedWorkerServer implements IServer { - /** - * @inheritdoc - */ - open(): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - abstract addClient(driver: DedicatedWorkerClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * A SharedWorker server. - * - * The {@link SharedWorker} is an abstract class is realized to open a SharedWorker server and accept web-browser - * clients. Extends this {@link SharedWorkerServer} class and overrides {@link addClient addClient()} method to - * define what to do with newly connected {@link SharedWorkerClientDriver remote clients}. - * - * #### Why SharedWorker be a server? - * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser - * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship - * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as - * clients. - * - * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a - * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the - * server and clients with this {@link SharedWorkerCommunicator}. - * - * #### [Inherited] {@link IServer} - * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and - * {@link IClientDriver accepting clients}. - * - * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, - * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} - * object. Then at last, call {@link open open()} method with specified port number. - * - * Protocol | Derived Type | Related {@link IClientDriver} - * ------------------------|-------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} - * - * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server} - * - {@link external.ExternalClientArray} - * - {@link slave.SlaveServer} - * - * If you're embarrased because your class already extended another one, then use {@link IServerBase}. - * - * - * - * - * - * @see {@link SharedWorkerClientDriver}, {@link SharedWorkerServerBase} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) - * @author Jeongho Nam - */ - abstract class SharedWorkerServer implements IServer { - /** - * @inheritdoc - */ - abstract addClient(driver: SharedWorkerClientDriver): void; - /** - * @inheritdoc - */ - open(): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @hidden - */ - 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 below, who implemented the {@link IServer}. - * 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}. - * - * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} - * ------------------------|-------------------------------|-----------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} - * - * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who - * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with - * specified port number. - * - * ```typescript - * 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}, {@link IClientDriver} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) - * @author Jeongho Nam - */ - interface IServerBase extends IServer { - } -} -declare namespace samchon.protocol { - /** - * A substitute {@link Server}. - * - * The {@link ServerBase} is a substitute class who subrogates {@link Server}'s responsibility. - * - * #### [Inherited] {@link IServerBase} - * {@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 below, who implemented the {@link IServer}. - * 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}. - * - * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} - * ------------------------|-------------------------------|-----------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} - * - * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who - * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with - * specified port number. - * - * ```typescript - * 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 Server}, {@link ClientDriver} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) - * @author Jeongho Nam - */ - class ServerBase extends Server implements IServerBase { - /** - * @hidden - */ - private hooker_; - /** - * Construct from a *hooker*. - * - * @param hooker A hooker throwing responsibility of server's role. - */ - constructor(hooker: IServer); - /** - * @inheritdoc - */ - addClient(driver: IClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * A substitute {@link WebServer}. - * - * The {@link WebServerBase} is a substitute class who subrogates {@link WebServer}'s responsibility. - * - * #### [Inherited] {@link IServerBase} - * {@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 below, who implemented the {@link IServer}. - * 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}. - * - * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} - * ------------------------|-------------------------------|-----------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} - * - * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who - * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with - * specified port number. - * - * ```typescript - * 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 WebServer}, {@link WebClientDriver} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) - * @author Jeongho Nam - */ - class WebServerBase extends WebServer implements IServerBase { - /** - * @hidden - */ - private hooker_; - /** - * Construct from a *hooker*. - * - * @param hooker A hooker throwing responsibility of server's role. - */ - constructor(hooker: IServer); - /** - * @inheritdoc - */ - addClient(driver: IClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * A substitute {@link DedicatedWorkerServer}. - * - * The {@link DedicatedWorkerServerBase} is a substitute class who subrogates {@link DedicatedWorkerServer}'s - * responsibility. - * - * #### [Inherited] {@link IServerBase} - * {@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 below, who implemented the {@link IServer}. - * 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}. - * - * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} - * ------------------------|-------------------------------|-----------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} - * - * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who - * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with - * specified port number. - * - * ```typescript - * 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 DedicatedWorkerServer}, {@link DedicatedWorkerClientDriver} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) - * @author Jeongho Nam - */ - class DedicatedWorkerServerBase extends DedicatedWorkerServer implements IServerBase { - /** - * @hidden - */ - private hooker_; - /** - * Construct from a *hooker*. - * - * @param hooker A hooker throwing responsibility of server's role. - */ - constructor(hooker: IServer); - /** - * @inheritdoc - */ - addClient(driver: IClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * A substitute {@link SharedWorkerServer}. - * - * The {@link SharedWorkerServerBase} is a substitute class who subrogates {@link SharedWorkerServer}'s - * responsibility. - * - * #### [Inherited] {@link IServerBase} - * {@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 below, who implemented the {@link IServer}. - * 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}. - * - * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} - * ------------------------|-------------------------------|-----------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} - * - * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who - * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with - * specified port number. - * - * ```typescript - * 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 SharedWorkerServer}, {@link SharedWorkerClientDriver} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) - * @author Jeongho Nam - */ - class SharedWorkerServerBase extends SharedWorkerServer implements IServerBase { - /** - * @hidden - */ - private hooker_; - /** - * Construct from a *hooker*. - * - * @param hooker A hooker throwing responsibility of server's role. - */ - constructor(hooker: IServer); - /** - * @inheritdoc - */ - addClient(driver: IClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * An interface for server connector. - * - * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to - * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full - * charge of network communication with the remote server. - * - * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the - * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will - * be converted to an {@link Invoke} object and the {@link Invoke} object will be shifted to the - * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. Below code is an example - * connecting to remote server and interacting with it. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-application.ts - * - * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of - * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. - * - * Protocol | Derived Type | Connect to - * ------------------------|----------------------------------------|------------------------------- - * Samchon Framework's own | {@link ServerConnector} | {@link Server} - * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) - * - * @see {@link IServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) - * @author Jeongho Nam - */ - interface IServerConnector extends ICommunicator { - /** - * Callback function for connection completed. - * - * When you call {@link connect connect()} and the connection has completed, then this call back function - * {@link onConnect} will be called. Note that, if the listener of this {@link onConnect} is a member method of - * some class, then you've use the ```bind```. - */ - 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 { - /** - * Server connnector. - * - * {@link ServerConnector} is a class connecting to remote server who follows Samchon Framework's own protocol and - * taking full charge of network communication with the remote server. Create a {@link ServerConnector} instance from - * the {@IProtocol listener} and call the {@link connect connect()} method. - * - * #### [Inherited] {@link IServerConnector} - * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to - * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full - * charge of network communication with the remote server. - * - * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the - * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will - * be converted to an {@link Invoke} object and the {@link Invoke} object will be shifted to the - * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * - * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of - * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. - * - * Protocol | Derived Type | Connect to - * ------------------------|----------------------------------------|------------------------------- - * Samchon Framework's own | {@link ServerConnector} | {@link Server} - * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) - * - * @see {@link Server}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) - * @author Jeongho Nam - */ - class ServerConnector extends Communicator implements IServerConnector { - /** - * @inheritdoc - */ - onConnect: Function; - /** - * Construct from *listener*. - * - * @param listener A listener object to listen replied message from newly connected client in - * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. - */ - constructor(listener: IProtocol); - /** - * @inheritdoc - */ - connect(ip: string, port: number): void; - /** - * @hidden - */ - private handle_connect(...arg); - } -} -declare namespace samchon.protocol { - /** - * A server connector for web-socket protocol. - * - * {@link WebServerConnector} is a class connecting to remote server who follows Web-socket protocol and taking full - * charge of network communication with the remote server. Create an {@link WebServerConnector} instance from the - * {@IProtocol listener} and call the {@link connect connect()} method. - * - * #### [Inherited] {@link IServerConnector} - * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to - * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full - * charge of network communication with the remote server. - * - * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the - * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will - * be converted to an {@link Invoke} class and the {@link Invoke} object will be shifted to the - * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * - * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of - * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. - * - * Protocol | Derived Type | Connect to - * ------------------------|----------------------------------------|------------------------------- - * Samchon Framework's own | {@link ServerConnector} | {@link Server} - * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) - * - * @see {@link WebServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) - * @author Jeongho Nam - */ - class WebServerConnector extends WebCommunicator implements IServerConnector { - /** - * @hidden - */ - private browser_socket_; - /** - * @hidden - */ - private node_client_; - /** - * @inheritdoc - */ - onConnect: Function; - /** - * Construct from *listener*. - * - * @param listener A listener object to listen replied message from newly connected client in - * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. - */ - constructor(listener: IProtocol); - /** - * Connect to a web server. - * - * Connects to a server with specified *host* address, *port* number and *path*. 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. - * @param path Path of service which you want. - */ - connect(ip: string, port: number, path?: string): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - /** - * @hidden - */ - private handle_browser_connect(event); - /** - * @hidden - */ - private handle_browser_message(event); - /** - * @hidden - */ - private handle_node_connect(connection); - } -} -declare namespace samchon.protocol { - /** - * A server connector for DedicatedWorker. - * - * {@link DedicatedWorkerServerConnector} is a class connecting to SharedWorker and taking full charge of network - * communication with the SharedWorker. Create an {@link DedicatedWorkerServer} instance from the - * {@IProtocol listener} and call the {@link connect connect()} method. - * - * #### Why DedicatedWorker be a server? - * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the - * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the - * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network - * communication? Furthermore, there's not any difference between the worker communication and network communication. - * It's the reason why Samchon Framework considers the **Worker** as a network node. - * - * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a - * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the - * server and clients with this {@link DedicatedWorkerCommunicator}. - * - * #### [Inherited] {@link IServerConnector} - * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to - * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full - * charge of network communication with the remote server. - * - * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the - * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will - * be converted to an {@link Invoke} class and the {@link Invoke} object will be shifted to the - * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * - * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of - * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. - * - * Protocol | Derived Type | Connect to - * ------------------------|----------------------------------------|------------------------------- - * Samchon Framework's own | {@link ServerConnector} | {@link Server} - * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) - * - * @see {@link DedicatedWorkerServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) - * @author Jeongho Nam - */ - class DedicatedWorkerServerConnector extends DedicatedWorkerCommunicator implements IServerConnector { - /** - * @hidden - */ - private worker; - /** - * @inheritdoc - */ - onConnect: Function; - /** - * Construct from *listener*. - * - * @param listener A listener object to listen replied message from newly connected client in - * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. - */ - constructor(listener: IProtocol); - /** - * @inheritdoc - */ - connect(jsFile: string): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - } -} -declare namespace samchon.protocol { - /** - * A server connector for SharedWorker. - * - * {@link SharedWorkerServerConnector} is a class connecting to SharedWorker and taking full charge of network - * communication with the SharedWorker. Create an {@link SharedWorkerServerConnector} instance from the - * {@IProtocol listener} and call the {@link connect connect()} method. - * - * #### Why SharedWorker be a server? - * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser - * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship - * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as - * clients. - * - * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a - * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the - * server and clients with this {@link SharedWorkerCommunicator}. - * - * #### [Inherited] {@link IServerConnector} - * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to - * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full - * charge of network communication with the remote server. - * - * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the - * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will - * be converted to an {@link Invoke} class and the {@link Invoke} object will be shifted to the - * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * - * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of - * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. - * - * Protocol | Derived Type | Connect to - * ------------------------|----------------------------------------|------------------------------- - * Samchon Framework's own | {@link ServerConnector} | {@link Server} - * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) - * - * @see {@link SharedWorkerServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) - * @author Jeongho Nam - */ - class SharedWorkerServerConnector extends SharedWorkerCommunicator implements IServerConnector { - /** - * @inheritdoc - */ - onConnect: Function; - /** - * Construct from *listener*. - * - * @param listener A listener object to listen replied message from newly connected client in - * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. - */ - constructor(listener: IProtocol); - /** - * Connect to a SharedWorker. - * - * Connects to a server with specified *jstFile* path. If a SharedWorker instance of the *jsFile* is not - * constructed yet, then the SharedWorker will be newly constructed. Otherwise the SharedWorker already exists, - * then connect to the SharedWorker. After those processes, 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 jsFile Path of JavaScript file to execute who defines SharedWorker. - */ - connect(jsFile: string): void; - } -} -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; - type IMessage = any; - type ICookie = any; - type client = any; - } -} -declare namespace samchon.templates.distributed { - /** - * Master of Distributed Processing System, a server accepting slave clients. - * - * The {@link DistributedClientArray} is an abstract class, derived from the {@link DistributedSystemArray} class, - * opening a server accepting {@link DistributedSystem distributed clients}. - * - * Extends this {@link DistributedClientArray}, overrides {@link createServerBase createServerBase()} to determine - * which protocol to follow and {@link createExternalClient createExternalClient()} creating child - * {@link DistributedSystem} object. After the extending and overridings, open this server using the - * {@link open open()} method. - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedClientArray extends DistributedSystemArray implements external.IExternalClientArray { - /** - * @hidden - */ - 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. - * - * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - * - * @return A new {@link IServerBase} object. - */ - protected abstract createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, - * then this {@link ParallelClientArray} creates a child {@link ParallelSystem parallel client} object through - * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. - * - * @param driver A communicator for external client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * (Deprecated) Factory method creating child object. - * - * The method {@link createChild createChild()} is deprecated. Don't use and override this. - * - * Note that, the {@link ParallelClientArray} is a server accepting {@link ParallelSystem parallel clients}. - * There's no way to creating the {@link ParallelSystem parallel clients} in advance before opening the server. - * - * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. - * @return ```null``` - */ - createChild(xml: library.XML): System; - /** - * Factory method creating {@link DistributedSystem} object. - * - * The method {@link createExternalClient createExternalClient()} is a factory method creating a child - * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by - * {@link addClient addClient()}. - * - * Overrides this {@link createExternalClient} method and creates a type of {@link DistributedSystem} object with - * the *driver* that communicates with the parallel client. After the creation, returns the object. Then whenever - * a parallel client has connected, matched {@link DistributedSystem} object will be constructed and - * {@link insert inserted} into this {@link DistributedSystemArray} object. - * - * @param driver A communicator with the parallel client. - * @return A newly created {@link ParallelSystem} object. - */ - protected abstract createExternalClient(driver: protocol.IClientDriver): System; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * Mediator of Distributed Processing System, a server accepting slave clients. - * - * The {@link DistributedClientArrayMediator} is an abstract class, derived from {@link DistributedSystemArrayMediator} - * class, opening a server accepting {@link DistributedSystem distributed clients} as a **master**. - * - * Extends this {@link DistributedClientArrayMediator}, overrides {@link createServerBase createServerBase()} to - * determine which protocol to follow and {@link createExternalClient createExternalClient()} creating child - * {@link DistributedSystem} object. After the extending and overridings, open this server using the - * {@link open open()} method. - * - * #### [Inherited] {@link DistributedSystemArrayMediator} - * The {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a slave to its master - * system at the same time. This {@link DistributedSystemArrayMediator} be a master system, containing and managing - * {@link DistributedSystem} objects, which represent distributed slave systems, by extending - * {@link DistributedSystemArray} class. Also, be a slave system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a slave, you can specify this {@link DistributedSystemArrayMediator} to be a client slave connecting to master - * server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - 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 - * {@link DistributedClientArrayMediator} object as a **master**. If the protocol is determined, then - * {@link DistributedSystem distributed clients} who may connect to {@link DistributedClientArrayMediator this - * server} must follow the specified protocol. - * - * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - * - * @return A new {@link IServerBase} object. - */ - protected abstract createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * When a {@link IClientDriver remote client} connects to this *master server of distributed processing system*, - * then this {@link DistributedClientArrayMediator} creates a child {@link Distributed distributed client} object - * through the {@link createExternalClient createExternalClient()} method. - * - * @param driver A communicator for external client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * (Deprecated) Factory method creating child object. - * - * The method {@link createChild createChild()} is deprecated. Don't use and override this. - * - * Note that, the {@link DistributedClientArrayMediator} is a server accepting {@link DistributedSystem distributed - * clients} as a master. There's no way to creating the {@link DistributedSystem distributed clients} in advance - * before opening the server. - * - * @param xml An {@link XML} object represents the child {@link DistributedSystem} object. - * @return null - */ - createChild(xml: library.XML): System; - /** - * Factory method creating {@link DistributedSystem} object. - * - * The method {@link createExternalClient createExternalClient()} is a factory method creating a child - * {@link DistributedSystem} object, that is called whenever a distributed client has connected, by - * {@link addClient addClient()}. - * - * Overrides this {@link createExternalClient} method and creates a type of {@link DistributedSystem} object with - * the *driver* that communicates with the distributed client. After the creation, returns the object. Then whenever - * a distributed client has connected, matched {@link DistributedSystem} object will be constructed and - * {@link insert inserted} into this {@link DistributedClientArrayMediator} object. - * - * @param driver A communicator with the distributed client. - * @return A newly created {@link DistributedSystem} object. - */ - protected abstract createExternalClient(driver: protocol.IClientDriver): System; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * A process of Distributed Processing System. - * - * The {@link DistributedProcess} is an abstract class who represents a **process**, *SOMETHING TO DISTRIBUTE* in a Distributed - * Processing System. Overrides the {@link DistributedProcess} and defines the *SOMETHING TO DISTRIBUTE*. - * - * Relationship between {@link DistributedSystem} and {@link DistributedProcess} objects are **M: N Associative**. - * Unlike {@link ExternalSystemRole}, the {@link DistributedProcess} objects are not belonged to a specific - * {@link DistributedSystem} object. The {@link DistributedProcess} objects are belonged to the - * {@link DistributedSystemArrayMediator} directly. - * - * When you need the **distributed process**, then call {@link sendData sendData()}. The {@link sendData} will find - * the most idle {@link DistributedSystem slave system} considering not only number of processes on progress, but also - * {@link DistributedSystem.getPerformance performance index} of each {@link DistributedSystem} object and - * {@link getResource resource index} of this {@link DistributedProcess} object. The {@link Invoke} message - * requesting the **distributed process** will be sent to the most idle {@link DistributedSystem slave system}. - * - * Those {@link DistributedSystem.getPerformance performance index} and {@link getResource resource index} are - * revaluated whenever the **distributed process** has completed basis on the execution time. - * - * - * - * - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedProcess extends protocol.Entity implements protocol.IProtocol { - /** - * @hidden - */ - private system_array_; - /** - * A name, represents and identifies this {@link DistributedProcess process}. - * - * This {@link name} is an identifier represents this {@link DistributedProcess process}. This {@link name} is - * used in {@link DistributedSystemArray.getProcess} and {@link DistributedSystemArray.getProcess}, as a key elements. - * Thus, this {@link name} should be unique in its parent {@link DistributedSystemArray} object. - */ - protected name: string; - /** - * @hidden - */ - private progress_list_; - /** - * @hidden - */ - private history_list_; - /** - * @hidden - */ - private resource; - /** - * @hidden - */ - private enforced_; - /** - * Constrct from parent {@link DistributedSystemArray} object. - * - * @param systemArray The parent {@link DistributedSystemArray} object. - */ - constructor(systemArray: DistributedSystemArray); - /** - * Identifier of {@link ParallelProcess} is its {@link name}. - */ - key(): string; - /** - * Get parent {@link DistributedSystemArray} object. - * - * @return The parent {@link DistributedSystemArray} object. - */ - getSystemArray(): DistributedSystemArray; - /** - * Get parent {@link DistributedSystemArray} object. - * - * @return The parent {@link DistributedSystemArray} object. - */ - getSystemArray>(): SystemArray; - /** - * Get name, who represents and identifies this process. - */ - getName(): string; - /** - * Get resource index. - * - * Get *resource index* that indicates how much this {@link DistributedProcess process} is heavy. - * - * If this {@link DistributedProcess process} does not have any {@link Invoke} message had handled, then the - * *resource index* will be ```1.0```, which means default and average value between all - * {@link DistributedProcess} instances (that are belonged to a same {@link DistributedSystemArray} object). - * - * You can specify the *resource index* by yourself, but notice that, if the *resource index* is higher than - * other {@link DistributedProcess} objects, then this {@link DistributedProcess process} will be ordered to - * handle less processes than other {@link DistributedProcess} objects. Otherwise, the *resource index* is - * lower than others, of course, much processes will be requested. - * - * - {@link setResource setResource()} - * - {@link enforceResource enforceResource()} - * - * Unless {@link enforceResource enforceResource()} is called, This *resource index* is **revaluated** whenever - * {@link sendData sendData()} is called. - * - * @return Resource index. - */ - getResource(): number; - /** - * Set resource index. - * - * Set *resource index* that indicates how much this {@link DistributedProcess process} is heavy. This - * *resource index* can be **revaulated**. - * - * Note that, initial and average *resource index* of {@link DistributedProcess} objects are ```1.0```. If the - * *resource index* is higher than other {@link DistributedProcess} objects, then this - * {@link DistributedProcess} will be ordered to handle more processes than other {@link DistributedProcess} - * objects. Otherwise, the *resource index* is lower than others, of course, less processes will be requested. - * - * Unlike {@link enforceResource}, configuring *resource index* by this {@link setResource} allows the - * **revaluation**. This **revaluation** prevents wrong valuation from user. For example, you *mis-valuated* the - * *resource index*. The {@link DistributedProcess process} is much heavier than any other, but you estimated it - * to the lightest one. It looks like a terrible case that causes - * {@link DistributedSystemArray entire distributed processing system} to be slower, however, don't mind. The - * {@link DistributedProcess process} will the direct to the *propriate resource index* eventually with the - * **revaluation**. - * - * - The **revaluation** is caused by the {@link sendData sendData()} method. - * - * @param val New resource index, but can be revaluated. - */ - setResource(val: number): void; - /** - * Enforce resource index. - * - * Enforce *resource index* that indicates how much heavy the {@link DistributedProcess process is}. The - * *resource index* will be fixed, never be **revaluated**. - * - * Note that, initial and average *resource index* of {@link DistributedProcess} objects are ```1.0```. If the - * *resource index* is higher than other {@link DistributedProcess} objects, then this - * {@link DistributedProcess} will be ordered to handle more processes than other {@link DistributedProcess} - * objects. Otherwise, the *resource index* is lower than others, of course, less processes will be requested. - * - * The difference between {@link setResource} and this {@link enforceResource} is allowing **revaluation** or not. - * This {@link enforceResource} does not allow the **revaluation**. The *resource index* is clearly fixed and - * never be changed by the **revaluation**. But you've to keep in mind that, you can't avoid the **mis-valuation** - * with this {@link enforceResource}. - * - * For example, there's a {@link DistributedProcess process} much heavier than any other, but you - * **mis-estimated** it to the lightest. In that case, there's no way. The - * {@link DistributedSystemArray entire distributed processing system} will be slower by the **mis-valuation**. - * By the reason, using {@link enforceResource}, it's recommended only when you can clearly certain the - * *resource index*. If you can't certain the *resource index* but want to recommend, then use {@link setResource} - * instead. - * - * @param val New resource index to be fixed. - */ - enforceResource(val: number): void; - /** - * @hidden - */ - private compute_average_elapsed_time(); - /** - * @inheritdoc - */ - abstract replyData(invoke: protocol.Invoke): void; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message requesting a **distributed process**. The {@link Invoke} message will be sent - * to the most idle {@link DistributedSystem} object, which represents a slave system, and the most idle - * {@link DistributedSystem} object will be returned. - * - * When the **distributed process** has completed, then the {@link DistributedSystemArray} object will revaluate - * {@link getResource resource index} and {@link DistributedSystem.getPerformance performance index} of this - * {@link DistributedSystem} and the most idle {@link DistributedSystem} objects basis on the execution time. - * - * @param invoke An {@link Invoke} message requesting distributed process. - * @return The most idle {@link DistributedSystem} object who may send the {@link Invoke} message. - */ - sendData(invoke: protocol.Invoke): DistributedSystem; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message requesting a **distributed process**. The {@link Invoke} message will be sent - * to the most idle {@link DistributedSystem} object, which represents a slave system, and the most idle - * {@link DistributedSystem} object will be returned. - * - * When the **distributed process** has completed, then the {@link DistributedSystemArray} object will revaluate - * {@link getResource resource index} and {@link DistributedSystem.getPerformance performance index} of this - * {@link DistributedSystem} and the most idle {@link DistributedSystem} objects basis on the execution time. - * - * @param invoke An {@link Invoke} message requesting distributed process. - * @param weight Weight of resource which indicates how heavy this {@link Invoke} message is. Default is 1. - * - * @return The most idle {@link DistributedSystem} object who may send the {@link Invoke} message. - */ - sendData(invoke: protocol.Invoke, weight: number): DistributedSystem; - /** - * @hidden - */ - private complete_history(history); - /** - * @inheritdoc - */ - TAG(): string; - } -} -declare namespace samchon.templates.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 the remote, 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*.
    • - *
    - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalSystem extends protocol.EntityDequeCollection implements protocol.IProtocol { - /** - * The name represents external system have connected. - */ - protected name: string; - /** - * @hidden - */ - private system_array_; - /** - * @hidden - */ - private communicator_; - /** - * Construct from parent {@link ExternalSystemArray}. - * - * @param systemArray The parent {@link ExternalSystemArray} object. - */ - constructor(systemArray: ExternalSystemArray); - /** - * Constrct from parent {@link ExternalSystemArray} and communicator. - * - * @param systemArray The parent {@link ExternalSystemArray} object. - * @param communicator Communicator with the remote, external system. - */ - constructor(systemArray: ExternalSystemArray, communicator: protocol.IClientDriver); - /** - * Default Destructor. - * - * This {@link destructor destructor()} method is called when the {@link ExternalSystem} object is destructed and - * the {@link ExternalSystem} object is destructed when connection with the remote system is closed or this - * {@link ExternalSystem} object is {@link ExternalSystemArray.erase erased} from its parent - * {@link ExternalSystemArray} object. - * - * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically - * by those *destruction* cases. Also, if your derived {@link ExternalSystem} class has something to do on the - * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. - * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. - * - * ```typescript - * class SomeSystem extends templates.external.ExternalSystem - * { - * protected destructor(): void - * { - * // DO SOMETHING - * this.do_something(); - * - * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS - * super.destructor(); - * } - * } - * ``` - */ - protected destructor(): void; - /** - * @hidden - */ - private handle_close(); - /** - * Get parent {@link ExternalSystemArray} object. - */ - getSystemArray(): ExternalSystemArray; - /** - * Get parent {@link ExternalSystemArray} object. - */ - getSystemArray>(): SystemArray; - /** - * Identifier of {@link ExternalSystem} is its {@link name}. - * - * @return name. - */ - key(): string; - /** - * Get {@link name}. - */ - getName(): string; - /** - * @hidden - */ - /** - * @hidden - */ - protected communicator: protocol.ICommunicator; - /** - * Close connection. - */ - close(): void; - /** - * Send {@link Invoke} message to external system. - * - * @param invoke An {@link Invoke} message to send. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle an {@Invoke} message has received. - * - * @param invoke An {@link Invoke} message have received. - */ - replyData(invoke: protocol.Invoke): void; - /** - * Tag name of the {@link ExternalSystem} in {@link XML}. - * - * @return *system*. - */ - TAG(): string; - /** - * Tag name of {@link ExternalSystemRole children elements} belonged to the {@link ExternalSystem} in {@link XML}. - * - * @return *role*. - */ - CHILD_TAG(): string; - } -} -declare namespace samchon.templates.parallel { - /** - * A driver for a parallel slave system. - * - * The {@link ParallelSystem} is an abstract class represents a **slave** system in *Parallel Processing System*, - * connected with this **master** system. This {@link ParallelSystem} takes full charge of network communication with - * the remote, parallel **slave** system has connected. - * - * When a *parallel process* is requested (by {@link ParallelSystemArray.sendSegmentData} or - * {@link ParallelSystemArray.sendPieceData}), the number of pieces to be allocated to a {@link ParallelSystem} is - * turn on its {@link getPerformance performance index}. Higher {@link getPerformance performance index}, then - * more pieces are requested. The {@link getPerformance performance index} is revaluated whenever a *parallel process* - * has completed, basic on the execution time and number of pieces. You can sugguest or enforce the - * {@link getPerformance performance index} with {@link setPerformance} or {@link enforcePerformance}. - * - * - * - * - * - * #### Bridge & Proxy Pattern - * This class {@link ParallelSystem} is derived from the {@link ExternalSystem} class. Thus, you can take advantage - * of the *Bridge & Proxy Pattern* in this {@link ParallelSystem} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelSystem extends external.ExternalSystem { - /** - * @hidden - */ - private progress_list_; - /** - * @hidden - */ - private history_list_; - /** - * @hidden - */ - private exclude_; - /** - * @hidden - */ - private performance; - /** - * @hidden - */ - private enforced_; - /** - * Construct from parent {@link ParallelSystemArray}. - * - * @param systemArray The parent {@link ParallelSystemArray} object. - */ - constructor(systemArray: ParallelSystemArray); - /** - * Construct from parent {@link ParallelSystemArray} and communicator. - * - * @param systemArray The parent {@link ParallelSystemArray} object. - * @param communicator A communicator communicates with remote, the external system. - */ - constructor(systemArray: ParallelSystemArray, communicator: protocol.IClientDriver); - /** - * Default Destructor. - * - * This {@link destructor destructor()} method is called when the {@link ParallelSystem} object is destructed and - * the {@link ParallelSystem} object is destructed when connection with the remote system is closed or this - * {@link ParallelSystem} object is {@link ParallelSystemArray.erase erased} from its parent - * {@link ParallelSystemArray} object. - * - * You may think if there're some *parallel processes* have requested but not completed yet, then it would be a - * critical problem because the *parallel processes* will not complete forever. Do not worry. The critical problem - * does not happen. After the destruction, the remained *parallel processes* will be shifted to and proceeded in - * other {@link ParallelSystem} objects. - * - * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically - * by those *destruction* cases. Also, if your derived {@link ParallelSystem} class has something to do on the - * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. - * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. - * - * ```typescript - * class SomeSystem extends protocol.external.ExternalSystem - * { - * protected destructor(): void - * { - * // DO SOMETHING - * this.do_something(); - * - * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS - * super.destructor(); - * } - * } - * ``` - */ - protected destructor(): void; - /** - * Get manager of this object. - * - * @return The parent {@link ParallelSystemArray} object. - */ - getSystemArray(): ParallelSystemArray; - /** - * Get manager of this object. - * - * @return The parent {@link ParallelSystemArray} object. - */ - getSystemArray>(): SystemArray; - /** - * Get performance index. - * - * Get *performance index* that indicates how much fast the remote system is. - * - * If this {@link ParallelSystem parallel system} does not have any {@link Invoke} message had handled, then the - * *performance index* will be ```1.0```, which means default and average value between all {@link ParallelSystem} - * instances (that are belonged to a same {@link ParallelSystemArray} object). - * - * You can specify this *performance index* by yourself but notice that, if the *performance index* is higher - * than other {@link ParallelSystem} objects, then this {@link ParallelSystem parallel system} will be ordered to - * handle more processes than other {@link ParallelSystem} objects. Otherwise, the *performance index* is lower - * than others, of course, less processes will be delivered. - * - * - {@link setPerformance setPerformance()} - * - {@link enforcePerformance enforcePerformance()} - * - * Unless {@link enforcePerformance enforcePerformance()} is called, This *performance index* is **revaluated** - * whenever user calls one of them below. - * - * - {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()} - * - {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()} - * - {@link DistributedProcess.sendData DistributedProcess.sendData()}. - * - * @return Performance index. - */ - getPerformance(): number; - /** - * Set performance index. - * - * Set *performance index* that indicates how much fast the remote system is. This *performance index* can be - * **revaulated**. - * - * Note that, initial and average *performance index* of {@link ParallelSystem} objects are ```1.0```. If the - * *performance index* is higher than other {@link ParallelSystem} objects, then this {@link ParallelSystem} will - * be ordered to handle more processes than other {@link ParallelSystem} objects. Otherwise, the - * *performance index* is lower than others, of course, less processes will be delivered. - * - * Unlike {@link enforcePerformance}, configuring *performance index* by this {@link setPerformance} allows - * **revaluation**. This **revaluation** prevents wrong valuation from user. For example, you *mis-valuated* the - * *performance index*. The remote system is much faster than any other, but you estimated it to the slowest one. - * It looks like a terrible case that causes {@link ParallelSystemArray entire parallel systems} to be slower, - * however, don't mind. The system will direct to the *propriate performance index* eventually with the - * **revaluation** by following methods. - * - * - {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()} - * - {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()} - * - {@link DistributedProcess.sendData DistributedProcess.sendData()}. - * - * @param val New performance index, but can be revaluated. - */ - setPerformance(val: number): void; - /** - * Enforce performance index. - * - * Enforce *performance index* that indicates how much fast the remote system is. The *performance index* will be - * fixed, never be **revaluated**. - * - * Note that, initial and average *performance index* of {@link ParallelSystem} objects are ```1.0```. If the - * *performance index* is higher than other {@link ParallelSystem} objects, then this {@link ParallelSystem} will - * be ordered to handle more processes than other {@link ParallelSystem} objects. Otherwise, the - * *performance index* is lower than others, of course, less processes will be delivered. - * - * The difference between {@link setPerformance} and this {@link enforcePerformance} is allowing **revaluation** - * or not. This {@link enforcePerformance} does not allow the **revaluation**. The *performance index* is clearly - * fixed and never be changed by the **revaluation**. But you've to keep in mind that, you can't avoid the - * **mis-valuation** with this {@link enforcePerformance}. - * - * For example, there's a remote system much faster than any other, but you **mis-estimated** it to the slowest. - * In that case, there's no way. The {@link ParallelSystemArray entire parallel systems} will be slower by the - * **mis-valuation**. By the reason, using {@link enforcePerformance}, it's recommended only when you can clearly - * certain the *performance index*. If you can't certain the *performance index* but want to recommend, then use - * {@link setPerformance} instead. - * - * @param val New performance index to be fixed. - */ - enforcePerformance(val: number): void; - /** - * @hidden - */ - private send_piece_data(invoke, first, last); - /** - * @hidden - */ - private _replyData(invoke); - /** - * @hidden - */ - protected _Report_history(xml: library.XML): void; - /** - * @hidden - */ - protected _Send_back_history(invoke: protocol.Invoke, history: protocol.InvokeHistory): void; - } -} -declare namespace samchon.templates.distributed { - /** - * A driver for a distributed slave system. - * - * The {@link DistributedSystem} is an abstract class represents a **slave** system in *Distributed Processing System*, - * connected with this **master** system. This {@link DistributedSystem} takes full charge of network communication - * with the remote, distributed **slave** system has connected. - * - * This {@link DistributedSystem} has a {@link getPerformance performance index} that indicates how much the **slave** - * system is fast. The {@link getPerformance performance index} is referenced and revaluated whenever those methods - * are called: - * - * - Requesting a *parallel process* - * - {@link DistributedSystemArray.sendSegmentData} - * - {@link DistributedSystemArray.sendPieceData} - * - Requesting a *distributed process*: {@link DistributedProcess.sendData} - * - * Note that, this {@link DistributedSystem} class derived from the {@link ExternalSystem} class. Thus, this - * {@link DistributedSystem} can also have children {@link ExternalSystemRole} objects exclusively. However, the - * children {@link ExternalSystemRole roles} objects are different with the {@link DistributedProcess}. The - * domestic {@link ExternalSystemRole roles} are belonged to only a specific {@link DistributedSystem} object. - * Otherwise, the {@link DistributedProcess} objects are belonged to a {@link DistributedSystemArray} object. - * Furthermore, the relationship between this {@link DistributedSystem} and {@link DistributedProcess} classes are - * **M: N Associative**. - * - * Articles | {@link DistributedProcess} | {@link ExternalSystemRole} - * -------------|--------------------------------|---------------------------- - * Belonged to | {@link DistributedSystemArray} | {@link DistributedSystem} - * Relationship | M: N Associative | 1: N Composite - * Ownership | References | Exclusive possession - * - * - * - * - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedSystem extends parallel.ParallelSystem { - /** - * Construct from parent {@link DistributedSystemArray}. - * - * @param systemArray The parent {@link DistributedSystemArray} object. - */ - constructor(systemArray: DistributedSystemArray); - /** - * Constrct from parent {@link DistributedSystemArray} and communicator. - * - * @param systemArray The parent {@link DistributedSystemArray} object. - * @param communicator A communicator communicates with remote, the external system. - */ - constructor(systemArray: DistributedSystemArray, communicator: protocol.IClientDriver); - /** - * Factory method creating a {@link ExternalSystemRole child} object. - * - * In {@link distributed} module, the process class {@link DistributedProcess} is not belonged to a specific - * {@link DistributedSystem} object. It only belongs to a {@link DistributedSystemArray} object and has a - * **M: N Associative Relationship** between this {@link DistributedSystem} class. - * - * By that reason, it's the normal case that the {@link DistributedSystem} object does not have any children - * {@link ExternalSystemRole} object. Thus, default {@link createChild} returns ```null```. - * - * However, if you want a {@link DistributedSystem} to have its own domestic {@link ExternalSystemRole} objects - * without reference to the {@link DistributedProcess} objects, it is possible. Creates and returns the - * domestic {@link ExternalSystemRole} object. - * - * @param xml {@link XML} represents the {@link ExternalSystemRole child} object. - * @return A newly created {@link ExternalSystemRole} object or ```null```. - */ - createChild(xml: library.XML): external.ExternalSystemRole; - /** - * Get manager of this object. - * - * @return The parent {@link DistributedSystemArray} object. - */ - getSystemArray(): DistributedSystemArray; - /** - * Get manager of this object. - * - * @return The parent {@link DistributedSystemArray} object. - */ - getSystemArray>(): SystemArray; - /** - * @hidden - */ - private compute_average_elapsed_time(); - /** - * @inheritdoc - */ - replyData(invoke: protocol.Invoke): void; - /** - * @hidden - */ - protected _Report_history(xml: library.XML): void; - /** - * @hidden - */ - protected _Send_back_history(invoke: protocol.Invoke, history: protocol.InvokeHistory): void; - } -} -declare namespace samchon.templates.distributed { - /** - * An interface for a distributed slave server driver. - * - * The easiest way to defining a driver for distributed **slave** server is extending {@link DistributedServer} class. - * However, if you've to interact with a prallel **slave** system who can be both server and client, them make a class - * (let's name it **BaseSystem**) extending the {@link DistributedServer} class. At next, make a new class (now, I name - * it **BaseServer**) extending the **BaseSystem** and implements this interface {@link IParallelServer}. Define the - * **BaseServer** following those codes on below: - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - interface IDistributedServer extends DistributedSystem { - /** - * Connect to external server. - */ - connect(): void; - } - /** - * A driver for distributed slave server. - * - * The {@link DistributedServer} is an abstract class, derived from the {@link DistributedSystem} class, connecting to - * remote, distributed **slave** server. Extends this {@link DistributedServer} class and overrides the - * {@link createServerConnector createServerConnector()} method following which protocol the **slave** server uses. - * - * #### [Inheritdoc] {@link DistributedSystem} - * The {@link DistributedSystem} is an abstract class represents a **slave** system in *Distributed Processing System*, - * connected with this **master** system. This {@link DistributedSystem} takes full charge of network communication - * with the remote, distributed **slave** system has connected. - * - * This {@link DistributedSystem} has a {@link getPerformance performance index} that indicates how much the **slave** - * system is fast. The {@link getPerformance performance index} is referenced and revaluated whenever those methods - * are called: - * - * - Requesting a *parallel process* - * - {@link DistributedSystemArray.sendSegmentData} - * - {@link DistributedSystemArray.sendPieceData} - * - Requesting a *distributed process*: {@link DistributedProcess.sendData} - * - * Note that, this {@link DistributedSystem} class derived from the {@link ExternalSystem} class. Thus, this - * {@link DistributedSystem} can also have children {@link ExternalSystemRole} objects exclusively. However, the - * children {@link ExternalSystemRole roles} objects are different with the {@link DistributedProcess}. The - * domestic {@link ExternalSystemRole roles} are belonged to only a specific {@link DistributedSystem} object. - * Otherwise, the {@link DistributedProcess} objects are belonged to a {@link DistributedSystemArray} object. - * Furthermore, the relationship between this {@link DistributedSystem} and {@link DistributedProcess} classes are - * **M: N Associative**. - * - * Articles | {@link DistributedProcess} | {@link ExternalSystemRole} - * -------------|--------------------------------|---------------------------- - * Belonged to | {@link DistributedSystemArray} | {@link DistributedSystem} - * Relationship | M: N Associative | 1: N Composite - * Ownership | References | Exclusive possession - * - * - * - * - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedServer extends DistributedSystem implements external.IExternalServer { - /** - * IP address of target external system to connect. - */ - protected ip: string; - /** - * Port number of target external system to connect. - */ - protected port: number; - /** - * Construct from parent {@link DistributedSystemArray}. - * - * @param systemArray The parent {@link DistributedSystemArray} object. - */ - constructor(systemArray: DistributedSystemArray); - /** - * Factory method creating {@link IServerConnector} object. - * - * The {@link createServerConnector createServerConnector()} is an abstract method creating - * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the slave server - * follows: - * - * - {@link ServerConnector} - * - {@link WebServerConnector} - * - {@link DedicatedWorkerServerConnector} - * - {@link SharedWorkerServerConnector} - * - * @return A newly created {@link IServerConnector} object. - */ - protected abstract createServerConnector(): protocol.IServerConnector; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * Master of Distributed Processing System, a client connecting to slave servers. - * - * The {@link DistributedServerArray} is an abstract class, derived from the {@link DistributedSystemArray} class, - * connecting to {@link IDistributedServer distributed servers}. - * - * Extends this {@link DistributedServerArray} and overrides {@link createChild createChild()} method creating child - * {@link IDistributedServer} object. After the extending and overriding, construct children {@link IDistributedServer} - * objects and call the {@link connect connect()} method. - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedServerArray extends DistributedSystemArray implements external.IExternalServerArray { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * Mediator of Distributed Processing System, a client connecting to slave servers. - * - * The {@link DistributedServerArrayMediator} is an abstract class, derived from {@link DistributedSystemArrayMediator} - * class, connecting to {@link IDistributedServer distributed servers}. - * - * Extends this {@link DistributedServerArrayMediator} and overrides {@link createChild createChild()} method creating - * child {@link IDistributedServer} object. After the extending and overriding, construct children - * {@link IDistributedServer} objects and call the {@link connect connect()} method. - * - * #### [Inherited] {@link DistributedSystemArrayMediator} - * The {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a slave to its master - * system at the same time. This {@link DistributedSystemArrayMediator} be a master system, containing and managing - * {@link DistributedSystem} objects, which represent distributed slave systems, by extending - * {@link DistributedSystemArray} class. Also, be a slave system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a slave, you can specify this {@link DistributedSystemArrayMediator} to be a client slave connecting to master - * server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedServerArrayMediator extends DistributedSystemArrayMediator implements external.IExternalServerArray { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * Master of Distributed Processing System, be a server and client at the same time. - * - * The {@link DistributedServerClientArray} is an abstract class, derived from the {@link DistributedSystemArray} - * class, opening a server accepting {@link Distributed distributed clients} and being a client connecting to - * {@link IDistributedServer distributed servers} at the same time. - * - * Extends this {@link DistributedServerClientArray} and overrides below methods. After the overridings, open server - * with {@link open open()} method and connect to {@link IDistributedServer distributed servers} through the - * {@link connect connect()} method. - * - * - {@link createServerBase createServerBase()} - * - {@link createExternalClient createExternalClient()} - * - {@link createExternalServer createExternalServer()} - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedServerClientArray extends DistributedClientArray implements external.IExternalServerClientArray { - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method of a child Entity. - * - * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. - * - * @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()}. - */ - createChild(xml: library.XML): System; - /** - * Factory method creating an {@link IDistributedServer} 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 IDistributedServer} object. - */ - protected abstract createExternalServer(xml: library.XML): System; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * Mediator of Distributed Processing System, be a server and client at the same time as a **master**. - * - * The {@link DistributedServerClientArrayMediator} is an abstract class, derived from the - * {@link DistributedSystemArrayMediator} class, opening a server accepting {@link DistributedSystem distributed - * clients} and being a client connecting to {@link IDistributedServer distributed servers} at the same time. - * - * Extends this {@link DistributedServerClientArrayMediator} and overrides below methods. After the overridings, open - * server with {@link open open()} method and connect to {@link IDistributedServer distributed servers} through the - * {@link connect connect()} method. - * - * - {@link createServerBase createServerBase()} - * - {@link createExternalClient createExternalClient()} - * - {@link createExternalServer createExternalServer()} - * - * #### [Inherited] {@link DistributedSystemArrayMediator} - * The {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a slave to its master - * system at the same time. This {@link DistributedSystemArrayMediator} be a master system, containing and managing - * {@link DistributedSystem} objects, which represent distributed slave systems, by extending - * {@link DistributedSystemArray} class. Also, be a slave system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a slave, you can specify this {@link DistributedSystemArrayMediator} to be a client slave connecting to master - * server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedServerClientArrayMediator extends DistributedClientArrayMediator implements external.IExternalServerClientArray { - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method of a child Entity. - * - * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. - * - * @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()}. - */ - createChild(xml: library.XML): System; - /** - * Factory method creating an {@link IDistributedServer} 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 IDistributedServer} object. - */ - protected abstract createExternalServer(xml: library.XML): System; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * History of an {@link Invoke} message. - * - * The {@link PRInvokeHistory} is a class archiving history log of an {@link Invoke} message which requests the - * *distributed process*, created whenever {@link DistributedProcess.sendData} is called. - * - * When the *distributed process* has completed, then {@link complete complete()} is called and the *elapsed time* is - * determined. The elapsed time is utilized for computation of {@link DistributedSystem.getPerformance performance index} - * and {@link DistributedProcess.getResource resource index} of related objects. - * - * - * - * - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class DSInvokeHistory extends protocol.InvokeHistory { - /** - * @hidden - */ - private system_; - /** - * @hidden - */ - private process_; - /** - * @hidden - */ - private weight_; - /** - * Construct from a DistributedSystem. - * - * @param system The {@link DistributedSystem} object who sent the {@link Invoke} message. - */ - constructor(system: DistributedSystem); - /** - * Initilizer Constructor. - * - * @param system The {@link DistributedSystem} object who sent the {@link Invoke} message. - * @param process The {@link DistributedProcess} object who sent the {@link Invoke} message. - * @param invoke An {@link Invoke} message requesting the *distributed process*. - * @param weight Weight of resource which indicates how heavy this {@link Invoke} message is. - */ - constructor(system: DistributedSystem, process: DistributedProcess, invoke: protocol.Invoke, weight: number); - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * Get the related {@link DistributedSystem} object. - */ - getSystem(): DistributedSystem; - /** - * Get the related {@link DistributedProcess} object. - */ - getProcess(): DistributedProcess; - /** - * Get weight. - * - * Gets weight of resource which indicates how heavy this {@link Invoke} message is. Default is 1. - */ - getWeight(): number; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.templates.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: - * - * - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - interface IExternalClientArray extends ExternalSystemArray, protocol.IServer { - } - /** - * An array and manager of {@link ExternalSystem external clients} as a server. - * - * The {@link ExternalClientArray} is an abstract class, derived from the {@link ExternalSystemArray} class, opening - * a server accepting {@link ExternalSystem external clients}. - * - * Extends this {@link ExternalClientArray}, overrides {@link createServerBase createServerBase()} to determine which - * protocol to follow and {@link createExternalClient createExternalClient()} creating child {@link ExternalSystem} - * object. After the extending and overridings, open this server using the {@link open open()} method. - * - * #### [Inherited] {@link ExternalSystemArray} - * The {@link ExternalSystemArray} is an abstract class containing and managing external system drivers, - * {@link ExternalSystem} objects. Within framewokr of network, {@link ExternalSystemArray} represents your system - * and children {@link ExternalSystem} objects represent remote, external systems connected with your system. - * With this {@link ExternalSystemArray}, you can manage multiple external systems as a group. - * - * - * - * - * - * #### 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*.
    • - *
    - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalClientArray extends ExternalSystemArray implements IExternalClientArray { - /** - * @hidden - */ - private server_base_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating {@link IServerBase} object. - * - * This method {@link createServerBase createServerBase()} determines which templates is used in this server, - * {@link ExternalClientArray}. If the templates is determined, then {@link ExternalSystem external clients} who - * may connect to {@link ExternalClientArray this server} must follow the specified templates. - * - * Creates and returns one of them: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - * - * @return A new {@link IServerBase} object. - */ - protected abstract createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * When a {@link IClientDriver remote client} connects to this *server* {@link ExternalClientArray} object, - * then this {@link ExternalClientArray} creates a child {@link ExternalSystem external client} object through - * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. - * - * @param driver A communicator for external client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * (Deprecated) Factory method creating child object. - * - * The method {@link createChild createChild()} is deprecated. Don't use and override this. - * - * Note that, the {@link ExternalClientArray} is a server accepting {@link ExternalSystem external clients}. - * There's no way to creating the {@link ExternalSystem external clients} in advance before opening the server. - * - * @param xml An {@link XML} object represents the child {@link ExternalSystem} object. - * @return null - */ - createChild(xml: library.XML): T; - /** - * Factory method creating a child {@link ExternalSystem} object. - * - * @param driver A communicator with connected client. - * @return A newly created {@link ExternalSystem} object. - */ - protected abstract createExternalClient(driver: protocol.IClientDriver): T; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } -} -declare namespace samchon.templates.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: - * - * - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - interface IExternalServer extends ExternalSystem { - /** - * Connect to external server. - */ - connect(): void; - } - /** - * An external server driver. - * - * The {@link ExternalServer} is an abstract class, derived from the {@link ExternalSystem} class, connecting to - * remote, external server. Extends this {@link ExternalServer} class and overrides the - * {@link createServerConnector createServerConnector()} method following which protocol the external server uses. - * - * #### [Inherited] {@link ExternalSystem} - * The {@link ExternalSystem} class represents an external system, connected and interact with this system. - * {@link ExternalSystem} takes full charge of network communication with the remote, 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*.
    • - *
    - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @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; - /** - * Construct from parent {@link ExternalSystemArray}. - * - * @param systemArray The parent {@link ExternalSystemArray} object. - */ - constructor(systemArray: ExternalSystemArray); - /** - * Factory method creating {@link IServerConnector} object. - * - * The {@link createServerConnector createServerConnector()} is an abstract method creating - * {@link IServerConnector} object. Overrides and returns one of them, considering which templates the external - * system follows: - * - * - {@link ServerConnector} - * - {@link WebServerConnector} - * - {@link DedicatedWorkerServerConnector} - * - {@link SharedWorkerServerConnector} - * - * @return A newly created {@link IServerConnector} object. - */ - protected abstract createServerConnector(): protocol.IServerConnector; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.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: - * - * - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @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 array and manager of {@link IExternalServer external servers}. - * - * The {@link ExternalServerArray} is an abstract class, derived from the {@link ExternalSystemArray} class, - * connecting to {@link IExternalServer external servers}. - * - * Extends this {@link ExternalServerArray} and overrides {@link createChild createChild()} method creating child - * {@link IExternalServer} object. After the extending and overriding, construct children {@link IExternalServer} - * objects and call the {@link connect connect()} method. - * - * #### [Inherited] {@link ExternalSystemArray} - * The {@link ExternalSystemArray} is an abstract class containing and managing external system drivers, - * {@link ExternalSystem} objects. Within framewokr of network, {@link ExternalSystemArray} represents your system - * and children {@link ExternalSystem} objects represent remote, external systems connected with your system. - * With this {@link ExternalSystemArray}, you can manage multiple external systems as a group. - * - * - * - * - * - * #### 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*.
    • - *
    - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalServerArray extends ExternalSystemArray implements IExternalServerArray { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.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: - * - * - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - interface IExternalServerClientArray extends IExternalClientArray { - /** - * Connect to {@link IExternalServer external servers}. - * - * This method calls children elements' method {@link IExternalServer.connect} gradually. - */ - connect(): void; - } - /** - * An array and manager of {@link IExternalServer external servers} and {@link ExternalSystem external clients}. - * - * The {@link ExternalServerClientArray} is an abstract class, derived from the {@link ExternalSystemArray} class, - * opening a server accepting {@link ExternalSystem external clients} and being a client connecting to - * {@link IExternalServer external servers} at the same time. - * - * Extends this {@link ExternalServerClientArray} and overrides below methods. After the overridings, open server - * with {@link open open()} method and connect to {@link IExternalServer external servers} through the - * {@link connect connect()} method. - * - * - {@link createServerBase createServerBase()} - * - {@link createExternalClient createExternalClient()} - * - {@link createExternalServer createExternalServer()} - * - * #### [Inherited] {@link ExternalSystemArray} - * The {@link ExternalSystemArray} is an abstract class containing and managing external system drivers, - * {@link ExternalSystem} objects. Within framewokr of network, {@link ExternalSystemArray} represents your system - * and children {@link ExternalSystem} objects represent remote, external systems connected with your system. - * With this {@link ExternalSystemArray}, you can manage multiple external systems as a group. - * - * - * - * - * - * #### 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*.
    • - *
    - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @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}. Override the {@link createExternalServer} method. - * - * @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()}. - */ - createChild(xml: library.XML): T; - /** - * 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): T; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.external { - /** - * A role of an external system. - * - * The {@link ExternalSystemRole} class represents a role, *WHAT TO DO*. Extends the {@link ExternalSystemRole} class - * and overrides {@link replyData replyData()} to define the *WHAT TO DO*. And assign this {@link ExternalSystemRole} - * object to related {@link ExternalSystem} object. - * - * - * - * - * - * #### 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} object, via {@link ExternalSystemArray.getRole 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*.
    • - *
    - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalSystemRole extends protocol.Entity implements protocol.IProtocol { - /** - * @hidden - */ - 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}. - */ - protected name: string; - /** - * 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 grandparent {@link ExternalSystemArray}. - * - * Get the grandparent {@link ExternalSystemArray} object through this parent {@link ExternalSystem}, - * {@link ExternalSystem.getSystemArray ExternalSystem.getSystemArray()}. - * - * @return The grandparent {@link ExternalSystemArray} object. - */ - getSystemArray(): ExternalSystemArray; - /** - * Get parent {@link ExternalSystemRole} object. - */ - getSystem(): ExternalSystem; - /** - * Get name, who represents and identifies this role. - */ - getName(): string; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message to remote system through the parent {@link ExternalSystem} object. - * - * @param invoke An {@link Invoke} message to send to the external system. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle replied {@link Invoke} message. - * - * {@link ExternalSystemRole.replyData ExternalSystemRole.replyData()} is an abstract method handling a replied - * {@link Invoke message} gotten from remote system via parent {@link ExternalSystem} object. Overrides this - * method and defines the *WHAT TO DO* with the {@link Invoke message}. - * - * @param invoke An {@link Invoke} message received from the {@link ExternalSystem external system}. - */ - abstract replyData(invoke: protocol.Invoke): void; - /** - * Tag name of the {@link ExternalSytemRole} in {@link XML}. - * - * @return *role*. - */ - TAG(): string; - } -} -declare namespace samchon.templates.slave { - abstract class SlaveSystem implements protocol.IProtocol { - /** - * @hidden - */ - protected communicator_: protocol.ICommunicator; - /** - * Default Constructor. - */ - constructor(); - sendData(invoke: protocol.Invoke): void; - /** - * @hidden - */ - protected _replyData(invoke: protocol.Invoke): void; - replyData(invoke: protocol.Invoke): void; - } -} -declare namespace samchon.templates.parallel { - /** - * A mediator, the master driver. - * - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class MediatorSystem extends slave.SlaveSystem { - /** - * @hidden - */ - private system_array_; - /** - * @hidden - */ - private progress_list_; - /** - * Construct from parent {@link ParallelSystemArrayMediator} object. - * - * @param systemArray The parent {@link ParallelSystemArrayMediator} object. - */ - constructor(systemArray: ParallelSystemArrayMediator); - /** - * Construct from parent {@link DistributedSystemArrayMediator} object. - * - * @param systemArray The parent {@link DistributedSystemArrayMediator} object. - */ - constructor(systemArray: distributed.DistributedSystemArrayMediator); - /** - * Start interaction. - * - * The {@link start start()} is an abstract method starting interaction with the **master** system. If the - * **master** is a server, then connects to the **master**. Otherwise, the **master** is client, then this - * {@link MediatorSystem} object wil open a server accepting the **master**. - */ - abstract start(): void; - /** - * Get parent {@link ParallelSystemArrayMediator} or {@link DistributedSystemArrayMediator} object. - */ - getSystemArray(): ParallelSystemArrayMediator | distributed.DistributedSystemArrayMediator; - /** - * Get parent {@link ParallelSystemArrayMediator} object. - */ - getSystemArray>(): SystemArray; - /** - * Get parent {@link DistributedSystemArrayMediator} object. - */ - getSystemArray>(): SystemArray; - /** - * @hidden - */ - private complete_history(uid); - /** - * @hidden - */ - protected _replyData(invoke: protocol.Invoke): void; - /** - * @inheritdoc - */ - replyData(invoke: protocol.Invoke): void; - } -} -declare namespace samchon.templates.parallel { - /** - * A mediator server, driver for the master client. - * - * The {@link MediatorServer} is a class opening a server accepting the **master** client, following the protocol of - * Samchon Framework's own. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorServer extends MediatorSystem implements slave.ISlaveServer { - /** - * @hidden - */ - private server_base_; - /** - * @hidden - */ - private port; - /** - * Initializer Constructor. - * - * @param systemArray The parent {@link ParallelSystemArrayMediator} object. - * @param port Port number of server to open. - */ - constructor(systemArray: ParallelSystemArrayMediator, port: number); - /** - * Initializer Constructor. - * - * @param systemArray The parent {@link DistributedSystemArrayMediator} object. - * @param port Port number of server to open. - */ - constructor(systemArray: distributed.DistributedSystemArrayMediator, port: number); - /** - * Factory method creating {@link IServerBase} object. - * - * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, - * {@link MediatorServer}. Note that, **slave** (this {@link MediatorServer} object) must follow the **master**'s - * protocol. - * - * Overrides and return one of them considering the which protocol to follow: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - */ - protected createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * {@link MediatorServer} represents a **slave** dedicating to its **master**. In that reason, the - * {@link MediatorServer} does not accept multiple **master** clients. It accepts only one. Thus, *listener* of - * the *communicator* is {@link MediatorSystem} object, itself. - * - * @param driver A communicator with remote client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * @inheritdoc - */ - start(): void; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } - /** - * A mediator server, driver for the master client. - * - * The {@link MediatorWebServer} is a class opening a server accepting the **master** client, following the - * web-socket protocol. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorWebServer extends MediatorServer { - /** - * @inheritdoc - */ - protected createServerBase(): protocol.IServerBase; - } - /** - * A mediator server, driver for the master client. - * - * The {@link MediatorDedicatedWorkerServer} is a class opening a server accepting the **master** client, following - * the DedicatedWorker's protocol. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorDedicatedWorkerServer extends MediatorServer { - /** - * @inheritdoc - */ - protected createServerBase(): protocol.IServerBase; - } - /** - * A mediator server, driver for the master client. - * - * The {@link MediatorSharedWorkerServer} is a class opening a server accepting the **master** client, following the - * SharedWorker's protocol. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorSharedWorkerServer extends MediatorServer { - /** - * @inheritdoc - */ - protected createServerBase(): protocol.IServerBase; - } -} -declare namespace samchon.templates.parallel { - /** - * A mediator client, driver for the master server. - * - * The {@link MediatorServer} is a class being a client connecting to the **master** server, following the protocol - * of Samchon Framework's own. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorClient extends MediatorSystem implements slave.ISlaveClient { - /** - * @hidden - */ - private ip; - /** - * @hidden - */ - private port; - /** - * Initializer Constructor. - * - * @param systemArray The parent {@link ParallelSystemArrayMediator} object. - * @param ip IP address to connect. - * @param port Port number to connect. - */ - constructor(systemArray: ParallelSystemArrayMediator, ip: string, port: number); - /** - * Initializer Constructor. - * - * @param systemArray The parent {@link DistributedSystemArrayMediator} object. - * @param ip IP address to connect. - * @param port Port number to connect. - */ - constructor(systemArray: distributed.DistributedSystemArrayMediator, ip: string, port: number); - /** - * Factory method creating {@link IServerConnector} object. - * - * The {@link createServerConnector createServerConnector()} is an abstract method creating - * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the **master** - * server follows: - * - * - {@link ServerConnector} - * - {@link WebServerConnector} - * - {@link SharedWorkerServerConnector} - * - * @return A newly created {@link IServerConnector} object. - */ - protected createServerConnector(): protocol.IServerConnector; - /** - * @inheritdoc - */ - start(): void; - /** - * @inheritdoc - */ - connect(): void; - } - /** - * A mediator client, driver for the master server. - * - * The {@link MediatorWebClient} is a class being a client connecting to the **master** server, following the - * web-socket protocol. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorWebClient extends MediatorClient { - /** - * @inheritdoc - */ - protected createServerConnector(): protocol.IServerConnector; - } - /** - * A mediator client, driver for the master server. - * - * The {@link MediatorSharedWorkerClient} is a class being a client connecting to the **master** server, following - * the SharedWorker's protocol. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorSharedWorkerClient extends MediatorClient { - /** - * @inheritdoc - */ - protected createServerConnector(): protocol.IServerConnector; - } -} -declare namespace samchon.templates.parallel { - /** - * Master of Parallel Processing System, a server accepting slave clients. - * - * The {@link ParallelClientArray} is an abstract class, derived from the {@link ParallelSystemArray} class, opening - * a server accepting {@link ParallelSystem parallel clients}. - * - * Extends this {@link ParallelClientArray}, overrides {@link createServerBase createServerBase()} to determine which - * protocol to follow and {@link createExternalClient createExternalClient()} creating child {@link ParallelSystem} - * object. After the extending and overridings, open this server using the {@link open open()} method. - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelClientArray extends ParallelSystemArray implements external.IExternalClientArray { - /** - * @hidden - */ - 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. - * - * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - * - * @return A new {@link IServerBase} object. - */ - protected abstract createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, - * then this {@link ParallelClientArray} creates a child {@link ParallelSystem parallel client} object through - * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. - * - * @param driver A communicator for external client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * (Deprecated) Factory method creating child object. - * - * The method {@link createChild createChild()} is deprecated. Don't use and override this. - * - * Note that, the {@link ParallelClientArray} is a server accepting {@link ParallelSystem parallel clients}. - * There's no way to creating the {@link ParallelSystem parallel clients} in advance before opening the server. - * - * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. - * @return ```null``` - */ - createChild(xml: library.XML): System; - /** - * Factory method creating {@link ParallelSystem} object. - * - * The method {@link createExternalClient createExternalClient()} is a factory method creating a child - * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by - * {@link addClient addClient()}. - * - * Overrides this {@link createExternalClient} method and creates a type of {@link ParallelSystem} object with - * the *driver* that communicates with the parallel client. After the creation, returns the {@link ParallelSystem} - * object. Then whenever a parallel client has connected, matched {@link ParallelSystem} object will be - * constructed and {@link insert inserted} into this {@link ParallelClientArray} object. - * - * @param driver A communicator with the parallel client. - * @return A newly created {@link ParallelSystem} object. - */ - protected abstract createExternalClient(driver: protocol.IClientDriver): System; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * Mediator of Parallel Processing System. - * - * The {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a **slave** to its - * master system at the same time. This {@link ParallelSystemArrayMediator} be a **master **system, containing and - * managing {@link ParallelSystem} objects, which represent parallel slave systems, by extending - * {@link ParallelSystemArray} class. Also, be a **slave** system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a **master**, you can specify this {@link ParallelSystemArrayMediator} class to be a master server accepting - * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one - * of them below and overrides abstract factory method(s) creating the child {@link ParallelSystem} object. - * - * - {@link ParallelClientArrayMediator}: A server accepting {@link ParallelSystem parallel clients}. - * - {@link ParallelServerArrayMediator}: A client connecting to {@link ParallelServer parallel servers}. - * - {@link ParallelServerClientArrayMediator}: Both of them. Accepts {@link ParallelSystem parallel clients} and - * connects to {@link ParallelServer parallel servers} at the same time. - * - * As a **slave**, you can specify this {@link ParallelSystemArrayMediator} to be a client slave connecting to - * master server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelSystemArrayMediator extends ParallelSystemArray { - /** - * @hidden - */ - private mediator_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating a {@link MediatorSystem} object. - * - * The {@link createMediator createMediator()} is an abstract method creating the {@link MediatorSystem} object. - * - * You know what? this {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a - * **slave** to its master system at the same time. The {@link MediatorSystem} object makes it possible; be a - * **slave** system. This {@link createMediator} determines specific type of the {@link MediatorSystem}. - * - * Overrides the {@link createMediator createMediator()} method to create and return one of them following which - * protocol and which type of remote connection (server or client) will be used: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * @return A newly created {@link MediatorSystem} object. - */ - protected abstract createMediator(): MediatorSystem; - /** - * Start mediator. - * - * If the {@link getMediator mediator} is a type of server, then opens the server accepting master client. - * Otherwise, the {@link getMediator mediator} is a type of client, then connects the master server. - */ - protected startMediator(): void; - /** - * Get {@link MediatorSystem} object. - * - * When you need to send an {@link Invoke} message to the master system of this - * {@link ParallelSystemArrayMediator}, then send to the {@link MediatorSystem} through this {@link getMediator}. - * - * ```typescript - * this.getMediator().sendData(...); - * ``` - * - * @return The {@link MediatorSystem} object. - */ - getMediator(): MediatorSystem; - /** - * @hidden - */ - protected _Complete_history(history: PRInvokeHistory): boolean; - } -} -declare namespace samchon.templates.parallel { - /** - * Mediator of Parallel Processing System, a server accepting slave clients. - * - * The {@link ParallelClientArrayMediator} is an abstract class, derived from the {@link ParallelSystemArrayMediator} - * class, opening a server accepting {@link ParallelSystem parallel clients} as a **master**. - * - * Extends this {@link ParallelClientArrayMediator}, overrides {@link createServerBase createServerBase()} to - * determine which protocol to follow and {@link createExternalClient createExternalClient()} creating child - * {@link ParallelSystem} object. After the extending and overridings, open this server using the - * {@link open open()} method. - * - * #### [Inherited] {@link ParallelSystemArrayMediator} - * The {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a **slave** to its - * master system at the same time. This {@link ParallelSystemArrayMediator} be a **master **system, containing and - * managing {@link ParallelSystem} objects, which represent parallel slave systems, by extending - * {@link ParallelSystemArray} class. Also, be a **slave** system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a **slave**, you can specify this {@link ParallelSystemArrayMediator} to be a client slave connecting to - * master server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelClientArrayMediator extends ParallelSystemArrayMediator implements external.IExternalClientArray { - /** - * @hidden - */ - 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 ParallelClientArrayMediator}. If the protocol is determined, then - * {@link ParallelSystem parallel clients} who may connect to {@link ParallelClientArrayMediator this server} - * must follow the specified protocol. - * - * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - * - * @return A new {@link IServerBase} object. - */ - protected abstract createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, - * then this {@link ParallelClientArrayMediator} creates a child {@link ParallelSystem parallel client} object - * through the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. - * - * @param driver A communicator for parallel client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * (Deprecated) Factory method creating child object. - * - * The method {@link createChild createChild()} is deprecated. Don't use and override this. - * - * Note that, the {@link ParallelClientArrayMediator} is a server accepting {@link ParallelSystem parallel - * clients} as a master. There's no way to creating the {@link ParallelSystem parallel clients} in advance before - * opening the server. - * - * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. - * @return null - */ - createChild(xml: library.XML): System; - /** - * Factory method creating {@link ParallelSystem} object. - * - * The method {@link createExternalClient createExternalClient()} is a factory method creating a child - * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by - * {@link addClient addClient()}. - * - * Overrides this {@link createExternalClient} method and creates a type of {@link ParallelSystem} object with - * the *driver* that communicates with the parallel client. After the creation, returns the {@link ParallelSystem} - * object. Then whenever a parallel client has connected, matched {@link ParallelSystem} object will be - * constructed and {@link insert inserted} into this {@link ParallelClientArrayMediator} object. - * - * @param driver A communicator with the parallel client. - * @return A newly created {@link ParallelSystem} object. - */ - protected abstract createExternalClient(driver: protocol.IClientDriver): System; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * An interface for a parallel slave server driver. - * - * The easiest way to defining a driver for parallel **slave** server is extending {@link ParallelServer} class. - * However, if you've to interact with a prallel **slave** system who can be both server and client, them make a class - * (let's name it **BaseSystem**) extending the {@link ParallelSystem} class. At next, make a new class (now, I name it - * **BaseServer**) extending the **BaseSystem** and implements this interface {@link IParallelServer}. Define the - * **BaseServer** following those codes on below: - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - interface IParallelServer extends ParallelSystem { - /** - * Connect to slave server. - */ - connect(): void; - } - /** - * A driver for parallel slave server. - * - * The {@link ParallelServer} is an abstract class, derived from the {@link ParallelSystem} class, connecting to - * remote, parallel **slave** server. Extends this {@link ParallelServer} class and overrides the - * {@link createServerConnector createServerConnector()} method following which protocol the **slave** server uses. - * - * #### [Inherited] {@link ParallelSystem} - * The {@link ParallelSystem} is an abstract class represents a **slave** system in *Parallel Processing System*, - * connected with this **master** system. This {@link ParallelSystem} takes full charge of network communication with - * the remote, parallel **slave** system has connected. - * - * When a *parallel process* is requested (by {@link ParallelSystemArray.sendSegmentData} or - * {@link ParallelSystemArray.sendPieceData}), the number of pieces to be allocated to a {@link ParallelSystem} is - * turn on its {@link getPerformance performance index}. Higher {@link getPerformance performance index}, then - * more pieces are requested. The {@link getPerformance performance index} is revaluated whenever a *parallel process* - * has completed, basic on the execution time and number of pieces. You can sugguest or enforce the - * {@link getPerformance performance index} with {@link setPerformance} or {@link enforcePerformance}. - * - * - * - * - * - * #### Bridge & Proxy Pattern - * This class {@link ParallelSystem} is derived from the {@link ExternalSystem} class. Thus, you can take advantage - * of the *Bridge & Proxy Pattern* in this {@link ParallelSystem} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelServer extends ParallelSystem implements IParallelServer { - /** - * IP address of target external system to connect. - */ - protected ip: string; - /** - * Port number of target external system to connect. - */ - protected port: number; - /** - * Construct from parent {@link ParallelSystemArray}. - * - * @param systemArray The parent {@link ParallelSystemArray} object. - */ - constructor(systemArray: ParallelSystemArray); - /** - * Factory method creating {@link IServerConnector} object. - * - * The {@link createServerConnector createServerConnector()} is an abstract method creating - * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the slave server - * follows: - * - * - {@link ServerConnector} - * - {@link WebServerConnector} - * - {@link DedicatedWorkerServerConnector} - * - {@link SharedWorkerServerConnector} - * - * @return A newly created {@link IServerConnector} object. - */ - protected abstract createServerConnector(): protocol.IServerConnector; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * Master of Parallel Processing System, a client connecting to slave servers. - * - * The {@link ParallelServerArray} is an abstract class, derived from the {@link ParallelSystemArray} class, - * connecting to {@link IParallelServer parallel servers}. - * - * Extends this {@link ParallelServerArray} and overrides {@link createChild createChild()} method creating child - * {@link IParallelServer} object. After the extending and overriding, construct children {@link IParallelServer} - * objects and call the {@link connect connect()} method. - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelServerArray extends ParallelSystemArray implements external.IExternalServerArray { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * Mediator of Parallel Processing System, a client connecting to slave servers. - * - * The {@link ParallelServerArrayMediator} is an abstract class, derived from the {@link ParallelSystemArrayMediator} - * class, connecting to {@link IParallelServer parallel servers}. - * - * Extends this {@link ParallelServerArrayMediator} and overrides {@link createChild createChild()} method creating - * child {@link IParallelServer} object. After the extending and overriding, construct children - * {@link IParallelServer} objects and call the {@link connect connect()} method. - * - * #### [Inherited] {@link ParallelSystemArrayMediator} - * The {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a **slave** to its - * master system at the same time. This {@link ParallelSystemArrayMediator} be a **master **system, containing and - * managing {@link ParallelSystem} objects, which represent parallel slave systems, by extending - * {@link ParallelSystemArray} class. Also, be a **slave** system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a **master**, you can specify this {@link ParallelSystemArrayMediator} class to be a master server accepting - * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one - * of them below and overrides abstract factory method(s) creating the child {@link ParallelSystem} object. - * - * - {@link ParallelClientArrayMediator}: A server accepting {@link ParallelSystem parallel clients}. - * - {@link ParallelServerArrayMediator}: A client connecting to {@link ParallelServer parallel servers}. - * - {@link ParallelServerClientArrayMediator}: Both of them. Accepts {@link ParallelSystem parallel clients} and - * connects to {@link ParallelServer parallel servers} at the same time. - * - * As a **slave**, you can specify this {@link ParallelSystemArrayMediator} to be a client slave connecting to - * master server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelServerArrayMediator extends ParallelSystemArrayMediator implements external.IExternalServerArray { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * Master of Parallel Processing System, be a server and client at the same time. - * - * The {@link ParallelServerClientArray} is an abstract class, derived from the {@link ParallelSystemArray} class, - * opening a server accepting {@link ParallelSystem parallel clients} and being a client connecting to - * {@link IParallelServer parallel servers} at the same time. - * - * Extends this {@link ParallelServerClientArray} and overrides below methods. After the overridings, open server - * with {@link open open()} method and connect to {@link IParallelServer parallel servers} through the - * {@link connect connect()} method. - * - * - {@link createServerBase createServerBase()} - * - {@link createExternalClient createExternalClient()} - * - {@link createExternalServer createExternalServer()} - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelServerClientArray extends ParallelClientArray implements external.IExternalServerClientArray { - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method of a child Entity. - * - * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. - * - * @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()}. - */ - createChild(xml: library.XML): System; - /** - * Factory method creating an {@link IParallelServer} 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 IParallelServer} object. - */ - protected abstract createExternalServer(xml: library.XML): System; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * Mediator of Parallel Processing System, be a server and client at the same time as a **master**. - * - * The {@link ParallelServerClientArrayMediator} is an abstract class, derived from the - * {@link ParallelSystemArrayMediator} class, opening a server accepting {@link ParallelSystem parallel clients} and - * being a client connecting to {@link IParallelServer parallel servers} at the same time. - * - * Extends this {@link ParallelServerClientArrayMediator} and overrides below methods. After the overridings, open - * server with {@link open open()} method and connect to {@link IParallelServer parallel servers} through the - * {@link connect connect()} method. - * - * - {@link createServerBase createServerBase()} - * - {@link createExternalClient createExternalClient()} - * - {@link createExternalServer createExternalServer()} - * - * #### [Inherited] {@link ParallelSystemArrayMediator} - * The {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a **slave** to its - * master system at the same time. This {@link ParallelSystemArrayMediator} be a **master **system, containing and - * managing {@link ParallelSystem} objects, which represent parallel slave systems, by extending - * {@link ParallelSystemArray} class. Also, be a **slave** system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a **master**, you can specify this {@link ParallelSystemArrayMediator} class to be a master server accepting - * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one - * of them below and overrides abstract factory method(s) creating the child {@link ParallelSystem} object. - * - * - {@link ParallelClientArrayMediator}: A server accepting {@link ParallelSystem parallel clients}. - * - {@link ParallelServerArrayMediator}: A client connecting to {@link ParallelServer parallel servers}. - * - {@link ParallelServerClientArrayMediator}: Both of them. Accepts {@link ParallelSystem parallel clients} and - * connects to {@link ParallelServer parallel servers} at the same time. - * - * As a **slave**, you can specify this {@link ParallelSystemArrayMediator} to be a client slave connecting to - * master server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *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*.
    • - *
    - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelServerClientArrayMediator extends ParallelClientArrayMediator implements external.IExternalServerClientArray { - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method of a child Entity. - * - * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. - * - * @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()}. - */ - createChild(xml: library.XML): System; - /** - * Factory method creating an {@link IParallelServer} 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 IParallelServer} object. - */ - protected abstract createExternalServer(xml: library.XML): System; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * History of an {@link Invoke} message. - * - * The {@link PRInvokeHistory} is a class archiving history log of an {@link Invoke} message which requests the - * *parallel process*, created whenever {@link ParallelSystemArray.sendSegmentData} or - * {@link ParallelSystemArray.sendSegmentData} is called. - * - * When the *parallel process* has completed, then {@link complete complete()} is called and the *elapsed time* is - * determined. The elapsed time is utilized for computation of {@link ParallelSystem.getPerformance performance index} - * of each {@link ParallelSystem parallel slave system}. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - class PRInvokeHistory extends protocol.InvokeHistory { - /** - * @hidden - */ - private first; - /** - * @hidden - */ - private last; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from an {@link Invoke} message. - * - * @param invoke An {@link Invoke} message requesting a *parallel process*. - */ - constructor(invoke: protocol.Invoke); - /** - * Get initial piece's index. - * - * Returns initial piece's index in the section of requested *parallel process*. - * - * @return The initial index. - */ - getFirst(): number; - /** - * Get final piece's index. - * - * Returns initial piece's index in the section of requested *parallel process*. The range 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*. - * - * @return The final index. - */ - getLast(): number; - /** - * Compute number of allocated pieces. - */ - computeSize(): number; - } -} -declare namespace samchon.templates.service { - /** - * A driver of remote client. - * - * The {@link Client} is an abstract class representing and interacting with a remote client. It deals the network - * communication with the remote client and shifts {@link Invoke} message to related {@link User} and {@link Service} - * objects. - * - * Extends this {@link Client} class and override the {@link createService} method, a factory method creating a child - * {@link Service} object. Note that, {@link Client} represents a remote client, not *an user*, a specific *web page* - * or *service*. Do not define logics about user or account information. It must be declared in the parent - * {@link User} class. Also, don't define processes of a specific a web page or service. Defines them in the child - * {@link Service} class. - * - * - * - * - * - * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) - * @author Jeongho Nam - */ - abstract class Client implements protocol.IProtocol { - /** - * @hidden - */ - private user_; - /** - * @hidden - */ - private no_; - /** - * @hidden - */ - private communicator_; - /** - * @hidden - */ - private service_; - /** - * Construct from parent {@link User} and communicator. - * - * @param user Parent {@link User} object. - * @param driver Communicator with remote client. - */ - constructor(user: User, driver: protocol.WebClientDriver); - /** - * Default Destructor. - * - * This {@link destructor destructor()} method is called when the {@link Client} object is destructed and this - * {@link Client} object is destructed when connection with the remote client is closed or this {@link Client} - * object is {@link User.erase erased} from its parent {@link User} object. - * - * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically - * by those *destruction* cases. Also, if your derived {@link Client} class has something to do on the - * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. - * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. - * - * ```typescript - * class MyUser extends protocol.service.Client - * { - * protected destructor(): void - * { - * // DO SOMETHING - * this.do_something(); - * - * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS - * super.destructor(); - * } - * } - * ``` - */ - protected destructor(): void; - /** - * Factory method creating {@link Service} object. - * - * @param path Requested path. - * @return A newly created {@link Service} object or ```null```. - */ - protected abstract createService(path: string): Service; - /** - * Close connection. - */ - close(): void; - /** - * Get parent {@link User} object. - * - * Get the parent {@link User} object, who is groupping {@link Client} objects with same session id. - * - * @return The parent {@link User} object. - */ - getUser(): User; - /** - * Get child {@link Service} object. - * - * @return The child {@link Service} object. - */ - getService(): Service; - /** - * Get sequence number. - * - * Get sequence number of this {@link Client} object in the parent {@link User} object. This sequence number also - * be a *key* in the parent {@link User} object, who extended the ```std.HashMap```. - * - * @return Sequence number. - */ - getNo(): number; - /** - * Change related {@link Service} object. - * - * @param path Requested, identifier path. - */ - protected changeService(path: string): void; - /** - * Change {@link Service} to another. - * - * @param service {@link service} object to newly assigned. - */ - protected changeService(service: Service): void; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message to remote client. - * - * @param invoke An {@link Invoke} messgae to send to remote client. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle a replied {@link Invoke} message. - * - * The default {@link Client.replyData Client.replyData()} shifts chain to its parent {@link User} and belonged - * {@link Service} objects, by calling the the {@link User.replyData User.replyData()} and - * {@link Service.replyData Service.replyData()} methods. - * - * Note that, {@link Client} represents a remote client, not *an user*, a specific *web page* or *service*. Do not - * define logics about user or account information. It must be declared in the parent {@link User} class. Also, - * don't define processes of a specific a web page or service. Defines them in the child {@link Service} class. - * - * ```typescript - * class protocol.service.Client - * { - * public replyData(invoke: protocol.Invoke): void - * { - * // SHIFT TO PARENT USER - * // THE PARENT USER ALSO MAY SHIFT TO ITS PARENT SERVER - * this.getUser().replyData(invoke); - * - * // SHIFT TO BELOGED SERVICE - * if (this.getService() != null) - * this.getService().replyData(invoke); - * } - * } - * - * class MyClient extends protocol.service.Client - * { - * public replyData(invoke: protocol.Invoke): void - * { - * if (invoke.getListener() == "do_something_in_client_level") - * this.do_something_in_client_level(); - * else - * super.replyData(invoke); - * } - * } - * ``` - * - * @param invoke An {@link Invoke invoke} message to be handled in {@link Client} level. - */ - replyData(invoke: protocol.Invoke): void; - } -} -/** - * A system template for Cloud Service. - * - * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) - * @author Jeongho Nam - */ -declare namespace samchon.templates.service { - /** - * A cloud server. - * - * The {@link Server} is an abstract server class, who can build a real-time cloud server, that is following the - * web-socket protocol. Extends this {@link Server} and related classes and overrides abstract methods under below. - * After the overridings, open this {@link Server cloud server} using the {@link open open()} method. - * - * - Objects in composite relationship and their factory methods - * - {@link User}: {@link Server.createUser Server.createUser()} - * - {@link Client}: {@link User.createClient User.createClient()} - * - {@link Service}: {@link Client.createService Client.createService()} - * - {@link Invoke} message chains; {@link IProtocol.replyData replyData} - * - {@link Server.replyData} - * - {@link User.replyData} - * - {@link Client.replyData} - * - {@link Service.replyData} - * - * - * - * - * - * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) - * @author Jeongho Nam - */ - abstract class Server extends protocol.WebServer implements protocol.IProtocol { - /** - * @hidden - */ - private session_map_; - /** - * @hidden - */ - private account_map_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating {@link User} object. - * - * @return A newly created {@link User} object. - */ - protected abstract createUser(): User; - /** - * Test wheter an {@link User} exists with the *accountID*. - * - * @param accountID Account id of {@link User} to find. - * @return Exists or not. - */ - has(accountID: string): boolean; - /** - * Get an {@link User} object by its *accountID*. - * - * @param accountID Account id of {@link User} to get. - * @return An {@link User} object. - */ - get(accountID: string): User; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message to all remote clients through the belonged {@link User} and {@link Client} - * objects. Sending the {@link Invoke} message to all remote clients, it's came true by passing through - * {@link User.sendData User.sendData()}. And the {@link User.sendData} also pass through the - * {@link Client.sendData Client.sendData()}. - * - * ```typescript - * class protocol.service.Server - * { - * public sendData(invoke: Invoke): void - * { - * for (user: User in this) - * for (client: Client in user) - * client.sendData(invoke); - * } - * } - * ``` - * - * @param invoke {@link Invoke} message to send to all remote clients. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle a replied {@link Invoke} message. - * - * The {@link Server.replyData Server.replyData()} is an abstract method that handling {@link Invoke} message - * that should be handled in the {@link Server} level. Overrides this {@link replyData replyData()} method and - * defines what to do with the {@link Invoke} message in this {@link Server} level. - * - * @param invoke An {@link Invoke invoke} message to be handled in {@link Server} level. - */ - abstract replyData(invoke: protocol.Invoke): void; - /** - * Add a newly connected remote client. - * - * When a {@link WebClientDriver remote client} connects to this cloud server, then {@link Server} queries the - * {WebClientDriver.getSessionID session id} of the {@link WebClientDriver remote client}. If the - * {WebClientDriver.getSessionID session id} is new one, then creates a new {@link User} object. - * - * At next, creates a {@link Client} object who represents the newly connected remote client and insert the - * {@link Client} object to the matched {@link User} object which is new or ordinary one following the - * {WebClientDriver.getSessionID session id}. At last, a {@link Service} object can be created with referencing - * the {@link WebClientDriver.getPath path}. - * - * List of objects can be created by this method. - * - {@link User} by {@link createUser createUser()}. - * - {@link Client} by {@link User.createClient User.createClient()}. - * - {@link Service} by {@link Client.createService Client.createService()}. - * - * @param driver A web communicator for remote client. - */ - addClient(driver: protocol.WebClientDriver): void; - /** - * @hidden - */ - private erase_user(user); - } -} -declare namespace samchon.templates.service { - /** - * A service. - * - * The {@link Service} is an abstract class who represents a service, that is providing functions a specific page. - * - * Extends the {@link Service} class and defines its own service, which to be provided for the specific weg page, - * by overriding the {@link replyData replyData()} method. Note that, the service, functions for the specific page - * should be defined in this {@link Service} class, not its parent {@link Client} class who represents a remote client - * and takes communication responsibility. - * - * - * - * - * - * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) - * @author Jeongho Nam - */ - abstract class Service implements protocol.IProtocol { - /** - * @hidden - */ - private client_; - /** - * @hidden - */ - private path_; - /** - * Construct from parent {@link Client} and requested path. - * - * @param client Driver of remote client. - * @param path Requested path that identifies this {@link Service}. - */ - constructor(client: Client, path: string); - /** - * Default Destructor. - * - * This {@link destructor destructor()} method is call when the {@link Service} object is destructed and the - * {@link Service} object is destructed when its parent {@link Client} object has - * {@link Client.destructor destructed} or the {@link Client} object {@link Client.changeService changed} its - * child {@link Service service} object to another one. - * - * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically - * by those *destruction* cases. Also, if your derived {@link Service} class has something to do on the - * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. - */ - protected destructor(): void; - /** - * Get client. - */ - getClient(): Client; - /** - * Get requested path. - */ - getPath(): string; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message to remote system through parent {@link Client} object ({@link Client.sendData}). - * - * @param invoke An {@link Invoke} message to send to the remte system. - */ - sendData(invoke: protocol.Invoke): void; - /** - * @inheritdoc - */ - abstract replyData(invoke: protocol.Invoke): void; - } -} -declare namespace samchon.templates.service { - /** - * An user. - * - * The {@link User} is an abstract class groupping {@link Client} objects, who communicates with remote client, with - * same *session id*. This {@link User} represents a *remote user* literally. Within framework of remote system, - * an {@link User} corresponds to a web-browser and a {@link Client} represents a window in the web-browser. - * - * Extends this {@link User} class and override the {@link createClient} method, a factory method creating a child - * {@link Client} object. I repeat, the {@link User} class represents a *remote user*, groupping {@link Client} - * objects with same *session id*. If your cloud server has some processes to be handled in the **user level**, then - * defines method in this {@link User} class. Methods managing **account** under below are some of them: - * - * - {@link setAccount setAccount()} - * - {@link getAccountID getAccountID()} - * - {@link getAuthority getAuthority()} - * - * The children {@link Client} objects, they're contained with their key, the {@link Client.getNo sequence number}. - * If you {@link User.erase erase} the children {@link Client} object by yourself, then their connection with the - * remote clients will be {@link Client.close closed} and their {@link Client.destructor destruction method} will be - * called. If you remove {@link clear all children}, then this {@link User} object will be also - * {@link destructor destructed} and erased from the parent {@link Server} object. - * - * - * - * - * - * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) - * @author Jeongho Nam - */ - abstract class User extends collections.HashMapCollection implements protocol.IProtocol { - /** - * @hidden - */ - private server_; - /** - * @hidden - */ - private session_id_; - /** - * @hidden - */ - private sequence_; - /** - * @hidden - */ - private account_id_; - /** - * @hidden - */ - private authority_; - /** - * Construct from its parent {@link Server}. - * - * @param server The parent {@link Server} object. - */ - constructor(server: Server); - /** - * Default Destructor. - * - * This {@link destructor destructor()} method is called when the {@link User} object is destructed. The - * {@link User} object is destructed when connections with the remote clients are all closed, that is all the - * children {@link Client} objects are all removed, and 30 seconds has left. If some remote client connects - * within the 30 seconds, then the {@link User} object doesn't be destructed. - * - * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically - * by those *destruction* cases. Also, if your derived {@link User} class has something to do on the - * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. - * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. - * - * ```typescript - * class MyUser extends protocol.service.User - * { - * protected destructor(): void - * { - * // DO SOMETHING - * this.do_something(); - * - * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS - * super.destructor(); - * } - * } - * ``` - */ - protected destructor(): void; - /** - * Factory method creating a {@link Client} object. - * - * @param driver A web communicator for remote client. - * @return A newly created {@link Client} object. - */ - protected abstract createClient(driver: protocol.WebClientDriver): Client; - /** - * @hidden - */ - private handle_erase_client(event); - /** - * Get parent {@lin Server} object. - * - * @return Parent {@link Server} object. - */ - getServer(): Server; - /** - * Get account id. - * - * @return Account ID. - */ - getAccountID(): string; - /** - * Get authority. - * - * @return Authority - */ - getAuthority(): number; - /** - * Set *account id* and *authority*. - * - * The {@link setAccount setAccount()} is a method configuring *account id* and *authority* of this {@link User}. - * - * After the configuring, the {@link getAccountID account id} is enrolled into the parent {@link Server} as a - * **key** for this {@link User} object. You can test existence and access this {@link User} object from - * {@link Server.has Server.has()} and {@link Server.get Server.get()} with the {@link getAccountID account id}. - * Of course, if ordinary {@link getAccountID account id} had existed, then the ordinary **key** will be - * replaced. - * - * As you suggest, this {@link setAccount setAccount()} is something like a **log-in** function. If what you want - * is not **logging-in**, but **logging-out**, then configure the *account id* to empty string ``""```` or call - * the {@link lgout logout()} method. - * - * @param id To be account id. - * @param authority To be authority. - */ - setAccount(id: string, authority: number): void; - /** - * Log-out. - * - * This {@link logout logout()} method configures {@link getAccountID account id} to empty string and - * {@link getAuthority authority} to zero. - * - * The ordinary {@link getAccountID account id} will be also erased from the parent {@link Server} object. You - * can't access this {@link User} object from {@link Server.has Server.has()} and {@link Server.get Server.get()} - * with the ordinary {@link getAccountID account id} more. - */ - logout(): void; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message to all remote clients through the belonged {@link Client} objects. Sending the - * {@link Invoke} message to all remote clients, it's came true by passing through the - * {@link Client.sendData Client.sendData()} methods. - * - * ```typescript - * class protocol.service.User - * { - * public sendData(invoke: Invoke): void - * { - * for (let it = this.begin(); !it.equal_to(this.end()); it = it.next()) - * it.second.sendData(invoke); - * } - * } - * ``` - * - * @param invoke {@link Invoke} message to send to all remote clients. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle a replied {@link Invoke} message. - * - * The default {@link User.replyData User.replyData()} shifts chain to its parent {@link Server} object, by - * calling the {@link Server.replyData Server.replyData()} method. If there're some {@link Invoke} message to be - * handled in this {@link User} level, then override this method and defines what to do with the {@link Invoke} - * message in this {@link User} level. - * - * ```typescript - * class protocol.service.User - * { - * public replyData(invoke: protocol.Invoke): void - * { - * this.getServer().replyData(invoke); - * } - * } - * - * class MyUser extends protocol.service.User - * { - * public replyData(invoke: protocol.Invoke): void - * { - * if (invoke.apply(this) == false) // IS TARGET TO BE HANDLED IN THIS USER LEVEL - * super.replyData(invoke); // SHIFT TO SERVER - * } - * } - * ``` - * - * @param invoke An {@link Invoke invoke} message to be handled in {@link User} level. - */ - replyData(invoke: protocol.Invoke): void; - } -} -declare namespace samchon.templates.slave { - interface ISlaveClient extends SlaveSystem { - connect(ip: string, port: number): void; - } - abstract class SlaveClient extends SlaveSystem implements ISlaveClient { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - protected abstract createServerConnector(): protocol.IServerConnector; - /** - * @inheritdoc - */ - connect(ip: string, port: number): void; - } -} -declare namespace samchon.templates.slave { - interface ISlaveServer extends SlaveSystem, protocol.IServer { - } - abstract class SlaveServer extends SlaveSystem implements ISlaveServer { - private server_base_; - constructor(); - protected abstract createServerBase(): protocol.IServerBase; - open(port: number): void; - close(): void; - addClient(driver: protocol.IClientDriver): void; - } -} +} \ No newline at end of file diff --git a/samchon/index.d.ts b/samchon/index.d.ts new file mode 100644 index 0000000000..6f2bc17b43 --- /dev/null +++ b/samchon/index.d.ts @@ -0,0 +1,8403 @@ +// Type definitions for Samchon Framework v2.0.7 +// Project: https://github.com/samchon/framework +// Definitions by: Jeongho Nam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "samchon" +{ + export = samchon; +} + +/** + * # Samchon Framework + * + * + * + * + * Samchon, a OON (Object-Oriented 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.collections { + /** + * A {@link Vector} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link push} + * - {@link push_back} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - {@link pop_back} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link Vector} + * @copydoc Vector + */ + class ArrayCollection extends std.Vector implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @inheritdoc + */ + push(...items: T[]): number; + /** + * @inheritdoc + */ + push_back(val: T): void; + /** + * @hidden + */ + 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; + /** + * @hidden + */ + private _Notify_insert(first, last); + /** + * @hidden + */ + private _Notify_erase(first, last); + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.VectorIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.VectorIterator, last: std.VectorIterator): void; + /** + * @inheritdoc + */ + 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: 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: 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: 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.library { + /** + * A basic event class of Samchon Framework. + * + * @reference https://developer.mozilla.org/en-US/docs/Web/API/Event + * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-EventDispatcher + * @author Jeongho Nam + */ + class BasicEvent { + protected type_: string; + protected target_: IEventDispatcher; + private currentTarget_; + protected trusted_: boolean; + protected bubbles_: boolean; + protected cancelable_: boolean; + protected defaultPrevented_: boolean; + protected cancelBubble_: boolean; + private timeStamp_; + constructor(type: string, bubbles?: boolean, cancelable?: boolean); + /** + * @inheritdoc + */ + initEvent(type: string, bubbles: boolean, cancelable: boolean): void; + /** + * @inheritdoc + */ + /** + * @inheritdoc + */ + stopImmediatePropagation(): void; + /** + * @inheritdoc + */ + stopPropagation(): void; + /** + * @inheritdoc + */ + readonly type: string; + /** + * @inheritdoc + */ + target: IEventDispatcher; + /** + * @inheritdoc + */ + readonly currentTarget: IEventDispatcher; + /** + * @inheritdoc + */ + readonly bubbles: boolean; + /** + * @inheritdoc + */ + readonly cancelable: boolean; + /** + * @inheritdoc + */ + readonly eventPhase: number; + /** + * @inheritdoc + */ + readonly defaultPrevented: boolean; + /** + * @inheritdoc + */ + readonly srcElement: Element; + /** + * @inheritdoc + */ + readonly cancelBubble: boolean; + /** + * @inheritdoc + */ + readonly timeStamp: number; + /** + * Don't know what it is. + */ + readonly returnValue: boolean; + } +} +declare namespace samchon.collections { + /** + * Type of function pointer for listener of {@link CollectionEvent CollectionEvents}. + */ + type CollectionEventListener = (event: CollectionEvent) => void; +} +declare namespace samchon.collections { + /** + * An event occured in a {@link ICollection collection} object. + * + * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) + * @author Jeongho Nam + */ + class CollectionEvent extends library.BasicEvent { + /** + * @hidden + */ + private first_; + /** + * @hidden + */ + private last_; + /** + * @hidden + */ + private temporary_container_; + /** + * @hidden + */ + private origin_first_; + /** + * Initialization Constructor. + * + * @param type Type of collection event. + * @param first An {@link Iterator} to the initial position in this {@link CollectionEvent}. + * @param last An {@link Iterator} to the final position in this {@link CollectionEvent}. + */ + 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); + /** + * Associative target, the {@link ICollection collection}. + */ + readonly target: ICollection; + /** + * An {@link Iterator} to the initial position in this {@link CollectionEvent}. + */ + readonly first: std.Iterator; + /** + * An {@link Iterator} to the final position in this {@link CollectionEvent}. + */ + readonly last: std.Iterator; + /** + * @inheritdoc + */ + preventDefault(): void; + } +} +declare namespace samchon.collections.CollectionEvent { + const INSERT: "insert"; + const ERASE: "erase"; + const REFRESH: "refresh"; +} +declare namespace samchon.collections { + /** + * A {@link Deque} who can detect element I/O events. + * + * Below is the 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} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link Deque} + * @copydoc Deque + */ + class DequeCollection extends std.Deque implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @inheritdoc + */ + push_front(val: T): void; + /** + * @inheritdoc + */ + push_back(val: T): void; + /** + * @hidden + */ + protected _Insert_by_range>(position: std.DequeIterator, begin: InputIterator, end: InputIterator): std.DequeIterator; + /** + * @inheritdoc + */ + pop_front(): void; + /** + * @inheritdoc + */ + pop_back(): void; + /** + * @hidden + */ + protected _Erase_by_range(first: std.DequeIterator, last: std.DequeIterator): std.DequeIterator; + /** + * @hidden + */ + private _Notify_insert(first, last); + /** + * @hidden + */ + private _Notify_erase(first, last); + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.DequeIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.DequeIterator, last: std.DequeIterator): void; + /** + * @inheritdoc + */ + 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: 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: 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: 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.collections { + /** + * A {@link HashMap} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link MapCollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link insert_or_assign} + * - {@link emplace} + * - {@link set} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - {@link extract} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link HashMap} + * @copydoc HashMap + */ + class HashMapCollection extends std.HashMap implements ICollection> { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + 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: 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: 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: 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.collections { + /** + * A {@link HashMultiMap} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link MapCollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link emplace} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link HashMultiMap} + * @copydoc HashMultiMap + */ + class HashMultiMapCollection extends std.HashMultiMap implements ICollection> { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + 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: 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: 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: 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.collections { + /** + * A {@link HashMultiSet} who can detect element I/O events. + * + * Below is the 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} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link HashMultiSet} + * @copydoc HashMultiSet + */ + class HashMultiSetCollection extends std.HashMultiSet implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + 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: 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: 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: 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.collections { + /** + * A {@link HashSet} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link push} + * - {@link insert_or_assign} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - {@link extract} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link HashSet} + * @copydoc HashSet + */ + class HashSetCollection extends std.HashSet implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + 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: 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: 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: 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; + } +} +/** + * Collections, elements I/O detectable STL containers. + * + * STL Containers | Collections + * ---------------------|------------------- + * {@link Vector} | {@link ArrayCollection} + * {@link List} | {@link ListCollection} + * {@link Deque} | {@link DequeCollection} + * | + * {@link TreeSet} | {@link TreeSetCollection} + * {@link HashSet} | {@link HashSetCollection} + * {@link TreeMultiSet} | {@link TreeMultiSetCollection} + * {@link HashMultiSet} | {@link HashMultiSetCollection} + * | + * {@link TreeMap} | {@link TreeMapCollection} + * {@link HashMap} | {@link HashMapCollection} + * {@link TreeMultiMap} | {@link TreeMultiMapCollection} + * {@link HashMultiMap} | {@link HashMultiMapCollection} + * + * @author Jeongho Nam + */ +declare namespace samchon.collections { + /** + * 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} + * - *refresh* typed events: + * - {@link refresh} + * + * @author Jeongho Nam + */ + interface ICollection extends std.base.Container, 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: 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: 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: 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: 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 { + /** + * @hidden + */ + function _Dispatch_CollectionEvent(collection: ICollection, type: string, first: std.Iterator, last: std.Iterator): void; + /** + * @hidden + */ + function _Dispatch_MapCollectionEvent(collection: ICollection>, type: string, first: std.MapIterator, last: std.MapIterator): void; + } +} +declare namespace samchon.collections { + /** + * A {@link List} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *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} + * - *refresh* typed events: + * - {@link refresh} + * - {@link sort} + * + * #### [Inherited] {@link List} + * @copydoc List + */ + class ListCollection extends std.List implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Insert_by_range>(position: std.ListIterator, begin: InputIterator, end: InputIterator): std.ListIterator; + /** + * @hidden + */ + protected _Erase_by_range(first: std.ListIterator, last: std.ListIterator): std.ListIterator; + /** + * @hidden + */ + private _Notify_insert(first, last); + /** + * @hidden + */ + private _Notify_erase(first, last); + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.ListIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.ListIterator, last: std.ListIterator): void; + /** + * @inheritdoc + */ + 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: 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: 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: 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.collections { + type MapCollectionEventListener = (event: MapCollectionEvent) => void; + /** + * An event occured in a {@link MapContainer map container} object. + * + * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) + * @author Jeongho Nam + */ + class MapCollectionEvent extends CollectionEvent> { + /** + * @inheritdoc + */ + readonly first: std.MapIterator; + /** + * @inheritdoc + */ + readonly last: std.MapIterator; + } +} +declare namespace samchon.collections { + /** + * A {@link TreeMap} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link MapCollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link insert_or_assign} + * - {@link emplace} + * - {@link set} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - {@link extract} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link TreeMap} + * @copydoc TreeMap + */ + class TreeMapCollection extends std.TreeMap implements ICollection> { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + 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: 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: 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: 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.collections { + /** + * A {@link TreeMultiMap} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link MapCollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link emplace} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link TreeMultiMap} + * @copydoc TreeMultiMap + */ + class TreeMultiMapCollection extends std.TreeMultiMap implements ICollection> { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + 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: 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: 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: 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.collections { + /** + * A {@link TreeMultiSet} who can detect element I/O events. + * + * Below is the 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} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link TreeMultiSet} + * @copydoc TreeMultiSet + */ + class TreeMultiSetCollection extends std.TreeMultiSet implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + 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: 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: 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: 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.collections { + /** + * A {@link TreeMap} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link insert_or_assign} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear}7 + * - {@link erase} + * - {@link extract} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link TreeSet} + * @copydoc TreeSet + */ + class TreeSetCollection extends std.TreeSet implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + 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: 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: 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: 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.library { + /** + * Case generator. + * + * {@link CaseGenerator} is an abstract case generator being used like a matrix. + *
      + *
    • n��r(n^r) -> {@link CombinedPermutationGenerator}
    • + *
    • nPr -> {@link PermutationGenerator}
    • + *
    • n! -> {@link FactorialGenerator}
    • + *
    + * + * @author Jeongho Nam + */ + abstract class CaseGenerator { + /** + * Size, the number of all cases. + */ + protected size_: number; + /** + * N, size of the candidates. + */ + protected n_: number; + /** + * R, size of elements of each case. + */ + protected r_: number; + /** + * Construct from size of N and R. + * + * @param n Size of candidates. + * @param r Size of elements of each case. + */ + constructor(n: number, r: number); + /** + * Get size of all cases. + * + * @return Get a number of the all cases. + */ + size(): number; + /** + * Get size of the N. + */ + n(): number; + /** + * Get size of the R. + */ + r(): number; + /** + * Get index'th case. + * + * @param index Index number + * @return The row of the index'th in combined permuation case + */ + abstract at(index: number): number[]; + } + /** + * A combined-permutation case generator. + * + * n��r + * + * @author Jeongho Nam + */ + class CombinedPermutationGenerator extends CaseGenerator { + /** + * An array using for dividing each element index. + */ + private divider_array; + /** + * Construct from size of N and R. + * + * @param n Size of candidates. + * @param r Size of elements of each case. + */ + constructor(n: number, r: number); + at(index: number): number[]; + } + /** + * A permutation case generator. + * + * nPr + * + * @author Jeongho Nam + */ + class PermuationGenerator extends CaseGenerator { + /** + * Construct from size of N and R. + * + * @param n Size of candidates. + * @param r Size of elements of each case. + */ + constructor(n: number, r: number); + /** + * @inheritdoc + */ + at(index: number): number[]; + } + /** + * Factorial case generator. + * + * n! = nPn + * + * @author Jeongho Nam + */ + class FactorialGenerator extends PermuationGenerator { + /** + * Construct from factorial size N. + * + * @param n Factoria size N. + */ + constructor(n: number); + } +} +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. + * + * The event 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 target node; and the bubbling phase + * includes any subsequent nodes encountered on the return trip to the root of the display list. + * + * In general, the easiest way for a user-defined class to gain event dispatching capabilities is to extend + * {@link EventDispatcher}. If this is impossible (that is, if the class is already extending another class), you + * can instead implement the {@link IEventDispatcher} interface, create an {@link EventDispatcher} member, and + * write simple hooks to route calls into the aggregated {@link EventDispatcher}. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/IEventDispatcher.html + * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-EventDispatcher + * @author Migrated by Jeongho Nam + */ + interface IEventDispatcher { + /** + * Checks whether the {@link EventDispatcher} object has any listeners registered for a specific type of event. + * This allows you to determine where an {@link EventDispatcher} object has altered handling of an event type + * in the event flow hierarchy. To determine whether a specific event type actually triggers an event listener, + * use {@link willTrigger willTrigger()}. + * + * The difference between {@link hasEventListener hasEventListener()} and {@link willTrigger willTrigger()} is + * that {@link hasEventListener} examines only the object to which it belongs, whereas {@link willTrigger} + * examines the entire event flow for the event specified by the type parameter. + * + * @param type The type of event. + */ + hasEventListener(type: string): boolean; + /** + * Dispatches an event into the event flow. + * + * The event target is the {@link EventDispatcher} object upon which the {@link dispatchEvent dispatchEvent()} + * method is called. + * + * @param event The {@link BasicEvent} object that is dispatched into the event flow. If the event is being + * redispatched, a clone of the event is created automatically. After an event is dispatched, its + * target property cannot be changed, so you must create a new copy + * of the event for redispatching to work. + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * Registers an event listener object with an {@link 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 {@link addEventListener addEventListener()|} To change a listener's priority, you must first call + * {@link removeEventListener 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 {@link 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 {@link 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 {@link 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 {@link EventDispatcher} instance does not copy the event listeners attached to it. (If your n + * ewly created node needs an event listener, you must attach the listener after creating the node.) However, + * if you move an {@link 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. + * @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: string, listener: library.BasicEventListener): void; + /** + * Registers an event listener object with an {@link 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 {@link addEventListener addEventListener()|} To change a listener's priority, you must first call + * {@link removeEventListener 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 {@link 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 {@link 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 {@link 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 {@link EventDispatcher} instance does not copy the event listeners attached to it. (If your n + * ewly created node needs an event listener, you must attach the listener after creating the node.) However, + * if you move an {@link 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. + * @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: library.BasicEventListener, thisArg: Object): void; + /** + * Removes a listener from the {@link EventDispatcher} object. If there is no matching listener registered + * with the {@link EventDispatcher} object, a call to this method has no effect. + * + * @param type The type of event. + * @param listener The listener object to remove. + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + /** + * Removes a listener from the {@link EventDispatcher} object. If there is no matching listener registered + * with the {@link EventDispatcher} object, a call to this method has no effect. + * + * @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: library.BasicEventListener, thisArg: Object): void; + } + /** + * The {@link EventDispatcher} class is the base class for all classes that dispatch events. The + * {@link EventDispatcher} class implements the {@link IEventDispatcher} interface and is the base class for the + * {@link DisplayObject} class. The {@link EventDispatcher} class allows any object on the display list to be an + * event target and as such, to use the methods of the {@link IEventDispatcher} interface. + * + * The event 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 target node; and the bubbling phase + * includes any subsequent nodes encountered on the return trip to the root of the display list. + * + * In general, the easiest way for a user-defined class to gain event dispatching capabilities is to extend + * {@link EventDispatcher}. If this is impossible (that is, if the class is already extending another class), you + * can instead implement the {@link IEventDispatcher} interface, create an {@link EventDispatcher} member, and + * write simple hooks to route calls into the aggregated {@link EventDispatcher}. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/EventDispatcher.html + * @author Migrated by Jeongho Nam + */ + class EventDispatcher implements IEventDispatcher { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + private event_listeners_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from the origin event dispatcher. + * + * @param dispatcher The origin object who issuing events. + */ + constructor(dispatcher: IEventDispatcher); + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + } +} +declare namespace samchon.library { + /** + * The {@link FileReference} class provides a means to load and save files in browser level. + * + * The {@link FileReference} class provides a means to {@link load} and {@link save} files in browser level. A + * browser-system dialog box prompts the user to select a file to {@link load} or a location for {@link svae}. Each + * {@link FileReference} object refers to a single file on the user's disk and has properties that contain + * information about the file's size, type, name, creation date, modification date, and creator type (Macintosh only). + * + * + * FileReference instances are created in the following ways: + *
      + *
    • + * When you use the new operator with the {@link FileReference} constructor: + * let myFileReference: FileReference = new FileReference(); + *
    • + *
    • + * When you call the {@link FileReferenceList.browse} method, which creates an array of {@link FileReference} + * objects. + *
    • + *
    + * + * During a load operation, all the properties of a {@link FileReference} object are populated by calls to the + * {@link FileReference.browse} or {@link FileReferenceList.browse} methods. During a save operation, the name + * property is populated when the select event is dispatched; all other properties are populated when the complete + * event is dispatched. + * + * The {@link browse browse()} method opens an browser-system dialog box that prompts the user to select a file + * for {@link load}. The {@link FileReference.browse} method lets the user select a single file; the + * {@link FileReferenceList.browse} method lets the user select multiple files. After a successful call to the + * {@link browse browse()} method, call the {@link FileReference.load} method to load one file at a time. The + * {@link FileReference.save} method prompts the user for a location to save the file and initiates downloading from + * a binary or string data. + * + * The {@link FileReference} and {@link FileReferenceList} classes do not let you set the default file location + * for the dialog box that the {@link browse} or {@link save} methods generate. The default location shown in the + * dialog box is the most recently browsed folder, if that location can be determined, or the desktop. The classes do + * not allow you to read from or write to the transferred file. They do not allow the browser that initiated the + * {@link load} or {@link save} to access the loaded or saved file or the file's location on the user's disk. + * + * @references http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html + * @author Jeongho Nam + */ + class FileReference extends EventDispatcher { + /** + * @hidden + */ + private file_; + /** + * @hidden + */ + private data_; + /** + * Default Constructor. + */ + constructor(); + /** + * The data from the loaded file after a successful call to the {@link load load()} method. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly data: any; + /** + * The name of the file on the local disk. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly name: string; + /** + * The filename extension. + * + * A file's extension is the part of the name following (and not including) the final dot ("."). If + * there is no dot in the filename, the extension is null. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly extension: string; + /** + * The file type, metadata of the {@link extension}. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly type: string; + /** + * The size of the file on the local disk in bytes. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly size: number; + /** + * The date that the file on the local disk was last modified. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly modificationDate: Date; + /** + * 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 + * example, through a UNC path on Windows. + * + * When you call this method and the user successfully selects a file, the properties of this + * {@link FileReference} object are populated with the properties of that file. Each subsequent time that the + * {@link FileReference.browse} method is called, the {@link FileReference} object's properties are reset to + * the file that the user selects in the dialog box. Only one {@link browse browse()} can be performed at a time + * (because only one dialog box can be invoked at a time). + * + * Using the *typeFilter parameter*, you can determine which files the dialog box displays. + * + * @param typeFilter An array of filter strings used to filter the files that are displayed in the dialog box. + * If you omit this parameter, all files are displayed. + */ + browse(...typeFilter: string[]): void; + /** + * Starts the load of a local file selected by a user. + * + * You must call the {@link FileReference.browse} or {@link FileReferenceList.browse} method before you call + * the {@link load load()} method. + * + * Listeners receive events to indicate the progress, success, or failure of the load. Although you can use + * the {@link FileReferenceList} object to let users select multiple files to load, you must {@link load} the + * {@link FileReferenceList files} one by one. To {@link load} the files one by one, iterate through the + * {@link FileReferenceList.fileList} array of {@link FileReference} objects. + * + * If the file finishes loading successfully, its contents are stored in the {@link data} property. + */ + load(): 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. + */ + 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 + * {@link FileReference.load loading}. A {@link FileReferenceList} object represents a group of one or more local + * files on the user's disk as an array of {@link FileReference} objects. For detailed information and important + * considerations about {@link FileReference} objects and the FileReference class, which you use with + * {@link FileReferenceList}, see the {@link FileReference} class. + * + * To work with the {@link FileReferenceList} class: + *
      + *
    • Instantiate the class: var myFileRef = new FileReferenceList();
    • + *
    • + * Call the {@link FileReferenceList.browse} method, which opens a dialog box that lets the user select one or + * more files for upload: myFileRef.browse(); + *
    • + *
    • + * After the {@link browse browse()} method is called successfully, the {@link fileList} property of the + * {@link FileReferenceList} object is populated with an array of {@link FileReference} objects. + *
    • + *
    • Call {@link FileReference.load} on each element in the {@link fileList} array.
    • + *
    + * + * The {@link FileReferenceList} class includes a {@link browse browse()} method and a {@link fileList} property + * for working with multiple files. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReferenceList.html + * @author Jeongho Nam + */ + class FileReferenceList extends EventDispatcher { + /** + * @hidden + */ + file_list: std.Vector; + /** + * Default Constructor. + */ + constructor(); + /** + * An array of {@link FileReference} objects. + * + * When the {@link FileReferenceList.browse} method is called and the user has selected one or more files + * from the dialog box that the {@link browse browse()} method opens, this property is populated with an array of + * {@link FileReference} objects, each of which represents the files the user selected. + * + * The {@link fileList} property is populated anew each time {@link browse browse()} is called on that + * {@link FileReferenceList} object. + */ + readonly fileList: std.Vector; + /** + * Displays a file-browsing dialog box that lets the user select one or more local files to upload. The + * dialog box is native to the user's browser system. + * + * When you call this method and the user successfully selects files, the {@link fileList} property of this + * {@link FileReferenceList} object is populated with an array of {@link FileReference} objects, one for each + * file that the user selects. Each subsequent time that the {@link FileReferenceList.browse} method is called, + * the {@link FileReferenceList.fileList} property is reset to the file(s) that the user selects in the dialog + * box. + * + * Using the *typeFilter* parameter, you can determine which files the dialog box displays. + * + * Only one {@link FileReference.browse}, {@link FileReference.load}, or {@link FileReferenceList.browse} + * session can be performed at a time on a {@link FileReferenceList} object (because only one dialog box can be + * opened at a time). + * + * @param typeFilter An array of filter strings used to filter the files that are displayed in the dialog box. + * If you omit this parameter, all files are displayed. + */ + browse(...typeFilter: string[]): void; + } +} +declare namespace samchon.library { + /** + * A genetic algorithm class. + * + * 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); + children(): std.Vector; + /** + * 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. + * 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 { + /** + * Generate a substring. + * + * Extracts a substring consisting of the characters from specified start to end. + * It's same with str.substring( ? = (str.find(start) + start.size()), str.find(end, ?) ) + * + * ```typescript + * let str: string = StringUtil.between("ABCD(EFGH)IJK", "(", ")"); + * console.log(str); // PRINTS "EFGH" + * ``` + * + * - If start is not specified, extracts from begin of the string to end. + * - If end is not specified, extracts from start to end of the string. + * - 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. + * + * @return substring by specified terms. + */ + static between(str: string, start?: string, end?: string): string; + /** + * Fetch substrings. + * + * Splits a string into an array of substrings dividing by specified delimeters of start and end. + * It's the array of substrings adjusted the between. + * + *
      + *
    • If startStr is omitted, it's same with the split by endStr not having last item.
    • + *
    • If endStr is omitted, it's same with the split by startStr not having first item.
    • + *
    • If startStr and endStar are all omitted, returns *str*.
    • + *
    + * + * @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. + * @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. + */ + static betweens(str: string, start?: string, end?: string): Array; + /** + * An array containing whitespaces. + */ + private static SPACE_ARRAY; + /** + * Remove all designated characters from the beginning and end of the specified string. + * + * @param str The string whose designated characters should be trimmed. + * @param args Designated character(s). + * + * @return Updated string where designated characters was removed from the beginning and end. + */ + static trim(str: string, ...args: string[]): string; + /** + * Remove all designated characters from the beginning of the specified string. + * + * @param str The string should be trimmed. + * @param delims Designated character(s). + * + * @return Updated string where designated characters was removed from the beginning + */ + static ltrim(str: string, ...args: string[]): string; + /** + * Remove all designated characters from the end of the specified string. + * + * @param str The string should be trimmed. + * @param delims Designated character(s). + * + * @return Updated string where designated characters was removed from the end. + */ + static rtrim(str: string, ...args: string[]): string; + /** + * Substitute `{n}` tokens within the specified string. + * + * @param format The string to make substitutions in. This string can contain special tokens of the form + * `{n}`, where *n* is a zero based index, that will be replaced with the additional parameters + * found at that index if specified. + * @param args Additional parameters that can be substituted in the *format* parameter at each + * `{n}` location, where *n* is an integer (zero based) index value into the array of values + * specified. + * + * @return New string with all of the `{n}` tokens replaced with the respective arguments specified. + */ + static substitute(format: string, ...args: any[]): string; + /** + * Substitute `{n}` tokens within the specified SQL-string. + * + * @param format The string to make substitutions in. This string can contain special tokens of the form + * `{n}`, where *n* is a zero based index, that will be replaced with the additional parameters + * found at that index if specified. + * @param args Additional parameters that can be substituted in the *format* parameter at each + * `{n}` location, where *n* is an integer (zero based) index value into the array of values + * specified. + * + * @return New SQL-string with all of the `{n}` tokens replaced with the respective arguments specified. + */ + static substituteSQL(format: string, ...args: any[]): string; + /** + * @hidden + */ + private static _Fetch_substitute_index(format); + /** + * Returns a string specified word is replaced. + * + * @param str Target string to replace + * @param before Specific word you want to be replaced + * @param after Specific word you want to replace + * + * @return A string specified word is replaced + */ + static replaceAll(str: string, before: string, after: string): string; + /** + * Returns a string specified words are replaced. + * + * @param str Target string to replace + * @param pairs A specific word's pairs you want to replace and to be replaced + * + * @return A string specified words are replaced + */ + static replaceAll(str: string, ...pairs: std.Pair[]): 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. + * + * {@link URLVariables} class allows you to transfer variables between an application and server. + * + * When transfering, {@link 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.library { + /** + * A tree-structured XML object. + * + * The {@link XML| class contains methods and properties for working with XML objects. The {@link XML} class (along + * with the {@link XMLList}) implements the powerful XML-handling standards defined in ECMAScript for XML (E4X) + * specification (ECMA-357 edition 2). + * + * An XML object, it is composed with three members; {@link getTag tag}, {@link getProperty properties} and + * {@link getValue value}. As you know, XML is a tree structured data expression method. The tree-stucture; + * {@link XML} class realizes it by extending ```std.HashMap```. Child {@link XML} objects are + * contained in the matched {@link XMLList} object being grouped by their {@link getTag tag name}. The + * {@link XMLList} objects, they're stored in the {@link std.HashMap} ({@link XML} itself) with its **key**; common + * {@link getTag tag name} of children {@link XML} objects. + * + * ```typescript + * class XML extends std.HashMap + * { + * private tag_: string; + * private properties_: std.HashMap; + * private value_: string; + * } + * ``` + * + * ```xml + * + * + * + * {value} + * {value} + * {value} + * + * + * + * + * ``` + * + * Use the {@link toString toString()} method to return a string representation of the {@link XML} object regardless + * of whether the {@link XML} object has simple content or complex content. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/XML.html + * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-XML + * @author Jeongho Nam + */ + class XML extends std.HashMap { + /** + * @hidden + */ + private tag_; + /** + * @hidden + */ + private value_; + /** + * @hidden + */ + private property_map_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from string. + * + * Creates {@link XML} object by parsing a string who represents xml structure. + * + * @param str A string represents XML structure. + */ + constructor(str: string); + /** + * @hidden + */ + private _Parse(str); + /** + * @hidden + */ + private _Parse_tag(str); + /** + * @hidden + */ + private _Parse_properties(str); + /** + * @hidden + */ + private _Parse_value(str); + /** + * @hidden + */ + private _Parse_children(str); + /** + * Get tag. + * + * ```xml + * {value} + * ``` + * + * @return tag. + */ + getTag(): string; + /** + * Get value. + * + * ```xml + * {VALUE} + * ``` + * + * @return value. + */ + getValue(): string; + /** + * Get iterator to property element. + * + * Searches the {@link getPropertyMap properties} for an element with a identifier equivalent to key + * and returns an iterator to it if found, otherwise it returns an iterator to {@link HashMap.end end()}. + * + *

    Two keys are considered equivalent if the properties' comparison object returns false reflexively + * (i.e., no matter the order in which the elements are passed as arguments).

    + * + * Another member function, {@link hasProperty hasProperty()} can be used to just check whether a particular + * key exists. + * + * ```xml + * {value} + * ``` + * + * @param key Key to be searched for + * @return An iterator to the element, if an element with specified key is found, or + * {@link end HashMap.end()} otherwise. + */ + findProperty(key: string): std.MapIterator; + /** + * Test whether a property exists. + * + * ```xml + * {value} + * ``` + * + * @return Whether a property has the *key* exists or not. + */ + hasProperty(key: string): boolean; + /** + * Get property. + * + * Get property by its *key*, property name. If the matched *key* does not exist, then exception + * {@link std.OutOfRange} is thrown. Thus, it would better to test whether the *key* exits or not by calling the + * {@link hasProperty hasProperty()} method before calling this {@link getProperty getProperty()}. + * + * This method can be substituted by {@link getPropertyMap getPropertyMap()} such below: + * - ```getPropertyMap().get(key, value);``` + * - ```getPropertyMap().find(key).second;``` + * + * ```xml + * {value} + * ``` + * + * @return Value of the matched property. + */ + getProperty(key: string): string; + /** + * Get property map. + * + * ```xml + * {value} + * ``` + * + * @return {@link HashMap} containing properties' keys and values. + */ + getPropertyMap(): std.HashMap; + /** + * Set tag. + * + * Set tag name, identifier of this {@link XML} object. + * + * If this {@link XML} object is belonged to, a child of, an {@link XMLList} and its related {@link XML} objects, + * then calling this {@link setTag setTag()} method direclty is not recommended. Erase this {@link XML} object + * from parent objects and insert this object again. + * + * ```xml + * {value} + * ``` + * + * @param val To be new {@link getTag tag}. + */ + setTag(val: string): void; + /** + * Set value. + * + * ```xml + * {VALUE} + * ``` + * + * @param val To be new {@link getValue value}. + */ + setValue(val: string): void; + /** + * Set property. + * + * Set a property *value* with its *key*. If the *key* already exists, then the *value* will be overwritten to + * the property. Otherwise the *key* is not exist yet, then insert the *key* and *value* {@link Pair pair} to + * {@link getPropertyMao property map}. + * + * This method can be substituted by {@link getPropertyMap getPropertyMap()} such below: + * - ```getPropertyMap().set(key, value);``` + * - ```getPropertyMap().emplace(key, value);``` + * - ```getPropertyMap().insert([key, value]);``` + * - ```getPropertyMap().insert(std.make_pair(key, value));``` + * + * ```xml + * {value} + * ``` + * + * @param key Key, identifier of property to be newly inserted. + * @param value Value of new property to be newly inserted. + */ + setProperty(key: string, value: string): void; + /** + * Erase property. + * + * Erases a property by its *key*, property name. If the matched *key* does not exist, then exception + * {@link std.OutOfRange} is thrown. Thus, it would better to test whether the *key* exits or not by calling the + * {@link hasProperty hasProperty()} method before calling this {@link eraseProperty eraseProperty()}. + * + * This method can be substituted by ``getPropertyMap().erase(key)````. + * + * ```xml + * {value} + * ``` + * + * @param key Key of the property to erase + * @throw {@link std.OutOfRange} + */ + eraseProperty(key: string): void; + /** + * @hidden + */ + push(...args: std.Pair[]): number; + /** + * @hidden + */ + push(...args: [string, XMLList][]): number; + push(...xmls: XML[]): number; + push(...xmlLists: XMLList[]): number; + /** + * Add all properties from other {@link XML} object. + * + * All the properties in the *obj* are copied to this {@link XML} object. If this {@link XML} object has same + * property key in the *obj*, then value of the property will be replaced to *obj*'s own. If you don't want to + * overwrite properties with same key, then use {@link getPropertyMap getPropertyMap()} method. + * + * ```typescript + * let x: library.XML; + * let y: library.XML; + * + * x.addAllProperties(y); // duplicated key exists, then overwrites + * x.getPropertyMap().insert(y.getPropertyMap().begin(), y.getPropertyMap().end()); + * // ducpliated key, then ignores. only non-duplicateds are copied. + * ``` + * + * ```xml + * {value} + * ``` + * + * @param obj Target {@link XML} object to copy properties. + */ + insertAllProperties(obj: XML): void; + /** + * Clear properties. + * + * Remove all properties. It's same with calling ```getPropertyMap().clear()```. + * + * ```xml + * {value} + * ``` + */ + clearProperties(): void; + /** + * @hidden + */ + private _Compute_min_index(...args); + /** + * @hidden + */ + private _Decode_value(str); + /** + * @hidden + */ + private _Encode_value(str); + /** + * @hidden + */ + private _Decode_property(str); + /** + * @hidden + */ + private _Encode_property(str); + /** + * {@link XML} object to xml string. + * + * Returns a string representation of the {@link XML} object. + * + * @param tab Number of tabs to spacing. + * @return The string representation of the {@link XML} object. + */ + toString(tab?: number): string; + } +} +declare namespace samchon.library { + /** + * List of {@link XML} objects with same tag. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/XMLList.html + * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-XML + * @author Jeongho Nam + */ + class XMLList extends std.Deque { + /** + * Get tag. + */ + getTag(): string; + /** + * {@link XMLList XML objects} to string. + * + * Returns a string representation of the {@link XMLList XML objects}. + * + * @param tab Number of tabs to spacing. + * @return The string representation of the {@link XMLList XML objects}. + */ + toString(level?: number): string; + } +} +declare namespace samchon.protocol { + /** + * An interface of entity. + * + * Entity is a class for standardization of expression method using on network I/O by XML. If + * Invoke is a standard message protocol of Samchon Framework which must be kept, Entity is a + * recommended semi-protocol of message for expressing a data class. Following the semi-protocol + * Entity is not imposed but encouraged. + * + * As we could get advantages from standardization of message for network I/O with Invoke, + * we can get additional advantage from standardizing expression method of data class with Entity. + * We do not need to know a part of network communication. Thus, with the Entity, we can only + * concentrate on entity's own logics and relationships between another entities. Entity does not + * need to how network communications are being done. + * + * I say repeatedly. Expression method of Entity is recommended, but not imposed. It's a semi + * protocol for network I/O but not a essential protocol must be kept. The expression method of + * Entity, using on network I/O, is expressed by XML string. + * + * If your own network system has a critical performance issue on communication data class, + * it would be better to using binary communication (with ByteArray). + * Don't worry about the problem! Invoke also provides methods for binary data (ByteArray). + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) + * + * @author Jeongho Nam + */ + interface IEntity { + /** + * Construct data of the Entity from a XML object. + * + * Overrides the construct() method and fetch data of member variables from the XML. + * + * By recommended guidance, data representing member variables are contained in properties + * of the put XML object. + * + * @param xml An xml used to contruct data of entity. + */ + 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 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; + /** + * Get a XML object represents the Entity. + * + * A member variable (not object, but atomic value like number, string or date) is categorized + * as a property within the framework of entity side. Thus, when overriding a toXML() method and + * archiving member variables to an XML object to return, puts each variable to be a property + * belongs to only a XML object. + * + * Don't archive the member variable of atomic value to XML::value causing enormouse creation + * of XML objects to number of member variables. An Entity must be represented by only a XML + * instance (tag). + * + *

    Standard Usage.

    + * + * + * + * + * + * + * + *

    Non-standard usage abusing value.

    + * + * + * jhnam88 + * Jeongho Nam + * 1988-03-11 + * + * + * master + * Administartor + * 2011-07-28 + * + * + * + * @return An XML object representing the Entity. + */ + 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. + * + * Entity is a class for standardization of expression method using on network I/O by XML. If + * Invoke is a standard message protocol of Samchon Framework which must be kept, Entity is a + * recommended semi-protocol of message for expressing a data class. Following the semi-protocol + * Entity is not imposed but encouraged. + * + * As we could get advantages from standardization of message for network I/O with Invoke, + * we can get additional advantage from standardizing expression method of data class with Entity. + * We do not need to know a part of network communication. Thus, with the Entity, we can only + * concentrate on entity's own logics and relationships between another entities. Entity does not + * need to how network communications are being done. + * + * I say repeatedly. Expression method of Entity is recommended, but not imposed. It's a semi + * protocol for network I/O but not a essential protocol must be kept. The expression method of + * Entity, using on network I/O, is expressed by XML string. + * + * If your own network system has a critical performance issue on communication data class, + * it would be better to using binary communication (with ByteArray). + * Don't worry about the problem! Invoke also provides methods for binary data (ByteArray). + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) + * + * @author Jeongho Nam + */ + abstract class Entity implements IEntity { + /** + * Default Constructor. + */ + constructor(); + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + interface IEntityCollection extends IEntityGroup, collections.ICollection { + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityArrayCollection extends collections.ArrayCollection implements IEntityCollection { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityListCollection extends collections.ListCollection implements IEntityCollection { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityDequeCollection extends collections.DequeCollection implements IEntityCollection { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +/** + * A template for External Systems Manager. + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ +declare namespace samchon.templates.external { + /** + * An array and manager of {@link ExternalSystem external system drivers}. + * + * The {@link ExternalSystemArray} is an abstract class containing and managing external system drivers, + * {@link ExternalSystem} objects. Within framewokr of network, {@link ExternalSystemArray} represents your system + * and children {@link ExternalSystem} objects represent remote, external systems connected with your system. + * With this {@link ExternalSystemArray}, you can manage multiple external systems as a group. + * + * You can specify this {@link ExternalSystemArray} class to be *a server accepting external clients* or + * *a client connecting to external servers*. Even both of them is also possible. + * + * - {@link ExternalClientArray}: A server accepting {@link ExternalSystem external clients}. + * - {@link ExternalServerArray}: A client connecting to {@link ExternalServer external servers}. + * - {@link ExternalServerClientArray}: Both of them. Accepts {@link ExternalSystem external clients} and connects to + * {@link ExternalServer external servers} 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*.
    • + *
    + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + abstract class ExternalSystemArray extends protocol.EntityDequeCollection implements protocol.IProtocol { + /** + * Default Constructor. + */ + constructor(); + /** + * @hidden + */ + private _Handle_system_erase(event); + /** + * Test whether the role exists. + * + * @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: protocol.Invoke): void; + /** + * Handle an {@Invoke} message have received. + * + * @param invoke An {@link Invoke} message have received. + */ + abstract replyData(invoke: protocol.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; + } +} +/** + * A template for Parallel Processing System. + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ +declare namespace samchon.templates.parallel { + /** + * Master of Parallel Processing System. + * + * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system + * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your + * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to **slave** systems and the + * children {@link ParallelSystem} objects represent the remote **slave** systems, who is being requested the + * *parallel processes*. + * + * You can specify this {@link ParallelSystemArray} class to be *a server accepting parallel clients* or + * *a client connecting to parallel servers*. Even both of them is possible. Extends one of them below and overrides + * abstract factory method(s) creating the child {@link ParallelSystem} object. + * + * - {@link ParallelClientArray}: A server accepting {@link ParallelSystem parallel clients}. + * - {@link ParallelServerArray}: A client connecting to {@link ParallelServer parallel servers}. + * - {@link ParallelServerClientArray}: Both of them. Accepts {@link ParallelSystem parallel clients} and connects to + * {@link ParallelServer parallel servers} at the same time. + * + * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. + * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s + * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices + * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. + * + * + * + * + * + * #### Proxy Pattern + * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take + * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the + * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it + * may better to utilizing the *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*.
    • + *
    + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ + abstract class ParallelSystemArray extends external.ExternalSystemArray { + /** + * @hidden + */ + private history_sequence_; + /** + * Default Constructor. + */ + constructor(); + /** + * Send an {@link Invoke} message with segment size. + * + * Sends an {@link Invoke} message requesting a **parallel process** with its *segment size*. The {@link Invoke} + * message will be delivered to children {@link ParallelSystem} objects with the *piece size*, which is divided + * from the *segment size*, basis on their {@link ParallelSystem.getPerformance performance indices}. + * + * - If segment size is 100, + * - The segment will be allocated such below: + * + * Name | Performance index | Number of pieces to be allocated | Formula + * --------|-------------------|----------------------------------|-------------- + * Snail | 1 | 10 | 100 / 10 * 1 + * Cheetah | 4 | 40 | 100 / 10 * 4 + * Rabbit | 3 | 30 | 100 / 10 * 3 + * Turtle | 2 | 20 | 100 / 10 * 2 + * + * When the **parallel process** has completed, then this {@link ParallelSystemArraY} will estimate + * {@link ParallelSystem.getPerformance performance indices} of {@link ParallelSystem} objects basis on their + * execution time. + * + * @param invoke An {@link Invoke} message requesting parallel process. + * @param size Number of pieces to segment. + * + * @return Number of {@link ParallelSystem slave systems} participating in the *Parallel Process*. + * + * @see {@link sendPieceData}, {@link ParallelSystem.getPerformacen} + */ + sendSegmentData(invoke: protocol.Invoke, size: number): number; + /** + * Send an {@link Invoke} message with range of pieces. + * + * Sends an {@link Invoke} message requesting a **parallel process** with its *range of pieces [first, last)*. + * The {@link Invoke} will be delivered to children {@link ParallelSystem} objects with the newly computed + * *range of sub-pieces*, which is divided from the *range of pieces (first to last)*, basis on their + * {@link ParallelSystem.getPerformance performance indices}. + * + * - If indices of pieces are 0 to 50, + * - The sub-pieces will be allocated such below: + * + * Name | Performance index | Range of sub-pieces to be allocated | Formula + * --------|-------------------|-------------------------------------|------------------------ + * Snail | 1 | ( 0, 5] | (50 - 0) / 10 * 1 + * Cheetah | 4 | ( 5, 25] | (50 - 0) / 10 * 4 + 5 + * Rabbit | 3 | (25, 40] | (50 - 0) / 10 * 3 + 25 + * Turtle | 2 | (40, 50] | (50 - 0) / 10 * 2 + 40 + * + * When the **parallel process** has completed, then this {@link ParallelSystemArraY} will estimate + * {@link ParallelSystem.getPerformance performance indices} of {@link ParallelSystem} objects basis on their + * execution time. + * + * @param invoke An {@link Invoke} message requesting parallel process. + * @param first Initial piece's index in a section. + * @param last Final piece's index in a section. The range 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*. + * + * @return Number of {@link ParallelSystem slave systems} participating in the *Parallel Process*. + * + * @see {@link sendSegmentData}, {@link ParallelSystem.getPerformacen} + */ + sendPieceData(invoke: protocol.Invoke, first: number, last: number): number; + /** + * @hidden + */ + protected _Complete_history(history: slave.InvokeHistory): boolean; + /** + * @hidden + */ + protected _Normalize_performance(): void; + } +} +/** + * A template for Distributed Processing System. + * + * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ +declare namespace samchon.templates.distributed { + /** + * Master of Distributed Processing System. + * + * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system + * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents + * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** + * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being + * requested the *distributed processes*. + * + * You can specify this {@link DistributedSystemArray} class to be *a server accepting distributed clients* or + * *a client connecting to distributed servers*. Even both of them is possible. Extends one of them below and overrides + * abstract factory method(s) creating the child {@link DistributedSystem} object. + * + * - {@link DistributedClientArray}: A server accepting {@link DistributedSystem distributed clients}. + * - {@link DistributedServerArray}: A client connecting to {@link DistributedServer distributed servers}. + * - {@link DistributedServerClientArray}: Both of them. Accepts {@link DistributedSystem distributed clients} and + * connects to {@link DistributedServer distributed servers} at the same time. + * + * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a + * **distributed process** through the {@link DistributedProcess} object. You can access the + * {@link DistributedProcess} object(s) with those methods: + * + * - {@link hasProcess} + * - {@link getProcess} + * - {@link insertProcess} + * - {@link eraseProcess} + * - {@link getProcessMap} + * + * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the + * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed + * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When + * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and + * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. + * + * + * + * + * + * #### Parallel Process + * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request + * a **parallel process**, too. + * + * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. + * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s + * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will + * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. + * + * #### Proxy Pattern + * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take + * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the + * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it + * may better to utilizing the *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*.
    • + *
    + * + * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ + abstract class DistributedSystemArray extends parallel.ParallelSystemArray { + /** + * @hidden + */ + private process_map_; + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * Factory method creating a child {@link DistributedProcess process} object. + * + * @param xml {@link XML} represents the {@link DistributedProcess child} object. + * @return A new {@link DistributedProcess} object. + */ + protected abstract createProcess(xml: library.XML): DistributedProcess; + /** + * Get process map. + * + * Gets an {@link HashMap} containing {@link DistributedProcess} objects with their *key*. + * + * @return An {@link HasmMap> containing pairs of string and {@link DistributedProcess} object. + */ + getProcessMap(): std.HashMap; + /** + * Test whether the process exists. + * + * @param name Name, identifier of target {@link DistributedProcess process}. + * + * @return Whether the process has or not. + */ + hasProcess(name: string): boolean; + /** + * Get a process. + * + * @param name Name, identifier of target {@link DistributedProcess process}. + * + * @return The specified process. + */ + getProcess(name: string): DistributedProcess; + /** + * Insert a process. + * + * @param process A process to be inserted. + * @return Success flag. + */ + insertProcess(process: DistributedProcess): boolean; + /** + * Erase a process. + * + * @param name Name, identifier of target {@link DistributedProcess process}. + */ + eraseProcess(name: string): boolean; + /** + * @hidden + */ + protected _Complete_history(history: slave.InvokeHistory): boolean; + /** + * @hidden + */ + private estimate_process_resource(history); + /** + * @hidden + */ + private estimate_system_performance(history); + /** + * @hidden + */ + protected _Normalize_performance(): void; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.templates.distributed { + /** + * Mediator of Distributed Processing System. + * + * The {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a slave to its master + * system at the same time. This {@link DistributedSystemArrayMediator} be a master system, containing and managing + * {@link DistributedSystem} objects, which represent distributed slave systems, by extending + * {@link DistributedSystemArray} class. Also, be a slave system through {@link getMediator mediator} object, which is + * derived from the {@link SlaveSystem} class. + * + * As a master, you can specify this {@link DistributedSystemArrayMediator} class to be a master server accepting + * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one + * of them below and overrides abstract factory method(s) creating the child {@link DistributedSystem} object. + * + * - {@link DistributedClientArrayMediator}: A server accepting {@link DistributedSystem distributed clients}. + * - {@link DistributedServerArrayMediator}: A client connecting to {@link DistributedServer distributed servers}. + * - {@link DistributedServerClientArrayMediator}: Both of them. Accepts {@link DistributedSystem distributed clients} and + * connects to {@link DistributedServer distributed servers} at the same time. + * + * As a slave, you can specify this {@link DistributedSystemArrayMediator} to be a client slave connecting to master + * server or a server slave accepting master client by overriding the {@link createMediator} method. + * Overrides the {@link createMediator createMediator()} method and return one of them: + * + * - A client slave connecting to master server: + * - {@link MediatorClient} + * - {@link MediatorWebClient} + * - {@link MediatorSharedWorkerClient} + * - A server slave accepting master client: + * - {@link MediatorServer} + * - {@link MediatorWebServer} + * - {@link MediatorDedicatedWorkerServer} + * - {@link MediatorSharedWorkerServer} + * + * #### [Inherited] {@link DistributedSystemArray} + * @copydoc DistributedSystemArray + */ + abstract class DistributedSystemArrayMediator extends DistributedSystemArray { + /** + * @hidden + */ + private mediator_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating a {@link MediatorSystem} object. + * + * The {@link createMediator createMediator()} is an abstract method creating the {@link MediatorSystem} object. + * + * You know what? this {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a + * slave to its master system at the same time. The {@link MediatorSystem} object makes it possible; be a slave + * system. This {@link createMediator} determines specific type of the {@link MediatorSystem}. + * + * Overrides the {@link createMediator createMediator()} method to create and return one of them following which + * protocol and which type of remote connection (server or client) will be used: + * + * - A client slave connecting to master server: + * - {@link MediatorClient} + * - {@link MediatorWebClient} + * - {@link MediatorSharedWorkerClient} + * - A server slave accepting master client: + * - {@link MediatorServer} + * - {@link MediatorWebServer} + * - {@link MediatorDedicatedWorkerServer} + * - {@link MediatorSharedWorkerServer} + * + * @return A newly created {@link MediatorSystem} object. + */ + protected abstract createMediator(): parallel.MediatorSystem; + /** + * Start mediator. + * + * If the {@link getMediator mediator} is a type of server, then opens the server accepting master client. + * Otherwise, the {@link getMediator mediator} is a type of client, then connects the master server. + */ + protected startMediator(): void; + /** + * Get {@link MediatorSystem} object. + * + * When you need to send an {@link Invoke} message to the master system of this + * {@link DistributedSystemArrayMediator}, then send to the {@link MediatorSystem} through this + * {@link getMediator}. + * + * ```typescript + * this.getMediator().sendData(...); + * ``` + * + * @return The {@link MediatorSystem} object. + */ + getMediator(): parallel.MediatorSystem; + /** + * @hidden + */ + protected _Complete_history(history: slave.InvokeHistory): boolean; + } +} +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; + type IMessage = any; + type ICookie = any; + type client = any; + } +} +declare namespace samchon.protocol { + /** + * @hidden + */ + abstract class _CommunicatorBase implements ICommunicator { + /** + * @hidden + */ + protected listener_: IProtocol; + /** + * @inheritdoc + */ + onClose: Function; + /** + * @hidden + */ + protected connected_: boolean; + /** + * @hidden + */ + private binary_invoke_; + /** + * @hidden + */ + private binary_parameters_; + /** + * @hidden + */ + private unhandled_invokes_; + /** + * 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; + /** + * @hidden + */ + protected _Is_binary_invoke(): boolean; + /** + * @inheritdoc + */ + abstract sendData(invoke: Invoke): void; + /** + * @inheritdoc + */ + replyData(invoke: Invoke): void; + /** + * @hidden + */ + protected _Handle_string(str: string): void; + /** + * @hidden + */ + protected _Handle_binary(binary: Uint8Array): void; + } +} +declare namespace samchon.protocol { + /** + * A communicator following Samchon Framework's own protocol. + * + * {@link Communicator} is an abstract class following Samchon Framework's own protocol. This {@link Communicator} + * class is specified to {@link ServerConnector} and {@link ClientDriver} whether the remote system is a server (that + * my system is connecting to) or a client (a client conneting to to my server). + * + * Note that, if one of this or remote system is web-browser based, then you don't have to use this + * {@link Communicator} class who follows Samchon Framework's own protocol. Web-browser supports only Web-socket + * protocol. Thus in that case, you have to use {@link WebCommunicator} instead. + * + * #### [Inherited] {@link ICommunicator} + * @copydoc ICommunicator + */ + abstract 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 { + /** + * Communicator with remote client. + * + * {@link ClientDriver} is a class taking full charge of network communication with remote client who follows Samchon + * Framework's own protocol. This {@link ClientDriver} object is always created by {@link Server} class. When you got + * this {@link ClientDriver} object from the {@link Server.addClient Server.addClient()}, then specify + * {@link IProtocol listener} with the {@link ClientDriver.listen ClientDriver.listen()} method. + * + * #### [Inherited] {@link IClientDriver} + * @copydoc IClientDriver + */ + class ClientDriver extends Communicator implements IClientDriver { + /** + * Construct from a socket. + */ + constructor(socket: socket.socket); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + } +} +declare namespace samchon.protocol { + /** + * A communicator for shared worker. + * + * {@link DedicatedWorkerCommunicator} is an abstract class for communication between DedicatedWorker and Web-browser. + * This {@link DedicatedWorkerCommunicator} is specified to {@link DedicatedWorkerServerConnector} and + * {@link DedicatedWorkerClientDriver} whether the remote system is a server (that my system is connecting to) or a + * client (a client conneting to to my server). + * + * #### Why DedicatedWorker be a server? + * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the + * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the + * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network + * communication? Furthermore, there's not any difference between the worker communication and network communication. + * It's the reason why Samchon Framework considers the **Worker** as a network node. + * + * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a + * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the + * server and clients with this {@link DedicatedWorkerCommunicator}. + * + * #### [Inherited] {@link ICommunicator} + * @copydoc ICommunicator + */ + abstract class DedicatedWorkerCommunicator extends _CommunicatorBase { + /** + * @hidden + */ + protected _Handle_message(event: MessageEvent): void; + } +} +declare namespace samchon.protocol { + /** + * Communicator with master web-browser. + * + * {@link DedicatedWorkerClientDriver} is a class taking full charge of network communication with web browsers. This + * {@link DedicatedWorkerClientDriver} object is always created by {@link DedicatedWorkerServer} class. When you got + * this {@link DedicatedWorkerClientDriver} object from + * {@link DedicatedWorkerServer.addClient DedicatedWorkerServer.addClient()}, then specify {@link IProtocol listener} + * with the {@link DedicatedWorkerClientDriver.listen DedicatedWorkerClientDriver.listen()} method. + * + * #### Why DedicatedWorker be a server? + * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the + * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the + * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network + * communication? Furthermore, there's not any difference between the worker communication and network communication. + * It's the reason why Samchon Framework considers the **Worker** as a network node. + * + * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a + * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the + * server and clients with this {@link DedicatedWorkerCommunicator}. + * + * #### [Inherited] {@link IClientDriver} + * @copydoc IClientDriver + */ + class DedicatedWorkerClientDriver extends DedicatedWorkerCommunicator implements IClientDriver { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + } +} +declare namespace samchon.protocol { + /** + * A communicator for shared worker. + * + * {@link SharedWorkerCommunicator} is an abstract class for communication between SharedWorker and Web-browser. This + * {@link SharedWorkerCommunicator} is specified to {@link SharedWorkerServerConnector} and + * {@link SharedWorkerClientDriver} whether the remote system is a server (that my system is connecting to) or a client + * (a client conneting to to my server). + * + * Note that, SharedWorker is a conception only existed in web-browser. This {@link SharedWorkerCommunicator} is not + * supported in NodeJS. Only web-browser environment can utilize this {@link SharedWorkerCommunicator}. + * + * #### Why SharedWorker be a server? + * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser + * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship + * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as + * clients. + * + * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a + * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the + * server and clients with this {@link SharedWorkerCommunicator}. + * + * #### [Inherited] {@link ICommunicator} + * @copydoc ICommunicator + */ + abstract class SharedWorkerCommunicator extends _CommunicatorBase { + /** + * @hidden + */ + protected port_: MessagePort; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + /** + * @hidden + */ + protected _Handle_message(event: MessageEvent): void; + } +} +declare namespace samchon.protocol { + /** + * Communicator with remote web-browser. + * + * {@link SharedWorkerClientDriver} is a class taking full charge of network communication with web browsers. This + * {@link SharedWorkerClientDriver} object is always created by {@link SharedWorkerServer} class. When you got this + * {@link SharedWorkerClientDriver} object from {@link SharedWorkerServer.addClient SharedWorkerServer.addClient()}, + * then specify {@link IProtocol listener} with the + * {@link SharedWorkerClientDriver.listen SharedWorkerClientDriver.listen()} method. + * + * #### Why SharedWorker be a server? + * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser + * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship + * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as + * clients. + * + * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a + * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the + * server and clients with this {@link SharedWorkerCommunicator}. + * + * #### [Inherited] {@link IClientDriver} + * @copydoc IClientDriver + */ + class SharedWorkerClientDriver extends SharedWorkerCommunicator implements IClientDriver { + /** + * @hidden + */ + private listening_; + /** + * Construct from a MessagePort object. + */ + constructor(port: MessagePort); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + } +} +declare namespace samchon.protocol { + /** + * A communicator following Web-socket protocol. + * + * {@link WebCommunicator} is an abstract class following Web-socket protocol. This {@link WebCommunicator} class is + * specified to {@link WebServerConnector} and {@link WebClientDriver} whether the remote system is a server (that my + * system is connecting to) or a client (a client conneting to to my server). + * + * Note that, one of this or remote system is web-browser based, then there's not any alternative choice. Web browser + * supports only Web-socket protocol. In that case, you've use this {@link WebCommunicator} class. + * + * #### [Inherited] {@link ICommunicator} + * @copydoc ICommunicator + */ + abstract class WebCommunicator extends _CommunicatorBase { + /** + * @hidden + */ + protected connection_: websocket.connection; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + /** + * @hidden + */ + protected _Handle_message(message: websocket.IMessage): void; + /** + * @hidden + */ + protected _Handle_close(): void; + } +} +declare namespace samchon.protocol { + /** + * Communicator with remote web-client. + * + * {@link WebClientDriver} is a class taking full charge of network communication with remote client who follows + * Web-socket protocol. This {@link WebClientDriver} object is always created by {@link WebServer} class. When you + * got this {@link WebClientDriver} object from the {@link WebServer.addClient WebServer.addClient()}, then specify + * {@link IProtocol listener} with the {@link WebClientDriver.listen WebClientDriver.listen()} method. + * + * Unlike other protocol, Web-socket protocol's clients notify two parameters on their connection; + * {@link getSessionID session-id} and {@link getPath path}. The {@link getSessionID session-id} can be used to + * identify *user* of each client, and the {@link getPath path} can be used which type of *service* that client wants. + * In {@link service} module, you can see the best utilization case of them. + * - {@link service.User}: utlization of the {@link getSessionID session-id}. + * - {@link service.Service}: utilization of the {@link getPath path}. + * + * #### [Inherited] {@link IClientDriver} + * @copydoc IClientDriver + */ + class WebClientDriver extends WebCommunicator implements IClientDriver { + /** + * @hidden + */ + private path_; + /** + * @hidden + */ + private session_id_; + /** + * @hidden + */ + 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 { + /** + * An interface for communicator with remote client. + * + * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has + * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. + * + * The {@link IClientDriver} object is created and delivered from {@link IServer} and + * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being + * created by the matched {@link IServer} object. + * + * Protocol | Derived Type | Created By + * ------------------------|-------------------------------------|---------------------------- + * Samchon Framework's own | {@link ClientDriver} | {@link Server} + * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} + * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} + * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} + * + * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then + * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes + * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object + * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. + * Below code is an example specifying and managing the {@link IProtocol listener} objects. + * + * - https://github.com/samchon/framework-examples/blob/master/calculator/calculator-server.ts + * + * + * + * + * + * @see {@link IServer}, {@link IProtocol} + * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-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} object. + */ + listen(listener: IProtocol): void; + } +} +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 + * remote system, without reference to whether the remote system is a server or a client. Type of the + * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system + * is a server (that I've to connect) or a client (a client connected to my server). + * + * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class + * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s + * {@link IProtocol.replyData IProtocol.replyData()} method. + * + * + * + * + * + * @see {@link IClientDriver}, {@link IServerConnector}, {@link IProtocol} + * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) + * @author Jeongho Nam + */ + interface ICommunicator extends IProtocol { + /** + * Callback function for connection closed. + */ + onClose: Function; + /** + * Close connection. + */ + close(): void; + /** + * Test connection. + * + * Test whether this {@link ICommunicator communicator} object is connected with the remote system. If the + * connection is alive, then returns ```true```. Otherwise, the connection is not alive or this + * {@link ICommunicator communicator has not connected with the remote system yet, then returns ```false```. + * + * @return true if connected, otherwise false. + */ + isConnected(): boolean; + /** + * Send message. + * + * Send {@link Invoke} message to remote system. + * + * @param invoke An {@link Invoke} message to send. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle replied message. + * + * Handles replied {@link Invoke} message recived from remove system. The {@link Invoke} message will be shifted + * to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} by this method. + * + * @param invoke An {@link Invoke} message received from remote system. + */ + replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.protocol { + /** + * An interface for server connector. + * + * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to + * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full + * charge of network communication with the remote server. + * + * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the + * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will + * be converted to an {@link Invoke} object and the {@link Invoke} object will be shifted to the + * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. Below code is an example + * connecting to remote server and interacting with it. + * + * - https://github.com/samchon/framework-examples/blob/master/calculator/calculator-application.ts + * + * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of + * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. + * + * Protocol | Derived Type | Connect to + * ------------------------|----------------------------------------|------------------------------- + * Samchon Framework's own | {@link ServerConnector} | {@link Server} + * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} + * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} + * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) + * + * @see {@link IServer}, {@link IProtocol} + * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) + * @author Jeongho Nam + */ + interface IServerConnector extends ICommunicator { + /** + * Callback function for connection completed. + * + * When you call {@link connect connect()} and the connection has completed, then this call back function + * {@link onConnect} will be called. Note that, if the listener of this {@link onConnect} is a member method of + * some class, then you've use the ```bind```. + */ + 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 { + /** + * A server connector for DedicatedWorker. + * + * {@link DedicatedWorkerServerConnector} is a class connecting to SharedWorker and taking full charge of network + * communication with the SharedWorker. Create an {@link DedicatedWorkerServer} instance from the + * {@IProtocol listener} and call the {@link connect connect()} method. + * + * #### Why DedicatedWorker be a server? + * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the + * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the + * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network + * communication? Furthermore, there's not any difference between the worker communication and network communication. + * It's the reason why Samchon Framework considers the **Worker** as a network node. + * + * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a + * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the + * server and clients with this {@link DedicatedWorkerCommunicator}. + * + * #### [Inherited] {@link IServerConnector} + * @copydoc IServerConnector + */ + class DedicatedWorkerServerConnector extends DedicatedWorkerCommunicator implements IServerConnector { + /** + * @hidden + */ + private worker_; + /** + * @inheritdoc + */ + onConnect: Function; + /** + * Construct from *listener*. + * + * @param listener A listener object to listen replied message from newly connected client in + * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. + */ + constructor(listener: IProtocol); + /** + * @inheritdoc + */ + connect(jsFile: string): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + } +} +declare namespace samchon.protocol { + /** + * Server connnector. + * + * {@link ServerConnector} is a class connecting to remote server who follows Samchon Framework's own protocol and + * taking full charge of network communication with the remote server. Create a {@link ServerConnector} instance from + * the {@IProtocol listener} and call the {@link connect connect()} method. + * + * #### [Inherited] {@link IServerConnector} + * @copydoc IServerConnector + */ + class ServerConnector extends Communicator implements IServerConnector { + /** + * @inheritdoc + */ + onConnect: Function; + /** + * Construct from *listener*. + * + * @param listener A listener object to listen replied message from newly connected client in + * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. + */ + constructor(listener: IProtocol); + /** + * @inheritdoc + */ + connect(ip: string, port: number): void; + /** + * @hidden + */ + private _Handle_connect(...arg); + /** + * @hidden + */ + private _Send_dummy_packet_repeatedly(); + } +} +declare namespace samchon.protocol { + /** + * A server connector for SharedWorker. + * + * {@link SharedWorkerServerConnector} is a class connecting to SharedWorker and taking full charge of network + * communication with the SharedWorker. Create an {@link SharedWorkerServerConnector} instance from the + * {@IProtocol listener} and call the {@link connect connect()} method. + * + * #### Why SharedWorker be a server? + * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser + * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship + * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as + * clients. + * + * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a + * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the + * server and clients with this {@link SharedWorkerCommunicator}. + * + * #### [Inherited] {@link IServerConnector} + * @copydoc IServerConnector + */ + class SharedWorkerServerConnector extends SharedWorkerCommunicator implements IServerConnector { + /** + * @inheritdoc + */ + onConnect: Function; + /** + * Construct from *listener*. + * + * @param listener A listener object to listen replied message from newly connected client in + * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. + */ + constructor(listener: IProtocol); + /** + * Connect to a SharedWorker. + * + * Connects to a server with specified *jstFile* path. If a SharedWorker instance of the *jsFile* is not + * constructed yet, then the SharedWorker will be newly constructed. Otherwise the SharedWorker already exists, + * then connect to the SharedWorker. After those processes, 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 jsFile Path of JavaScript file to execute who defines SharedWorker. + */ + connect(jsFile: string): void; + } +} +declare namespace samchon.protocol { + /** + * A server connector for web-socket protocol. + * + * {@link WebServerConnector} is a class connecting to remote server who follows Web-socket protocol and taking full + * charge of network communication with the remote server. Create an {@link WebServerConnector} instance from the + * {@IProtocol listener} and call the {@link connect connect()} method. + * + * #### [Inherited] {@link IServerConnector} + * @copydoc IServerConnector + */ + class WebServerConnector extends WebCommunicator implements IServerConnector { + /** + * @hidden + */ + private browser_socket_; + /** + * @hidden + */ + private node_client_; + /** + * @inheritdoc + */ + onConnect: Function; + /** + * Construct from *listener*. + * + * @param listener A listener object to listen replied message from newly connected client in + * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. + */ + constructor(listener: IProtocol); + /** + * Connect to a web server. + * + * Connects to a server with specified *host* address, *port* number and *path*. 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. + * @param path Path of service which you want. + */ + connect(ip: string, port: number, path?: string): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + /** + * @hidden + */ + private _Handle_browser_connect(event); + /** + * @hidden + */ + private _Handle_browser_message(event); + /** + * @hidden + */ + private _Handle_node_connect(connection); + } +} +declare namespace samchon.protocol { + /** + * A container of entity, and it's a type of entity, too. + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) + * + * @handbook [Protocol - Standard Message](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Standard_Message) + * @author Jeongho Nam + */ + interface IEntityGroup extends IEntity, std.base.Container { + /** + * Construct data of the Entity from an XML object. + * + * Constructs the EntityArray's own member variables only from the input XML object. + * + * Do not consider about constructing children Entity objects' data in EntityArray::construct(). + * Those children Entity objects' data will constructed by their own construct() method. Even insertion + * of XML objects representing children are done by abstract method of EntityArray::toXML(). + * + * Constructs only data of EntityArray's own. + */ + 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. + */ + createChild(xml: library.XML): T; + /** + * Get iterator to element. + * + * Searches the container for an element with a identifier equivalent to *key* and returns an + * iterator to it if found, otherwise it returns an iterator to {@link end end()}. + * + * Two keys are considered equivalent if the container's comparison object returns false reflexively + * (i.e., no matter the order in which the elements are passed as arguments). + * + * Another member functions, {@link has has()} and {@link count count()}, can be used to just check + * whether a particular *key* exists. + * + * @param key Key to be searched for + * @return An iterator to the element, if an element with specified *key* is found, or + * {@link end end()} otherwise. + */ + /** + * Whether have the item or not. + * + * Indicates whether a map has an item having the specified identifier. + * + * @param key Key value of the element whose mapped value is accessed. + * + * @return Whether the map has an item having the specified identifier. + */ + has(key: any): boolean; + /** + * Count elements with a specific key. + * + * Searches the container for elements whose key is *key* and returns the number of elements found. + * + * @param key Key value to be searched for. + * + * @return The number of elements in the container with a *key*. + */ + count(key: any): number; + /** + * Get an element + * + * Returns a reference to the mapped value of the element identified with *key*. + * + * @param key Key value of the element whose mapped value is accessed. + * + * @throw exception out of range + * + * @return A reference object of the mapped value (_Ty) + */ + get(key: any): T; + /** + * A tag name of children objects. + */ + CHILD_TAG(): string; + /** + * Get an XML object represents the EntityArray. + * + * Archives the EntityArray's own member variables only to the returned XML object. + * + * Do not consider about archiving children Entity objects' data in EntityArray::toXML(). + * Those children Entity objects will converted to XML object by their own toXML() method. The + * insertion of XML objects representing children are done by abstract method of + * EntityArray::toXML(). + * + * Archives only data of EntityArray's own. + */ + toXML(): library.XML; + } + /** + * @hidden + */ + namespace IEntityGroup { + /** + * @hidden + */ + function construct(entityGroup: IEntityGroup, xml: library.XML, ...prohibited_names: string[]): void; + /** + * @hidden + */ + function toXML(group: 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 + */ + abstract class EntityArray extends std.Vector implements IEntityGroup { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityList extends std.List implements IEntityGroup { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityDeque extends std.Deque implements IEntityGroup { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * Standard message of network I/O. + * + * {@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 + * network I/O. + * + * The greatest advantage is that we can make any type of network system, even how the system + * is enourmously complicated. As network communication message is standardized, we only need to + * concentrate on logical relationships between network systems. We can handle each network system + * 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 componenets + * (IProtocol, IServer and ICommunicator) by implemens or inherits them, like designing + * classes of S/W architecture. + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) + * + * @see {@link IProtocol} + * @author Jeongho Nam + */ + class Invoke extends EntityArray { + /** + * Listener, represent function's name. + */ + private listener; + /** + * Default Constructor. + */ + constructor(); + constructor(listener: string); + /** + * Copy Constructor. + * + * @param invoke + */ + constructor(invoke: Invoke); + /** + * Construct from listener and parametric values. + * + * @param listener + * @param parameters + */ + constructor(listener: string, ...parameters: Array); + /** + * @inheritdoc + */ + createChild(xml: library.XML): InvokeParameter; + /** + * Get listener. + */ + getListener(): string; + /** + * Get arguments for Function.apply(). + * + * @return An array containing values of the contained parameters. + */ + getArguments(): Array; + /** + * Apply to a matched function. + * + * @param obj Target object to find matched function. + * @return Whether succeded to find matched function. + */ + apply(obj: Object): boolean; + /** + * Apply to a function. + * + * @param thisArg Owner of the function. + * @param func Function to call. + */ + apply(thisArg: Object, func: Function): void; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + CHILD_TAG(): string; + } +} +declare namespace samchon.protocol { + /** + * A parameter belongs to an Invoke. + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) + * + * @author Jeongho Nam + */ + class InvokeParameter extends Entity { + /** + * Name of the parameter. + * + * @details Optional property, can be omitted. + */ + protected name: string; + /** + * Type of the parameter. + */ + protected type: string; + /** + * Value of the parameter. + */ + protected value: boolean | number | string | library.XML | Uint8Array; + /** + * Default Constructor. + */ + constructor(); + constructor(val: boolean); + constructor(val: number); + constructor(val: string); + constructor(val: library.XML); + constructor(val: Uint8Array); + /** + * Construct from variable name and number value. + * + * @param name + * @param val + */ + constructor(name: string, val: boolean); + 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: boolean): void; + setValue(value: number): void; + setValue(value: string): void; + setValue(value: library.XML): void; + setValue(value: Uint8Array): void; + /** + * @inheritdoc + */ + key(): any; + /** + * Get name. + */ + getName(): string; + /** + * Get type. + */ + getType(): string; + /** + * Get value. + */ + getValue(): any; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * An interface for {@link Invoke} message chain. + * + * {@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. + * + * Implements {@link IProtocol} if the class sends and handles {@link Invoke} messages. Looking around source codes of + * the *Samchon Framework*, especially *Templates*, you can find out that all the classes and modules handling + * {@link Invoke} messages are always implementing this {@link IProtocol}. + * + * + * + * + * + * @see {@link Invoke} + * @handbook https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iprotocol + * @author Jeongho Nam + */ + interface IProtocol { + /** + * Sending message. + * + * Sends message to related system or shifts the responsibility to chain. + * + * @param invoke Invoke message to send + */ + replyData(invoke: Invoke): void; + /** + * Handling replied message. + * + * Handles replied message or shifts the responsibility to chain. + * + * @param invoke An {@link Invoke} message has received. + */ + sendData(invoke: Invoke): void; + } +} +declare namespace samchon.protocol { + /** + * A DeidcatedWorker server. + * + * The {@link DedicatedWorkerServer} is an abstract class is realized to open a DedicatedWorker server and accept + * web-browser client (master). Extends this {@link DedicatedWorkerServer} class and overrides + * {@link addClient addClient()} method to define what to do with a newly connected + * {@link DedicatedWorkerClientDriver remote client}. + * + * #### Why DedicatedWorker be a server? + * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the + * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the + * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network + * communication? Furthermore, there's not any difference between the worker communication and network communication. + * It's the reason why Samchon Framework considers the **Worker** as a network node. + * + * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a + * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the + * server and clients with this {@link DedicatedWorkerCommunicator}. + * + * #### [Inherited] {@link IServer} + * @copydoc IServer + */ + abstract class DedicatedWorkerServer implements IServer { + /** + * @inheritdoc + */ + abstract addClient(driver: DedicatedWorkerClientDriver): void; + /** + * @inheritdoc + */ + open(): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.protocol { + /** + * A substitute {@link DedicatedWorkerServer}. + * + * The {@link DedicatedWorkerServerBase} is a substitute class who subrogates {@link DedicatedWorkerServer}'s + * responsibility. + * + * #### [Inherited] {@link IServerBase} + * @copydoc IServerBase + */ + class DedicatedWorkerServerBase extends DedicatedWorkerServer implements IServerBase { + /** + * @hidden + */ + private hooker_; + /** + * Construct from a *hooker*. + * + * @param hooker A hooker throwing responsibility of server's role. + */ + constructor(hooker: IServer); + /** + * @inheritdoc + */ + addClient(driver: IClientDriver): void; + } +} +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 below, who implemented the {@link IServer}. + * 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}. + * + * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} + * ------------------------|-------------------------------|-----------------------------------|------------------------------------- + * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} + * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} + * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} + * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} + * + * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who + * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with + * specified port number. + * + * ```typescript + * 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}, {@link IClientDriver} + * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) + * @author Jeongho Nam + */ + interface IServerBase extends IServer { + } +} +declare namespace samchon.protocol { + /** + * A server. + * + * The {@link Server} is an abstract class designed to open a server and accept clients who are following Samchon + * Framework's own protocol. Extends this {@link Server} class and overrides {@link addClient addClient()} method to + * define what to do with newly connected {@link ClientDriver remote clients}. + * + * #### [Inherited] {@link IServer} + * @copydoc Server + */ + abstract class Server implements IServer { + /** + * @hidden + */ + private net_driver_; + /** + * @inheritdoc + */ + abstract addClient(driver: ClientDriver): void; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @hidden + */ + private _Handle_connect(socket); + } +} +declare namespace samchon.protocol { + /** + * A substitute {@link Server}. + * + * The {@link ServerBase} is a substitute class who subrogates {@link Server}'s responsibility. + * + * #### [Inherited] {@link IServerBase} + * @copydoc IServerBase + */ + class ServerBase extends Server implements IServerBase { + /** + * @hidden + */ + private hooker_; + /** + * Construct from a *hooker*. + * + * @param hooker A hooker throwing responsibility of server's role. + */ + constructor(hooker: IServer); + /** + * @inheritdoc + */ + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + * A SharedWorker server. + * + * The {@link SharedWorker} is an abstract class is realized to open a SharedWorker server and accept web-browser + * clients. Extends this {@link SharedWorkerServer} class and overrides {@link addClient addClient()} method to + * define what to do with newly connected {@link SharedWorkerClientDriver remote clients}. + * + * #### Why SharedWorker be a server? + * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser + * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship + * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as + * clients. + * + * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a + * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the + * server and clients with this {@link SharedWorkerCommunicator}. + * + * #### [Inherited] {@link IServer} + * @copydoc IServer + */ + abstract class SharedWorkerServer implements IServer { + /** + * @inheritdoc + */ + abstract addClient(driver: SharedWorkerClientDriver): void; + /** + * @inheritdoc + */ + open(): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @hidden + */ + private _Handle_connect(event); + } +} +declare namespace samchon.protocol { + /** + * A substitute {@link SharedWorkerServer}. + * + * The {@link SharedWorkerServerBase} is a substitute class who subrogates {@link SharedWorkerServer}'s + * responsibility. + * + * #### [Inherited] {@link IServerBase} + * @copydoc IServerBase + */ + class SharedWorkerServerBase extends SharedWorkerServer implements IServerBase { + /** + * @hidden + */ + private hooker_; + /** + * Construct from a *hooker*. + * + * @param hooker A hooker throwing responsibility of server's role. + */ + constructor(hooker: IServer); + /** + * @inheritdoc + */ + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + * A web server. + * + * The {@link WebServer} is an abstract class designed to open a server and accept clients who are following + * web-socket protocol. Extends this {@link WebServer} class and overrides {@link addClient addClient()} method to + * define what to do with newly connected {@link WebClientDriver remote clients}. + * + * #### [Inherited] {@link IServer} + * @copydoc IServer + */ + abstract class WebServer implements IServer { + /** + * @hidden + */ + private http_server_; + /** + * @hidden + */ + private sequence_; + /** + * @hidden + */ + private my_port_; + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + abstract addClient(driver: WebClientDriver): void; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @hidden + */ + private _Handle_request(request); + /** + * @hidden + */ + private _Fetch_session_id(cookies); + /** + * @hidden + */ + private _Issue_session_id(); + } +} +declare namespace samchon.protocol { + /** + * A substitute {@link WebServer}. + * + * The {@link WebServerBase} is a substitute class who subrogates {@link WebServer}'s responsibility. + * + * #### [Inherited] {@link IServerBase} + * @copydoc IServerBase + */ + class WebServerBase extends WebServer implements IServerBase { + /** + * @hidden + */ + private hooker_; + /** + * Construct from a *hooker*. + * + * @param hooker A hooker throwing responsibility of server's role. + */ + constructor(hooker: IServer); + /** + * @inheritdoc + */ + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + * An interface for a server. + * + * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and + * {@link IClientDriver accepting clients}. + * + * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, + * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} + * object. Then at last, call {@link open open()} method with specified port number. + * + * Protocol | Derived Type | Related {@link IClientDriver} + * ------------------------|-------------------------------|------------------------------------- + * Samchon Framework's own | {@link Server} | {@link ClientDriver} + * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} + * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} + * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} + * + * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. + * - https://github.com/samchon/framework-examples/blob/master/calculator/calculator-server.ts + * - https://github.com/samchon/framework-examples/blob/master/chat-server/server.ts + * - {@link service.Server} + * - {@link external.ExternalClientArray} + * - {@link slave.SlaveServer} + * + * If you're embarrased because your class already extended another one, then use {@link IServerBase}. + * + * + * + * + * + * @see {@link IClientDriver}, {@link IServerBase} + * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) + * @author Jeongho Nam + */ + interface IServer { + /** + * Open server. + * + * @param port Port number to open. + */ + open(port: number): void; + /** + * Close server. + * + * Close opened server. All remote clients, have connected with this server, are also closed and their call back + * functions, for closed connection, {@link IClientDriver.onClose} are also called. + */ + close(): void; + /** + * Add a newly connected remote client. + * + * The {@link addClient addClient()} is an abstract method being called when a remote client is newly connected + * with {@link IClientDriver} object who communicates with the remote system. Overrides this method and defines + * what to do with the *driver*, a newly connected remote client. + * + * Below methods and example codes may be good for comprehending how to utilize this {@link addClient} method. + * + * - https://github.com/samchon/framework-examples/blob/master/calculator/calculator-server.ts + * - https://github.com/samchon/framework-examples/blob/master/chat-server/server.ts + * - {@link service.Server.addClient} + * - {@link external.ExternalClientArray.addClient} + * - {@link slave.SlaveServer.addClient} + * + * @param driver A {@link ICommunicator communicator} with (newly connected) remote client. + */ + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Master of Distributed Processing System, a server accepting slave clients. + * + * The {@link DistributedClientArray} is an abstract class, derived from the {@link DistributedSystemArray} class, + * opening a server accepting {@link DistributedSystem distributed clients}. + * + * Extends this {@link DistributedClientArray}, overrides {@link createServerBase createServerBase()} to determine + * which protocol to follow and {@link createExternalClient createExternalClient()} creating child + * {@link DistributedSystem} object. After the extending and overridings, open this server using the + * {@link open open()} method. + * + * #### [Inherited] {@link DistributedSystemArray} + * @copydoc DistributedSystemArray + */ + abstract class DistributedClientArray extends DistributedSystemArray implements external.IExternalClientArray { + /** + * @hidden + */ + 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. + * + * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, + * then this {@link ParallelClientArray} creates a child {@link ParallelSystem parallel client} object through + * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. + * + * @param driver A communicator for external client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * (Deprecated) Factory method creating child object. + * + * The method {@link createChild createChild()} is deprecated. Don't use and override this. + * + * Note that, the {@link ParallelClientArray} is a server accepting {@link ParallelSystem parallel clients}. + * There's no way to creating the {@link ParallelSystem parallel clients} in advance before opening the server. + * + * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. + * @return ```null``` + */ + createChild(xml: library.XML): System; + /** + * Factory method creating {@link DistributedSystem} object. + * + * The method {@link createExternalClient createExternalClient()} is a factory method creating a child + * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by + * {@link addClient addClient()}. + * + * Overrides this {@link createExternalClient} method and creates a type of {@link DistributedSystem} object with + * the *driver* that communicates with the parallel client. After the creation, returns the object. Then whenever + * a parallel client has connected, matched {@link DistributedSystem} object will be constructed and + * {@link insert inserted} into this {@link DistributedSystemArray} object. + * + * @param driver A communicator with the parallel client. + * @return A newly created {@link ParallelSystem} object. + */ + protected abstract createExternalClient(driver: protocol.IClientDriver): System; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Mediator of Distributed Processing System, a server accepting slave clients. + * + * The {@link DistributedClientArrayMediator} is an abstract class, derived from {@link DistributedSystemArrayMediator} + * class, opening a server accepting {@link DistributedSystem distributed clients} as a **master**. + * + * Extends this {@link DistributedClientArrayMediator}, overrides {@link createServerBase createServerBase()} to + * determine which protocol to follow and {@link createExternalClient createExternalClient()} creating child + * {@link DistributedSystem} object. After the extending and overridings, open this server using the + * {@link open open()} method. + * + * #### [Inherited] {@link DistributedSystemArrayMediator} + * @copydoc DistributedSystemArrayMediator + */ + 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 + * {@link DistributedClientArrayMediator} object as a **master**. If the protocol is determined, then + * {@link DistributedSystem distributed clients} who may connect to {@link DistributedClientArrayMediator this + * server} must follow the specified protocol. + * + * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * When a {@link IClientDriver remote client} connects to this *master server of distributed processing system*, + * then this {@link DistributedClientArrayMediator} creates a child {@link Distributed distributed client} object + * through the {@link createExternalClient createExternalClient()} method. + * + * @param driver A communicator for external client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * (Deprecated) Factory method creating child object. + * + * The method {@link createChild createChild()} is deprecated. Don't use and override this. + * + * Note that, the {@link DistributedClientArrayMediator} is a server accepting {@link DistributedSystem distributed + * clients} as a master. There's no way to creating the {@link DistributedSystem distributed clients} in advance + * before opening the server. + * + * @param xml An {@link XML} object represents the child {@link DistributedSystem} object. + * @return null + */ + createChild(xml: library.XML): System; + /** + * Factory method creating {@link DistributedSystem} object. + * + * The method {@link createExternalClient createExternalClient()} is a factory method creating a child + * {@link DistributedSystem} object, that is called whenever a distributed client has connected, by + * {@link addClient addClient()}. + * + * Overrides this {@link createExternalClient} method and creates a type of {@link DistributedSystem} object with + * the *driver* that communicates with the distributed client. After the creation, returns the object. Then whenever + * a distributed client has connected, matched {@link DistributedSystem} object will be constructed and + * {@link insert inserted} into this {@link DistributedClientArrayMediator} object. + * + * @param driver A communicator with the distributed client. + * @return A newly created {@link DistributedSystem} object. + */ + protected abstract createExternalClient(driver: protocol.IClientDriver): System; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.templates.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 the remote, 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*.
    • + *
    + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + abstract class ExternalSystem extends protocol.EntityDequeCollection implements protocol.IProtocol { + /** + * The name represents external system have connected. + */ + protected name: string; + /** + * @hidden + */ + private system_array_; + /** + * @hidden + */ + private communicator_; + /** + * Construct from parent {@link ExternalSystemArray}. + * + * @param systemArray The parent {@link ExternalSystemArray} object. + */ + constructor(systemArray: ExternalSystemArray); + /** + * Constrct from parent {@link ExternalSystemArray} and communicator. + * + * @param systemArray The parent {@link ExternalSystemArray} object. + * @param communicator Communicator with the remote, external system. + */ + constructor(systemArray: ExternalSystemArray, communicator: protocol.IClientDriver); + /** + * Default Destructor. + * + * This {@link destructor destructor()} method is called when the {@link ExternalSystem} object is destructed and + * the {@link ExternalSystem} object is destructed when connection with the remote system is closed or this + * {@link ExternalSystem} object is {@link ExternalSystemArray.erase erased} from its parent + * {@link ExternalSystemArray} object. + * + * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically + * by those *destruction* cases. Also, if your derived {@link ExternalSystem} class has something to do on the + * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. + * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. + * + * ```typescript + * class SomeSystem extends templates.external.ExternalSystem + * { + * protected destructor(): void + * { + * // DO SOMETHING + * this.do_something(); + * + * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS + * super.destructor(); + * } + * } + * ``` + */ + protected destructor(): void; + /** + * @hidden + */ + private _Handle_close(); + /** + * Get parent {@link ExternalSystemArray} object. + */ + getSystemArray(): ExternalSystemArray; + /** + * Get parent {@link ExternalSystemArray} object. + */ + getSystemArray>(): SystemArray; + /** + * Identifier of {@link ExternalSystem} is its {@link name}. + * + * @return name. + */ + key(): string; + /** + * Get {@link name}. + */ + getName(): string; + /** + * @hidden + */ + /** + * @hidden + */ + protected communicator: protocol.ICommunicator; + /** + * Close connection. + */ + close(): void; + /** + * Send {@link Invoke} message to external system. + * + * @param invoke An {@link Invoke} message to send. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle an {@Invoke} message has received. + * + * @param invoke An {@link Invoke} message have received. + */ + replyData(invoke: protocol.Invoke): void; + /** + * Tag name of the {@link ExternalSystem} in {@link XML}. + * + * @return *system*. + */ + TAG(): string; + /** + * Tag name of {@link ExternalSystemRole children elements} belonged to the {@link ExternalSystem} in {@link XML}. + * + * @return *role*. + */ + CHILD_TAG(): string; + } +} +declare namespace samchon.templates.parallel { + /** + * A driver for a parallel slave system. + * + * The {@link ParallelSystem} is an abstract class represents a **slave** system in *Parallel Processing System*, + * connected with this **master** system. This {@link ParallelSystem} takes full charge of network communication with + * the remote, parallel **slave** system has connected. + * + * When a *parallel process* is requested (by {@link ParallelSystemArray.sendSegmentData} or + * {@link ParallelSystemArray.sendPieceData}), the number of pieces to be allocated to a {@link ParallelSystem} is + * turn on its {@link getPerformance performance index}. Higher {@link getPerformance performance index}, then + * more pieces are requested. The {@link getPerformance performance index} is revaluated whenever a *parallel process* + * has completed, basic on the execution time and number of pieces. You can sugguest or enforce the + * {@link getPerformance performance index} with {@link setPerformance} or {@link enforcePerformance}. + * + * + * + * + * + * #### Bridge & Proxy Pattern + * This class {@link ParallelSystem} is derived from the {@link ExternalSystem} class. Thus, you can take advantage + * of the *Bridge & Proxy Pattern* in this {@link ParallelSystem} class. If a process to request is not the + * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it + * may better to utilizing the *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*.
    • + *
    + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ + abstract class ParallelSystem extends external.ExternalSystem { + /** + * @hidden + */ + private progress_list_; + /** + * @hidden + */ + private history_list_; + /** + * @hidden + */ + private exclude_; + /** + * @hidden + */ + private performance; + /** + * @hidden + */ + private enforced_; + /** + * Construct from parent {@link ParallelSystemArray}. + * + * @param systemArray The parent {@link ParallelSystemArray} object. + */ + constructor(systemArray: ParallelSystemArray); + /** + * Construct from parent {@link ParallelSystemArray} and communicator. + * + * @param systemArray The parent {@link ParallelSystemArray} object. + * @param communicator A communicator communicates with remote, the external system. + */ + constructor(systemArray: ParallelSystemArray, communicator: protocol.IClientDriver); + /** + * Default Destructor. + * + * This {@link destructor destructor()} method is called when the {@link ParallelSystem} object is destructed and + * the {@link ParallelSystem} object is destructed when connection with the remote system is closed or this + * {@link ParallelSystem} object is {@link ParallelSystemArray.erase erased} from its parent + * {@link ParallelSystemArray} object. + * + * You may think if there're some *parallel processes* have requested but not completed yet, then it would be a + * critical problem because the *parallel processes* will not complete forever. Do not worry. The critical problem + * does not happen. After the destruction, the remained *parallel processes* will be shifted to and proceeded in + * other {@link ParallelSystem} objects. + * + * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically + * by those *destruction* cases. Also, if your derived {@link ParallelSystem} class has something to do on the + * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. + * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. + * + * ```typescript + * class SomeSystem extends protocol.external.ExternalSystem + * { + * protected destructor(): void + * { + * // DO SOMETHING + * this.do_something(); + * + * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS + * super.destructor(); + * } + * } + * ``` + */ + protected destructor(): void; + /** + * Get manager of this object. + * + * @return The parent {@link ParallelSystemArray} object. + */ + getSystemArray(): ParallelSystemArray; + /** + * Get manager of this object. + * + * @return The parent {@link ParallelSystemArray} object. + */ + getSystemArray>(): SystemArray; + /** + * Get performance index. + * + * Get *performance index* that indicates how much fast the remote system is. + * + * If this {@link ParallelSystem parallel system} does not have any {@link Invoke} message had handled, then the + * *performance index* will be ```1.0```, which means default and average value between all {@link ParallelSystem} + * instances (that are belonged to a same {@link ParallelSystemArray} object). + * + * You can specify this *performance index* by yourself but notice that, if the *performance index* is higher + * than other {@link ParallelSystem} objects, then this {@link ParallelSystem parallel system} will be ordered to + * handle more processes than other {@link ParallelSystem} objects. Otherwise, the *performance index* is lower + * than others, of course, less processes will be delivered. + * + * - {@link setPerformance setPerformance()} + * - {@link enforcePerformance enforcePerformance()} + * + * Unless {@link enforcePerformance enforcePerformance()} is called, This *performance index* is **revaluated** + * whenever user calls one of them below. + * + * - {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()} + * - {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()} + * - {@link DistributedProcess.sendData DistributedProcess.sendData()}. + * + * @return Performance index. + */ + getPerformance(): number; + /** + * Set performance index. + * + * Set *performance index* that indicates how much fast the remote system is. This *performance index* can be + * **revaulated**. + * + * Note that, initial and average *performance index* of {@link ParallelSystem} objects are ```1.0```. If the + * *performance index* is higher than other {@link ParallelSystem} objects, then this {@link ParallelSystem} will + * be ordered to handle more processes than other {@link ParallelSystem} objects. Otherwise, the + * *performance index* is lower than others, of course, less processes will be delivered. + * + * Unlike {@link enforcePerformance}, configuring *performance index* by this {@link setPerformance} allows + * **revaluation**. This **revaluation** prevents wrong valuation from user. For example, you *mis-valuated* the + * *performance index*. The remote system is much faster than any other, but you estimated it to the slowest one. + * It looks like a terrible case that causes {@link ParallelSystemArray entire parallel systems} to be slower, + * however, don't mind. The system will direct to the *propriate performance index* eventually with the + * **revaluation** by following methods. + * + * - {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()} + * - {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()} + * - {@link DistributedProcess.sendData DistributedProcess.sendData()}. + * + * @param val New performance index, but can be revaluated. + */ + setPerformance(val: number): void; + /** + * Enforce performance index. + * + * Enforce *performance index* that indicates how much fast the remote system is. The *performance index* will be + * fixed, never be **revaluated**. + * + * Note that, initial and average *performance index* of {@link ParallelSystem} objects are ```1.0```. If the + * *performance index* is higher than other {@link ParallelSystem} objects, then this {@link ParallelSystem} will + * be ordered to handle more processes than other {@link ParallelSystem} objects. Otherwise, the + * *performance index* is lower than others, of course, less processes will be delivered. + * + * The difference between {@link setPerformance} and this {@link enforcePerformance} is allowing **revaluation** + * or not. This {@link enforcePerformance} does not allow the **revaluation**. The *performance index* is clearly + * fixed and never be changed by the **revaluation**. But you've to keep in mind that, you can't avoid the + * **mis-valuation** with this {@link enforcePerformance}. + * + * For example, there's a remote system much faster than any other, but you **mis-estimated** it to the slowest. + * In that case, there's no way. The {@link ParallelSystemArray entire parallel systems} will be slower by the + * **mis-valuation**. By the reason, using {@link enforcePerformance}, it's recommended only when you can clearly + * certain the *performance index*. If you can't certain the *performance index* but want to recommend, then use + * {@link setPerformance} instead. + * + * @param val New performance index to be fixed. + */ + enforcePerformance(val: number): void; + /** + * @hidden + */ + private _Send_piece_data(invoke, first, last); + /** + * @hidden + */ + private _Reply_data(invoke); + /** + * @hidden + */ + protected _Report_history(xml: library.XML): void; + /** + * @hidden + */ + protected _Send_back_history(invoke: protocol.Invoke, history: slave.InvokeHistory): void; + } +} +declare namespace samchon.templates.distributed { + /** + * A driver for a distributed slave system. + * + * The {@link DistributedSystem} is an abstract class represents a **slave** system in *Distributed Processing System*, + * connected with this **master** system. This {@link DistributedSystem} takes full charge of network communication + * with the remote, distributed **slave** system has connected. + * + * This {@link DistributedSystem} has a {@link getPerformance performance index} that indicates how much the **slave** + * system is fast. The {@link getPerformance performance index} is referenced and revaluated whenever those methods + * are called: + * + * - Requesting a *parallel process* + * - {@link DistributedSystemArray.sendSegmentData} + * - {@link DistributedSystemArray.sendPieceData} + * - Requesting a *distributed process*: {@link DistributedProcess.sendData} + * + * Note that, this {@link DistributedSystem} class derived from the {@link ExternalSystem} class. Thus, this + * {@link DistributedSystem} can also have children {@link ExternalSystemRole} objects exclusively. However, the + * children {@link ExternalSystemRole roles} objects are different with the {@link DistributedProcess}. The + * domestic {@link ExternalSystemRole roles} are belonged to only a specific {@link DistributedSystem} object. + * Otherwise, the {@link DistributedProcess} objects are belonged to a {@link DistributedSystemArray} object. + * Furthermore, the relationship between this {@link DistributedSystem} and {@link DistributedProcess} classes are + * **M: N Associative**. + * + * Articles | {@link DistributedProcess} | {@link ExternalSystemRole} + * -------------|--------------------------------|---------------------------- + * Belonged to | {@link DistributedSystemArray} | {@link DistributedSystem} + * Relationship | M: N Associative | 1: N Composite + * Ownership | References | Exclusive possession + * + * + * + * + * + * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ + abstract class DistributedSystem extends parallel.ParallelSystem { + /** + * Construct from parent {@link DistributedSystemArray}. + * + * @param systemArray The parent {@link DistributedSystemArray} object. + */ + constructor(systemArray: DistributedSystemArray); + /** + * Constrct from parent {@link DistributedSystemArray} and communicator. + * + * @param systemArray The parent {@link DistributedSystemArray} object. + * @param communicator A communicator communicates with remote, the external system. + */ + constructor(systemArray: DistributedSystemArray, communicator: protocol.IClientDriver); + /** + * Factory method creating a {@link ExternalSystemRole child} object. + * + * In {@link distributed} module, the process class {@link DistributedProcess} is not belonged to a specific + * {@link DistributedSystem} object. It only belongs to a {@link DistributedSystemArray} object and has a + * **M: N Associative Relationship** between this {@link DistributedSystem} class. + * + * By that reason, it's the normal case that the {@link DistributedSystem} object does not have any children + * {@link ExternalSystemRole} object. Thus, default {@link createChild} returns ```null```. + * + * However, if you want a {@link DistributedSystem} to have its own domestic {@link ExternalSystemRole} objects + * without reference to the {@link DistributedProcess} objects, it is possible. Creates and returns the + * domestic {@link ExternalSystemRole} object. + * + * @param xml {@link XML} represents the {@link ExternalSystemRole child} object. + * @return A newly created {@link ExternalSystemRole} object or ```null```. + */ + createChild(xml: library.XML): external.ExternalSystemRole; + /** + * Get manager of this object. + * + * @return The parent {@link DistributedSystemArray} object. + */ + getSystemArray(): DistributedSystemArray; + /** + * Get manager of this object. + * + * @return The parent {@link DistributedSystemArray} object. + */ + getSystemArray>(): SystemArray; + /** + * @hidden + */ + private _Compute_average_elapsed_time(); + /** + * @inheritdoc + */ + replyData(invoke: protocol.Invoke): void; + /** + * @hidden + */ + protected _Report_history(xml: library.XML): void; + /** + * @hidden + */ + protected _Send_back_history(invoke: protocol.Invoke, history: slave.InvokeHistory): void; + } +} +declare namespace samchon.templates.distributed { + /** + * A driver for distributed slave server. + * + * The {@link DistributedServer} is an abstract class, derived from the {@link DistributedSystem} class, connecting to + * remote, distributed **slave** server. Extends this {@link DistributedServer} class and overrides the + * {@link createServerConnector createServerConnector()} method following which protocol the **slave** server uses. + * + * #### [Inheritdoc] {@link DistributedSystem} + * @copydoc DistributedSystem + */ + abstract class DistributedServer extends DistributedSystem implements external.IExternalServer { + /** + * IP address of target external system to connect. + */ + protected ip: string; + /** + * Port number of target external system to connect. + */ + protected port: number; + /** + * Construct from parent {@link DistributedSystemArray}. + * + * @param systemArray The parent {@link DistributedSystemArray} object. + */ + constructor(systemArray: DistributedSystemArray); + /** + * Factory method creating {@link IServerConnector} object. + * + * The {@link createServerConnector createServerConnector()} is an abstract method creating + * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the slave server + * follows: + * + * - {@link ServerConnector} + * - {@link WebServerConnector} + * - {@link DedicatedWorkerServerConnector} + * - {@link SharedWorkerServerConnector} + * + * @return A newly created {@link IServerConnector} object. + */ + protected abstract createServerConnector(): protocol.IServerConnector; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Master of Distributed Processing System, a client connecting to slave servers. + * + * The {@link DistributedServerArray} is an abstract class, derived from the {@link DistributedSystemArray} class, + * connecting to {@link IDistributedServer distributed servers}. + * + * Extends this {@link DistributedServerArray} and overrides {@link createChild createChild()} method creating child + * {@link IDistributedServer} object. After the extending and overriding, construct children {@link IDistributedServer} + * objects and call the {@link connect connect()} method. + * + * #### [Inherited] {@link DistributedSystemArray} + * @copydoc DistributedSystemArray + */ + abstract class DistributedServerArray extends DistributedSystemArray implements external.IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Mediator of Distributed Processing System, a client connecting to slave servers. + * + * The {@link DistributedServerArrayMediator} is an abstract class, derived from {@link DistributedSystemArrayMediator} + * class, connecting to {@link IDistributedServer distributed servers}. + * + * Extends this {@link DistributedServerArrayMediator} and overrides {@link createChild createChild()} method creating + * child {@link IDistributedServer} object. After the extending and overriding, construct children + * {@link IDistributedServer} objects and call the {@link connect connect()} method. + * + * #### [Inherited] {@link DistributedSystemArrayMediator} + * @copydoc DistributedSystemArrayMediator + */ + abstract class DistributedServerArrayMediator extends DistributedSystemArrayMediator implements external.IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Master of Distributed Processing System, be a server and client at the same time. + * + * The {@link DistributedServerClientArray} is an abstract class, derived from the {@link DistributedSystemArray} + * class, opening a server accepting {@link Distributed distributed clients} and being a client connecting to + * {@link IDistributedServer distributed servers} at the same time. + * + * Extends this {@link DistributedServerClientArray} and overrides below methods. After the overridings, open server + * with {@link open open()} method and connect to {@link IDistributedServer distributed servers} through the + * {@link connect connect()} method. + * + * - {@link createServerBase createServerBase()} + * - {@link createExternalClient createExternalClient()} + * - {@link createExternalServer createExternalServer()} + * + * #### [Inherited] {@link DistributedSystemArray} + * @copydoc DistributedSystemArray + */ + abstract class DistributedServerClientArray extends DistributedClientArray implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method of a child Entity. + * + * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. + * + * @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()}. + */ + createChild(xml: library.XML): System; + /** + * Factory method creating an {@link IDistributedServer} 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 IDistributedServer} object. + */ + protected abstract createExternalServer(xml: library.XML): System; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Mediator of Distributed Processing System, be a server and client at the same time as a **master**. + * + * The {@link DistributedServerClientArrayMediator} is an abstract class, derived from the + * {@link DistributedSystemArrayMediator} class, opening a server accepting {@link DistributedSystem distributed + * clients} and being a client connecting to {@link IDistributedServer distributed servers} at the same time. + * + * Extends this {@link DistributedServerClientArrayMediator} and overrides below methods. After the overridings, open + * server with {@link open open()} method and connect to {@link IDistributedServer distributed servers} through the + * {@link connect connect()} method. + * + * - {@link createServerBase createServerBase()} + * - {@link createExternalClient createExternalClient()} + * - {@link createExternalServer createExternalServer()} + * + * #### [Inherited] {@link DistributedSystemArrayMediator} + * @copydoc DistributedSystemArrayMediator + */ + abstract class DistributedServerClientArrayMediator extends DistributedClientArrayMediator implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method of a child Entity. + * + * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. + * + * @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()}. + */ + createChild(xml: library.XML): System; + /** + * Factory method creating an {@link IDistributedServer} 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 IDistributedServer} object. + */ + protected abstract createExternalServer(xml: library.XML): System; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * A process of Distributed Processing System. + * + * The {@link DistributedProcess} is an abstract class who represents a **process**, *SOMETHING TO DISTRIBUTE* in a Distributed + * Processing System. Overrides the {@link DistributedProcess} and defines the *SOMETHING TO DISTRIBUTE*. + * + * Relationship between {@link DistributedSystem} and {@link DistributedProcess} objects are **M: N Associative**. + * Unlike {@link ExternalSystemRole}, the {@link DistributedProcess} objects are not belonged to a specific + * {@link DistributedSystem} object. The {@link DistributedProcess} objects are belonged to the + * {@link DistributedSystemArrayMediator} directly. + * + * When you need the **distributed process**, then call {@link sendData sendData()}. The {@link sendData} will find + * the most idle {@link DistributedSystem slave system} considering not only number of processes on progress, but also + * {@link DistributedSystem.getPerformance performance index} of each {@link DistributedSystem} object and + * {@link getResource resource index} of this {@link DistributedProcess} object. The {@link Invoke} message + * requesting the **distributed process** will be sent to the most idle {@link DistributedSystem slave system}. + * + * Those {@link DistributedSystem.getPerformance performance index} and {@link getResource resource index} are + * revaluated whenever the **distributed process** has completed basis on the execution time. + * + * + * + * + * + * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ + abstract class DistributedProcess extends protocol.Entity implements protocol.IProtocol { + /** + * @hidden + */ + private system_array_; + /** + * A name, represents and identifies this {@link DistributedProcess process}. + * + * This {@link name} is an identifier represents this {@link DistributedProcess process}. This {@link name} is + * used in {@link DistributedSystemArray.getProcess} and {@link DistributedSystemArray.getProcess}, as a key elements. + * Thus, this {@link name} should be unique in its parent {@link DistributedSystemArray} object. + */ + protected name: string; + /** + * @hidden + */ + private progress_list_; + /** + * @hidden + */ + private history_list_; + /** + * @hidden + */ + private resource; + /** + * @hidden + */ + private enforced_; + /** + * Constrct from parent {@link DistributedSystemArray} object. + * + * @param systemArray The parent {@link DistributedSystemArray} object. + */ + constructor(systemArray: DistributedSystemArray); + /** + * Identifier of {@link ParallelProcess} is its {@link name}. + */ + key(): string; + /** + * Get parent {@link DistributedSystemArray} object. + * + * @return The parent {@link DistributedSystemArray} object. + */ + getSystemArray(): DistributedSystemArray; + /** + * Get parent {@link DistributedSystemArray} object. + * + * @return The parent {@link DistributedSystemArray} object. + */ + getSystemArray>(): SystemArray; + /** + * Get name, who represents and identifies this process. + */ + getName(): string; + /** + * Get resource index. + * + * Get *resource index* that indicates how much this {@link DistributedProcess process} is heavy. + * + * If this {@link DistributedProcess process} does not have any {@link Invoke} message had handled, then the + * *resource index* will be ```1.0```, which means default and average value between all + * {@link DistributedProcess} instances (that are belonged to a same {@link DistributedSystemArray} object). + * + * You can specify the *resource index* by yourself, but notice that, if the *resource index* is higher than + * other {@link DistributedProcess} objects, then this {@link DistributedProcess process} will be ordered to + * handle less processes than other {@link DistributedProcess} objects. Otherwise, the *resource index* is + * lower than others, of course, much processes will be requested. + * + * - {@link setResource setResource()} + * - {@link enforceResource enforceResource()} + * + * Unless {@link enforceResource enforceResource()} is called, This *resource index* is **revaluated** whenever + * {@link sendData sendData()} is called. + * + * @return Resource index. + */ + getResource(): number; + /** + * Set resource index. + * + * Set *resource index* that indicates how much this {@link DistributedProcess process} is heavy. This + * *resource index* can be **revaulated**. + * + * Note that, initial and average *resource index* of {@link DistributedProcess} objects are ```1.0```. If the + * *resource index* is higher than other {@link DistributedProcess} objects, then this + * {@link DistributedProcess} will be ordered to handle more processes than other {@link DistributedProcess} + * objects. Otherwise, the *resource index* is lower than others, of course, less processes will be requested. + * + * Unlike {@link enforceResource}, configuring *resource index* by this {@link setResource} allows the + * **revaluation**. This **revaluation** prevents wrong valuation from user. For example, you *mis-valuated* the + * *resource index*. The {@link DistributedProcess process} is much heavier than any other, but you estimated it + * to the lightest one. It looks like a terrible case that causes + * {@link DistributedSystemArray entire distributed processing system} to be slower, however, don't mind. The + * {@link DistributedProcess process} will the direct to the *propriate resource index* eventually with the + * **revaluation**. + * + * - The **revaluation** is caused by the {@link sendData sendData()} method. + * + * @param val New resource index, but can be revaluated. + */ + setResource(val: number): void; + /** + * Enforce resource index. + * + * Enforce *resource index* that indicates how much heavy the {@link DistributedProcess process is}. The + * *resource index* will be fixed, never be **revaluated**. + * + * Note that, initial and average *resource index* of {@link DistributedProcess} objects are ```1.0```. If the + * *resource index* is higher than other {@link DistributedProcess} objects, then this + * {@link DistributedProcess} will be ordered to handle more processes than other {@link DistributedProcess} + * objects. Otherwise, the *resource index* is lower than others, of course, less processes will be requested. + * + * The difference between {@link setResource} and this {@link enforceResource} is allowing **revaluation** or not. + * This {@link enforceResource} does not allow the **revaluation**. The *resource index* is clearly fixed and + * never be changed by the **revaluation**. But you've to keep in mind that, you can't avoid the **mis-valuation** + * with this {@link enforceResource}. + * + * For example, there's a {@link DistributedProcess process} much heavier than any other, but you + * **mis-estimated** it to the lightest. In that case, there's no way. The + * {@link DistributedSystemArray entire distributed processing system} will be slower by the **mis-valuation**. + * By the reason, using {@link enforceResource}, it's recommended only when you can clearly certain the + * *resource index*. If you can't certain the *resource index* but want to recommend, then use {@link setResource} + * instead. + * + * @param val New resource index to be fixed. + */ + enforceResource(val: number): void; + /** + * @hidden + */ + private _Compute_average_elapsed_time(); + /** + * @inheritdoc + */ + abstract replyData(invoke: protocol.Invoke): void; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message requesting a **distributed process**. The {@link Invoke} message will be sent + * to the most idle {@link DistributedSystem} object, which represents a slave system, and the most idle + * {@link DistributedSystem} object will be returned. + * + * When the **distributed process** has completed, then the {@link DistributedSystemArray} object will revaluate + * {@link getResource resource index} and {@link DistributedSystem.getPerformance performance index} of this + * {@link DistributedSystem} and the most idle {@link DistributedSystem} objects basis on the execution time. + * + * @param invoke An {@link Invoke} message requesting distributed process. + * @return The most idle {@link DistributedSystem} object who may send the {@link Invoke} message. + */ + sendData(invoke: protocol.Invoke): DistributedSystem; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message requesting a **distributed process**. The {@link Invoke} message will be sent + * to the most idle {@link DistributedSystem} object, which represents a slave system, and the most idle + * {@link DistributedSystem} object will be returned. + * + * When the **distributed process** has completed, then the {@link DistributedSystemArray} object will revaluate + * {@link getResource resource index} and {@link DistributedSystem.getPerformance performance index} of this + * {@link DistributedSystem} and the most idle {@link DistributedSystem} objects basis on the execution time. + * + * @param invoke An {@link Invoke} message requesting distributed process. + * @param weight Weight of resource which indicates how heavy this {@link Invoke} message is. Default is 1. + * + * @return The most idle {@link DistributedSystem} object who may send the {@link Invoke} message. + */ + sendData(invoke: protocol.Invoke, weight: number): DistributedSystem; + /** + * @hidden + */ + private _Complete_history(history); + /** + * @inheritdoc + */ + TAG(): string; + } +} +declare namespace samchon.templates.slave { + /** + * History of an {@link Invoke} message. + * + * The {@link InvokeHistory} is a class archiving history log of an {@link Invoke} message with elapsed time. This + * {@link InvokeHistory} class is used to report elapsed time of handling a requested process from **slave** to + * **master** system. + * + * The **master** system utilizes derived {@link InvokeHistory} objects to compute performance indices. + * - {@link ParallelSytem.getPerformance} + * - {@link DistributedProcess.getResource} + * + * @author Jeongho Nam + */ + class InvokeHistory extends protocol.Entity { + /** + * @hidden + */ + private uid; + /** + * @hidden + */ + private listener; + /** + * @hidden + */ + private start_time_; + /** + * @hidden + */ + private end_time_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from an {@link Invoke} message. + * + * @param invoke An {@link Invoke} message requesting a *parallel or distributed process*. + */ + constructor(invoke: protocol.Invoke); + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * Complete the history. + * + * Completes the history and determines the {@link getEndTime end time}. + */ + complete(): void; + key(): number; + /** + * Get unique ID. + */ + getUID(): number; + /** + * Get {@link Invoke.getListener listener} of the {@link Invoke} message. + */ + getListener(): string; + /** + * Get start time. + */ + getStartTime(): Date; + /** + * Get end time. + */ + getEndTime(): Date; + /** + * Compute elapsed time. + * + * @return nanoseconds. + */ + computeElapsedTime(): number; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + /** + * Convert to an {@link Invoke} message. + * + * Creates and returns an {@link Invoke} message that is used to reporting to the **master**. + */ + toInvoke(): protocol.Invoke; + } +} +declare namespace samchon.templates.distributed { + /** + * History of an {@link Invoke} message. + * + * The {@link PRInvokeHistory} is a class archiving history log of an {@link Invoke} message which requests the + * *distributed process*, created whenever {@link DistributedProcess.sendData} is called. + * + * When the *distributed process* has completed, then {@link complete complete()} is called and the *elapsed time* is + * determined. The elapsed time is utilized for computation of {@link DistributedSystem.getPerformance performance index} + * and {@link DistributedProcess.getResource resource index} of related objects. + * + * + * + * + * + * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ + class DSInvokeHistory extends slave.InvokeHistory { + /** + * @hidden + */ + private system_; + /** + * @hidden + */ + private process_; + /** + * @hidden + */ + private weight_; + /** + * Construct from a DistributedSystem. + * + * @param system The {@link DistributedSystem} object who sent the {@link Invoke} message. + */ + constructor(system: DistributedSystem); + /** + * Initilizer Constructor. + * + * @param system The {@link DistributedSystem} object who sent the {@link Invoke} message. + * @param process The {@link DistributedProcess} object who sent the {@link Invoke} message. + * @param invoke An {@link Invoke} message requesting the *distributed process*. + * @param weight Weight of resource which indicates how heavy this {@link Invoke} message is. + */ + constructor(system: DistributedSystem, process: DistributedProcess, invoke: protocol.Invoke, weight: number); + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * Get the related {@link DistributedSystem} object. + */ + getSystem(): DistributedSystem; + /** + * Get the related {@link DistributedProcess} object. + */ + getProcess(): DistributedProcess; + /** + * Get weight. + * + * Gets weight of resource which indicates how heavy this {@link Invoke} message is. Default is 1. + */ + getWeight(): number; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.templates.distributed { + /** + * An interface for a distributed slave server driver. + * + * The easiest way to defining a driver for distributed **slave** server is extending {@link DistributedServer} class. + * However, if you've to interact with a prallel **slave** system who can be both server and client, them make a class + * (let's name it **BaseSystem**) extending the {@link DistributedServer} class. At next, make a new class (now, I name + * it **BaseServer**) extending the **BaseSystem** and implements this interface {@link IParallelServer}. Define the + * **BaseServer** following those codes on below: + * + * + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ + interface IDistributedServer extends DistributedSystem { + /** + * Connect to external server. + */ + connect(): void; + } +} +declare namespace samchon.templates.external { + /** + * An array and manager of {@link ExternalSystem external clients} as a server. + * + * The {@link ExternalClientArray} is an abstract class, derived from the {@link ExternalSystemArray} class, opening + * a server accepting {@link ExternalSystem external clients}. + * + * Extends this {@link ExternalClientArray}, overrides {@link createServerBase createServerBase()} to determine which + * protocol to follow and {@link createExternalClient createExternalClient()} creating child {@link ExternalSystem} + * object. After the extending and overridings, open this server using the {@link open open()} method. + * + * #### [Inherited] {@link ExternalSystemArray} + * @copydoc ExternalSystemArray + */ + abstract class ExternalClientArray extends ExternalSystemArray implements IExternalClientArray { + /** + * @hidden + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating {@link IServerBase} object. + * + * This method {@link createServerBase createServerBase()} determines which templates is used in this server, + * {@link ExternalClientArray}. If the templates is determined, then {@link ExternalSystem external clients} who + * may connect to {@link ExternalClientArray this server} must follow the specified templates. + * + * Creates and returns one of them: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * When a {@link IClientDriver remote client} connects to this *server* {@link ExternalClientArray} object, + * then this {@link ExternalClientArray} creates a child {@link ExternalSystem external client} object through + * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. + * + * @param driver A communicator for external client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * (Deprecated) Factory method creating child object. + * + * The method {@link createChild createChild()} is deprecated. Don't use and override this. + * + * Note that, the {@link ExternalClientArray} is a server accepting {@link ExternalSystem external clients}. + * There's no way to creating the {@link ExternalSystem external clients} in advance before opening the server. + * + * @param xml An {@link XML} object represents the child {@link ExternalSystem} object. + * @return null + */ + createChild(xml: library.XML): T; + /** + * Factory method creating a child {@link ExternalSystem} object. + * + * @param driver A communicator with connected client. + * @return A newly created {@link ExternalSystem} object. + */ + protected abstract createExternalClient(driver: protocol.IClientDriver): T; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.templates.external { + /** + * An external server driver. + * + * The {@link ExternalServer} is an abstract class, derived from the {@link ExternalSystem} class, connecting to + * remote, external server. Extends this {@link ExternalServer} class and overrides the + * {@link createServerConnector createServerConnector()} method following which protocol the external server uses. + * + * #### [Inherited] {@link ExternalSystem} + * @copydoc ExternalSystem + */ + 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; + /** + * Construct from parent {@link ExternalSystemArray}. + * + * @param systemArray The parent {@link ExternalSystemArray} object. + */ + constructor(systemArray: ExternalSystemArray); + /** + * Factory method creating {@link IServerConnector} object. + * + * The {@link createServerConnector createServerConnector()} is an abstract method creating + * {@link IServerConnector} object. Overrides and returns one of them, considering which templates the external + * system follows: + * + * - {@link ServerConnector} + * - {@link WebServerConnector} + * - {@link DedicatedWorkerServerConnector} + * - {@link SharedWorkerServerConnector} + * + * @return A newly created {@link IServerConnector} object. + */ + protected abstract createServerConnector(): protocol.IServerConnector; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.external { + /** + * An array and manager of {@link IExternalServer external servers}. + * + * The {@link ExternalServerArray} is an abstract class, derived from the {@link ExternalSystemArray} class, + * connecting to {@link IExternalServer external servers}. + * + * Extends this {@link ExternalServerArray} and overrides {@link createChild createChild()} method creating child + * {@link IExternalServer} object. After the extending and overriding, construct children {@link IExternalServer} + * objects and call the {@link connect connect()} method. + * + * #### [Inherited] {@link ExternalSystemArray} + * @copydoc ExternalSystemArray + */ + abstract class ExternalServerArray extends ExternalSystemArray implements IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.external { + /** + * An array and manager of {@link IExternalServer external servers} and {@link ExternalSystem external clients}. + * + * The {@link ExternalServerClientArray} is an abstract class, derived from the {@link ExternalSystemArray} class, + * opening a server accepting {@link ExternalSystem external clients} and being a client connecting to + * {@link IExternalServer external servers} at the same time. + * + * Extends this {@link ExternalServerClientArray} and overrides below methods. After the overridings, open server + * with {@link open open()} method and connect to {@link IExternalServer external servers} through the + * {@link connect connect()} method. + * + * - {@link createServerBase createServerBase()} + * - {@link createExternalClient createExternalClient()} + * - {@link createExternalServer createExternalServer()} + * + * #### [Inherited] {@link ExternalSystemArray} + * @copydoc ExternalSystemArray + */ + abstract class ExternalServerClientArray extends ExternalClientArray implements IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method of a child Entity. + * + * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. + * + * @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()}. + */ + createChild(xml: library.XML): T; + /** + * 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): T; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.external { + /** + * A role of an external system. + * + * The {@link ExternalSystemRole} class represents a role, *WHAT TO DO*. Extends the {@link ExternalSystemRole} class + * and overrides {@link replyData replyData()} to define the *WHAT TO DO*. And assign this {@link ExternalSystemRole} + * object to related {@link ExternalSystem} object. + * + * + * + * + * + * #### 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} object, via {@link ExternalSystemArray.getRole 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*.
    • + *
    + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + abstract class ExternalSystemRole extends protocol.Entity implements protocol.IProtocol { + /** + * @hidden + */ + 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}. + */ + protected name: string; + /** + * 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 grandparent {@link ExternalSystemArray}. + * + * Get the grandparent {@link ExternalSystemArray} object through this parent {@link ExternalSystem}, + * {@link ExternalSystem.getSystemArray ExternalSystem.getSystemArray()}. + * + * @return The grandparent {@link ExternalSystemArray} object. + */ + getSystemArray(): ExternalSystemArray; + /** + * Get parent {@link ExternalSystemRole} object. + */ + getSystem(): ExternalSystem; + /** + * Get name, who represents and identifies this role. + */ + getName(): string; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message to remote system through the parent {@link ExternalSystem} object. + * + * @param invoke An {@link Invoke} message to send to the external system. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle replied {@link Invoke} message. + * + * {@link ExternalSystemRole.replyData ExternalSystemRole.replyData()} is an abstract method handling a replied + * {@link Invoke message} gotten from remote system via parent {@link ExternalSystem} object. Overrides this + * method and defines the *WHAT TO DO* with the {@link Invoke message}. + * + * @param invoke An {@link Invoke} message received from the {@link ExternalSystem external system}. + */ + abstract replyData(invoke: protocol.Invoke): void; + /** + * Tag name of the {@link ExternalSytemRole} in {@link XML}. + * + * @return *role*. + */ + TAG(): string; + } +} +declare namespace samchon.templates.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: + * + * + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + interface IExternalClientArray extends ExternalSystemArray, protocol.IServer { + } +} +declare namespace samchon.templates.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: + * + * + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + interface IExternalServer extends ExternalSystem { + /** + * Connect to the external server. + */ + connect(): void; + } +} +declare namespace samchon.templates.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: + * + * + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @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; + } +} +declare namespace samchon.templates.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: + * + * + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + interface IExternalServerClientArray extends IExternalClientArray { + /** + * Connect to {@link IExternalServer external servers}. + * + * This method calls children elements' method {@link IExternalServer.connect} gradually. + */ + connect(): void; + } +} +declare namespace samchon.templates.slave { + /** + * A slave system. + * + * @author Jeongho Nam + */ + abstract class SlaveSystem implements protocol.IProtocol { + /** + * @hidden + */ + protected communicator_: protocol.ICommunicator; + /** + * Default Constructor. + */ + constructor(); + sendData(invoke: protocol.Invoke): void; + abstract replyData(invoke: protocol.Invoke): void; + /** + * @hidden + */ + protected _Reply_data(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.templates.parallel { + /** + * A mediator, the master driver. + * + * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** + * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. + * + * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the + * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which + * type and protocol the **master** system follows: + * + * - A client slave connecting to master server: + * - {@link MediatorClient} + * - {@link MediatorWebClient} + * - {@link MediatorSharedWorkerClient} + * - A server slave accepting master client: + * - {@link MediatorServer} + * - {@link MediatorWebServer} + * - {@link MediatorDedicatedWorkerServer} + * - {@link MediatorSharedWorkerServer} + * + * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the + * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The + * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, + * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the + * result to its **master**. + * + * + * + * + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), + * [Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ + abstract class MediatorSystem extends slave.SlaveSystem { + /** + * @hidden + */ + private system_array_; + /** + * @hidden + */ + private progress_list_; + /** + * Construct from parent {@link ParallelSystemArrayMediator} object. + * + * @param systemArray The parent {@link ParallelSystemArrayMediator} object. + */ + constructor(systemArray: ParallelSystemArrayMediator); + /** + * Construct from parent {@link DistributedSystemArrayMediator} object. + * + * @param systemArray The parent {@link DistributedSystemArrayMediator} object. + */ + constructor(systemArray: distributed.DistributedSystemArrayMediator); + /** + * Start interaction. + * + * The {@link start start()} is an abstract method starting interaction with the **master** system. If the + * **master** is a server, then connects to the **master**. Otherwise, the **master** is client, then this + * {@link MediatorSystem} object wil open a server accepting the **master**. + */ + abstract start(): void; + /** + * Get parent {@link ParallelSystemArrayMediator} or {@link DistributedSystemArrayMediator} object. + */ + getSystemArray(): ParallelSystemArrayMediator | distributed.DistributedSystemArrayMediator; + /** + * Get parent {@link ParallelSystemArrayMediator} object. + */ + getSystemArray>(): SystemArray; + /** + * Get parent {@link DistributedSystemArrayMediator} object. + */ + getSystemArray>(): SystemArray; + /** + * @hidden + */ + private _Complete_history(uid); + /** + * @hidden + */ + protected _Reply_data(invoke: protocol.Invoke): void; + /** + * @inheritdoc + */ + replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.templates.parallel { + /** + * A mediator client, driver for the master server. + * + * The {@link MediatorServer} is a class being a client connecting to the **master** server, following the protocol + * of Samchon Framework's own. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorClient extends MediatorSystem implements slave.ISlaveClient { + /** + * @hidden + */ + private ip; + /** + * @hidden + */ + private port; + /** + * Initializer Constructor. + * + * @param systemArray The parent {@link ParallelSystemArrayMediator} object. + * @param ip IP address to connect. + * @param port Port number to connect. + */ + constructor(systemArray: ParallelSystemArrayMediator, ip: string, port: number); + /** + * Initializer Constructor. + * + * @param systemArray The parent {@link DistributedSystemArrayMediator} object. + * @param ip IP address to connect. + * @param port Port number to connect. + */ + constructor(systemArray: distributed.DistributedSystemArrayMediator, ip: string, port: number); + /** + * Factory method creating {@link IServerConnector} object. + * + * The {@link createServerConnector createServerConnector()} is an abstract method creating + * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the **master** + * server follows: + * + * - {@link ServerConnector} + * - {@link WebServerConnector} + * - {@link SharedWorkerServerConnector} + * + * @return A newly created {@link IServerConnector} object. + */ + protected createServerConnector(): protocol.IServerConnector; + /** + * @inheritdoc + */ + start(): void; + /** + * @inheritdoc + */ + connect(): void; + } + /** + * A mediator client, driver for the master server. + * + * The {@link MediatorWebClient} is a class being a client connecting to the **master** server, following the + * web-socket protocol. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorWebClient extends MediatorClient { + /** + * @inheritdoc + */ + protected createServerConnector(): protocol.IServerConnector; + } + /** + * A mediator client, driver for the master server. + * + * The {@link MediatorSharedWorkerClient} is a class being a client connecting to the **master** server, following + * the SharedWorker's protocol. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorSharedWorkerClient extends MediatorClient { + /** + * @inheritdoc + */ + protected createServerConnector(): protocol.IServerConnector; + } +} +declare namespace samchon.templates.parallel { + /** + * A mediator server, driver for the master client. + * + * The {@link MediatorServer} is a class opening a server accepting the **master** client, following the protocol of + * Samchon Framework's own. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorServer extends MediatorSystem implements slave.ISlaveServer { + /** + * @hidden + */ + private server_base_; + /** + * @hidden + */ + private port; + /** + * Initializer Constructor. + * + * @param systemArray The parent {@link ParallelSystemArrayMediator} object. + * @param port Port number of server to open. + */ + constructor(systemArray: ParallelSystemArrayMediator, port: number); + /** + * Initializer Constructor. + * + * @param systemArray The parent {@link DistributedSystemArrayMediator} object. + * @param port Port number of server to open. + */ + constructor(systemArray: distributed.DistributedSystemArrayMediator, port: number); + /** + * Factory method creating {@link IServerBase} object. + * + * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, + * {@link MediatorServer}. Note that, **slave** (this {@link MediatorServer} object) must follow the **master**'s + * protocol. + * + * Overrides and return one of them considering the which protocol to follow: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + */ + protected createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * {@link MediatorServer} represents a **slave** dedicating to its **master**. In that reason, the + * {@link MediatorServer} does not accept multiple **master** clients. It accepts only one. Thus, *listener* of + * the *communicator* is {@link MediatorSystem} object, itself. + * + * @param driver A communicator with remote client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * @inheritdoc + */ + start(): void; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } + /** + * A mediator server, driver for the master client. + * + * The {@link MediatorWebServer} is a class opening a server accepting the **master** client, following the + * web-socket protocol. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorWebServer extends MediatorServer { + /** + * @inheritdoc + */ + protected createServerBase(): protocol.IServerBase; + } + /** + * A mediator server, driver for the master client. + * + * The {@link MediatorDedicatedWorkerServer} is a class opening a server accepting the **master** client, following + * the DedicatedWorker's protocol. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorDedicatedWorkerServer extends MediatorServer { + /** + * @inheritdoc + */ + protected createServerBase(): protocol.IServerBase; + } + /** + * A mediator server, driver for the master client. + * + * The {@link MediatorSharedWorkerServer} is a class opening a server accepting the **master** client, following the + * SharedWorker's protocol. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorSharedWorkerServer extends MediatorServer { + /** + * @inheritdoc + */ + protected createServerBase(): protocol.IServerBase; + } +} +declare namespace samchon.templates.parallel { + /** + * Master of Parallel Processing System, a server accepting slave clients. + * + * The {@link ParallelClientArray} is an abstract class, derived from the {@link ParallelSystemArray} class, opening + * a server accepting {@link ParallelSystem parallel clients}. + * + * Extends this {@link ParallelClientArray}, overrides {@link createServerBase createServerBase()} to determine which + * protocol to follow and {@link createExternalClient createExternalClient()} creating child {@link ParallelSystem} + * object. After the extending and overridings, open this server using the {@link open open()} method. + * + * #### [Inherited] {@link ParallelSystemArray} + * @copydoc ParallelSystemArray + */ + abstract class ParallelClientArray extends ParallelSystemArray implements external.IExternalClientArray { + /** + * @hidden + */ + 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. + * + * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, + * then this {@link ParallelClientArray} creates a child {@link ParallelSystem parallel client} object through + * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. + * + * @param driver A communicator for external client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * (Deprecated) Factory method creating child object. + * + * The method {@link createChild createChild()} is deprecated. Don't use and override this. + * + * Note that, the {@link ParallelClientArray} is a server accepting {@link ParallelSystem parallel clients}. + * There's no way to creating the {@link ParallelSystem parallel clients} in advance before opening the server. + * + * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. + * @return ```null``` + */ + createChild(xml: library.XML): System; + /** + * Factory method creating {@link ParallelSystem} object. + * + * The method {@link createExternalClient createExternalClient()} is a factory method creating a child + * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by + * {@link addClient addClient()}. + * + * Overrides this {@link createExternalClient} method and creates a type of {@link ParallelSystem} object with + * the *driver* that communicates with the parallel client. After the creation, returns the {@link ParallelSystem} + * object. Then whenever a parallel client has connected, matched {@link ParallelSystem} object will be + * constructed and {@link insert inserted} into this {@link ParallelClientArray} object. + * + * @param driver A communicator with the parallel client. + * @return A newly created {@link ParallelSystem} object. + */ + protected abstract createExternalClient(driver: protocol.IClientDriver): System; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * Mediator of Parallel Processing System. + * + * The {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a **slave** to its + * master system at the same time. This {@link ParallelSystemArrayMediator} be a **master **system, containing and + * managing {@link ParallelSystem} objects, which represent parallel slave systems, by extending + * {@link ParallelSystemArray} class. Also, be a **slave** system through {@link getMediator mediator} object, which is + * derived from the {@link SlaveSystem} class. + * + * As a **master**, you can specify this {@link ParallelSystemArrayMediator} class to be a master server accepting + * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one + * of them below and overrides abstract factory method(s) creating the child {@link ParallelSystem} object. + * + * - {@link ParallelClientArrayMediator}: A server accepting {@link ParallelSystem parallel clients}. + * - {@link ParallelServerArrayMediator}: A client connecting to {@link ParallelServer parallel servers}. + * - {@link ParallelServerClientArrayMediator}: Both of them. Accepts {@link ParallelSystem parallel clients} and + * connects to {@link ParallelServer parallel servers} at the same time. + * + * As a **slave**, you can specify this {@link ParallelSystemArrayMediator} to be a client slave connecting to + * master server or a server slave accepting master client by overriding the {@link createMediator} method. + * Overrides the {@link createMediator createMediator()} method and return one of them: + * + * - A client slave connecting to master server: + * - {@link MediatorClient} + * - {@link MediatorWebClient} + * - {@link MediatorSharedWorkerClient} + * - A server slave accepting master client: + * - {@link MediatorServer} + * - {@link MediatorWebServer} + * - {@link MediatorDedicatedWorkerServer} + * - {@link MediatorSharedWorkerServer} + * + * #### [Inherited] {@link ParallelSystemArray} + * @copydoc ParallelSystemArray + */ + abstract class ParallelSystemArrayMediator extends ParallelSystemArray { + /** + * @hidden + */ + private mediator_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating a {@link MediatorSystem} object. + * + * The {@link createMediator createMediator()} is an abstract method creating the {@link MediatorSystem} object. + * + * You know what? this {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a + * **slave** to its master system at the same time. The {@link MediatorSystem} object makes it possible; be a + * **slave** system. This {@link createMediator} determines specific type of the {@link MediatorSystem}. + * + * Overrides the {@link createMediator createMediator()} method to create and return one of them following which + * protocol and which type of remote connection (server or client) will be used: + * + * - A client slave connecting to master server: + * - {@link MediatorClient} + * - {@link MediatorWebClient} + * - {@link MediatorSharedWorkerClient} + * - A server slave accepting master client: + * - {@link MediatorServer} + * - {@link MediatorWebServer} + * - {@link MediatorDedicatedWorkerServer} + * - {@link MediatorSharedWorkerServer} + * + * @return A newly created {@link MediatorSystem} object. + */ + protected abstract createMediator(): MediatorSystem; + /** + * Start mediator. + * + * If the {@link getMediator mediator} is a type of server, then opens the server accepting master client. + * Otherwise, the {@link getMediator mediator} is a type of client, then connects the master server. + */ + protected startMediator(): void; + /** + * Get {@link MediatorSystem} object. + * + * When you need to send an {@link Invoke} message to the master system of this + * {@link ParallelSystemArrayMediator}, then send to the {@link MediatorSystem} through this {@link getMediator}. + * + * ```typescript + * this.getMediator().sendData(...); + * ``` + * + * @return The {@link MediatorSystem} object. + */ + getMediator(): MediatorSystem; + /** + * @hidden + */ + protected _Complete_history(history: slave.InvokeHistory): boolean; + } +} +declare namespace samchon.templates.parallel { + /** + * Mediator of Parallel Processing System, a server accepting slave clients. + * + * The {@link ParallelClientArrayMediator} is an abstract class, derived from the {@link ParallelSystemArrayMediator} + * class, opening a server accepting {@link ParallelSystem parallel clients} as a **master**. + * + * Extends this {@link ParallelClientArrayMediator}, overrides {@link createServerBase createServerBase()} to + * determine which protocol to follow and {@link createExternalClient createExternalClient()} creating child + * {@link ParallelSystem} object. After the extending and overridings, open this server using the + * {@link open open()} method. + * + * #### [Inherited] {@link ParallelSystemArrayMediator} + * @copydoc ParallelSystemArrayMediator + */ + abstract class ParallelClientArrayMediator extends ParallelSystemArrayMediator implements external.IExternalClientArray { + /** + * @hidden + */ + 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 ParallelClientArrayMediator}. If the protocol is determined, then + * {@link ParallelSystem parallel clients} who may connect to {@link ParallelClientArrayMediator this server} + * must follow the specified protocol. + * + * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, + * then this {@link ParallelClientArrayMediator} creates a child {@link ParallelSystem parallel client} object + * through the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. + * + * @param driver A communicator for parallel client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * (Deprecated) Factory method creating child object. + * + * The method {@link createChild createChild()} is deprecated. Don't use and override this. + * + * Note that, the {@link ParallelClientArrayMediator} is a server accepting {@link ParallelSystem parallel + * clients} as a master. There's no way to creating the {@link ParallelSystem parallel clients} in advance before + * opening the server. + * + * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. + * @return null + */ + createChild(xml: library.XML): System; + /** + * Factory method creating {@link ParallelSystem} object. + * + * The method {@link createExternalClient createExternalClient()} is a factory method creating a child + * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by + * {@link addClient addClient()}. + * + * Overrides this {@link createExternalClient} method and creates a type of {@link ParallelSystem} object with + * the *driver* that communicates with the parallel client. After the creation, returns the {@link ParallelSystem} + * object. Then whenever a parallel client has connected, matched {@link ParallelSystem} object will be + * constructed and {@link insert inserted} into this {@link ParallelClientArrayMediator} object. + * + * @param driver A communicator with the parallel client. + * @return A newly created {@link ParallelSystem} object. + */ + protected abstract createExternalClient(driver: protocol.IClientDriver): System; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * A driver for parallel slave server. + * + * The {@link ParallelServer} is an abstract class, derived from the {@link ParallelSystem} class, connecting to + * remote, parallel **slave** server. Extends this {@link ParallelServer} class and overrides the + * {@link createServerConnector createServerConnector()} method following which protocol the **slave** server uses. + * + * #### [Inherited] {@link ParallelSystem} + * @copydoc ParallelSystem + */ + abstract class ParallelServer extends ParallelSystem implements IParallelServer { + /** + * IP address of target external system to connect. + */ + protected ip: string; + /** + * Port number of target external system to connect. + */ + protected port: number; + /** + * Construct from parent {@link ParallelSystemArray}. + * + * @param systemArray The parent {@link ParallelSystemArray} object. + */ + constructor(systemArray: ParallelSystemArray); + /** + * Factory method creating {@link IServerConnector} object. + * + * The {@link createServerConnector createServerConnector()} is an abstract method creating + * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the slave server + * follows: + * + * - {@link ServerConnector} + * - {@link WebServerConnector} + * - {@link DedicatedWorkerServerConnector} + * - {@link SharedWorkerServerConnector} + * + * @return A newly created {@link IServerConnector} object. + */ + protected abstract createServerConnector(): protocol.IServerConnector; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * Master of Parallel Processing System, a client connecting to slave servers. + * + * The {@link ParallelServerArray} is an abstract class, derived from the {@link ParallelSystemArray} class, + * connecting to {@link IParallelServer parallel servers}. + * + * Extends this {@link ParallelServerArray} and overrides {@link createChild createChild()} method creating child + * {@link IParallelServer} object. After the extending and overriding, construct children {@link IParallelServer} + * objects and call the {@link connect connect()} method. + * + * #### [Inherited] {@link ParallelSystemArray} + * @copydoc ParallelSystemArray + */ + abstract class ParallelServerArray extends ParallelSystemArray implements external.IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * Mediator of Parallel Processing System, a client connecting to slave servers. + * + * The {@link ParallelServerArrayMediator} is an abstract class, derived from the {@link ParallelSystemArrayMediator} + * class, connecting to {@link IParallelServer parallel servers}. + * + * Extends this {@link ParallelServerArrayMediator} and overrides {@link createChild createChild()} method creating + * child {@link IParallelServer} object. After the extending and overriding, construct children + * {@link IParallelServer} objects and call the {@link connect connect()} method. + * + * #### [Inherited] {@link ParallelSystemArrayMediator} + * @copydoc ParallelSystemArrayMediator + */ + abstract class ParallelServerArrayMediator extends ParallelSystemArrayMediator implements external.IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * Master of Parallel Processing System, be a server and client at the same time. + * + * The {@link ParallelServerClientArray} is an abstract class, derived from the {@link ParallelSystemArray} class, + * opening a server accepting {@link ParallelSystem parallel clients} and being a client connecting to + * {@link IParallelServer parallel servers} at the same time. + * + * Extends this {@link ParallelServerClientArray} and overrides below methods. After the overridings, open server + * with {@link open open()} method and connect to {@link IParallelServer parallel servers} through the + * {@link connect connect()} method. + * + * - {@link createServerBase createServerBase()} + * - {@link createExternalClient createExternalClient()} + * - {@link createExternalServer createExternalServer()} + * + * #### [Inherited] {@link ParallelSystemArray} + * @copydoc ParallelClientArray + */ + abstract class ParallelServerClientArray extends ParallelClientArray implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method of a child Entity. + * + * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. + * + * @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()}. + */ + createChild(xml: library.XML): System; + /** + * Factory method creating an {@link IParallelServer} 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 IParallelServer} object. + */ + protected abstract createExternalServer(xml: library.XML): System; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * Mediator of Parallel Processing System, be a server and client at the same time as a **master**. + * + * The {@link ParallelServerClientArrayMediator} is an abstract class, derived from the + * {@link ParallelSystemArrayMediator} class, opening a server accepting {@link ParallelSystem parallel clients} and + * being a client connecting to {@link IParallelServer parallel servers} at the same time. + * + * Extends this {@link ParallelServerClientArrayMediator} and overrides below methods. After the overridings, open + * server with {@link open open()} method and connect to {@link IParallelServer parallel servers} through the + * {@link connect connect()} method. + * + * - {@link createServerBase createServerBase()} + * - {@link createExternalClient createExternalClient()} + * - {@link createExternalServer createExternalServer()} + * + * #### [Inherited] {@link ParallelSystemArrayMediator} + * @copydoc ParallelClientArrayMediator + */ + abstract class ParallelServerClientArrayMediator extends ParallelClientArrayMediator implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method of a child Entity. + * + * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. + * + * @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()}. + */ + createChild(xml: library.XML): System; + /** + * Factory method creating an {@link IParallelServer} 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 IParallelServer} object. + */ + protected abstract createExternalServer(xml: library.XML): System; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * An interface for a parallel slave server driver. + * + * The easiest way to defining a driver for parallel **slave** server is extending {@link ParallelServer} class. + * However, if you've to interact with a prallel **slave** system who can be both server and client, them make a class + * (let's name it **BaseSystem**) extending the {@link ParallelSystem} class. At next, make a new class (now, I name it + * **BaseServer**) extending the **BaseSystem** and implements this interface {@link IParallelServer}. Define the + * **BaseServer** following those codes on below: + * + * + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ + interface IParallelServer extends ParallelSystem { + /** + * Connect to slave server. + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * History of an {@link Invoke} message. + * + * The {@link PRInvokeHistory} is a class archiving history log of an {@link Invoke} message which requests the + * *parallel process*, created whenever {@link ParallelSystemArray.sendSegmentData} or + * {@link ParallelSystemArray.sendSegmentData} is called. + * + * When the *parallel process* has completed, then {@link complete complete()} is called and the *elapsed time* is + * determined. The elapsed time is utilized for computation of {@link ParallelSystem.getPerformance performance index} + * of each {@link ParallelSystem parallel slave system}. + * + * + * + * + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ + class PRInvokeHistory extends slave.InvokeHistory { + /** + * @hidden + */ + private first; + /** + * @hidden + */ + private last; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from an {@link Invoke} message. + * + * @param invoke An {@link Invoke} message requesting a *parallel process*. + */ + constructor(invoke: protocol.Invoke); + /** + * Get initial piece's index. + * + * Returns initial piece's index in the section of requested *parallel process*. + * + * @return The initial index. + */ + getFirst(): number; + /** + * Get final piece's index. + * + * Returns initial piece's index in the section of requested *parallel process*. The range 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*. + * + * @return The final index. + */ + getLast(): number; + /** + * Compute number of allocated pieces. + */ + computeSize(): number; + } +} +declare namespace samchon.templates.service { + /** + * A driver of remote client. + * + * The {@link Client} is an abstract class representing and interacting with a remote client. It deals the network + * communication with the remote client and shifts {@link Invoke} message to related {@link User} and {@link Service} + * objects. + * + * Extends this {@link Client} class and override the {@link createService} method, a factory method creating a child + * {@link Service} object. Note that, {@link Client} represents a remote client, not *an user*, a specific *web page* + * or *service*. Do not define logics about user or account information. It must be declared in the parent + * {@link User} class. Also, don't define processes of a specific a web page or service. Defines them in the child + * {@link Service} class. + * + * + * + * + * + * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) + * @author Jeongho Nam + */ + abstract class Client implements protocol.IProtocol { + /** + * @hidden + */ + private user_; + /** + * @hidden + */ + private no_; + /** + * @hidden + */ + private communicator_; + /** + * @hidden + */ + private service_; + /** + * Construct from parent {@link User} and communicator. + * + * @param user Parent {@link User} object. + * @param driver Communicator with remote client. + */ + constructor(user: User, driver: protocol.WebClientDriver); + /** + * Default Destructor. + * + * This {@link destructor destructor()} method is called when the {@link Client} object is destructed and this + * {@link Client} object is destructed when connection with the remote client is closed or this {@link Client} + * object is {@link User.erase erased} from its parent {@link User} object. + * + * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically + * by those *destruction* cases. Also, if your derived {@link Client} class has something to do on the + * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. + * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. + * + * ```typescript + * class MyUser extends protocol.service.Client + * { + * protected destructor(): void + * { + * // DO SOMETHING + * this.do_something(); + * + * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS + * super.destructor(); + * } + * } + * ``` + */ + protected destructor(): void; + /** + * Factory method creating {@link Service} object. + * + * @param path Requested path. + * @return A newly created {@link Service} object or ```null```. + */ + protected abstract createService(path: string): Service; + /** + * Close connection. + */ + close(): void; + /** + * Get parent {@link User} object. + * + * Get the parent {@link User} object, who is groupping {@link Client} objects with same session id. + * + * @return The parent {@link User} object. + */ + getUser(): User; + /** + * Get child {@link Service} object. + * + * @return The child {@link Service} object. + */ + getService(): Service; + /** + * Get sequence number. + * + * Get sequence number of this {@link Client} object in the parent {@link User} object. This sequence number also + * be a *key* in the parent {@link User} object, who extended the ```std.HashMap```. + * + * @return Sequence number. + */ + getNo(): number; + /** + * Change related {@link Service} object. + * + * @param path Requested, identifier path. + */ + protected changeService(path: string): void; + /** + * Change {@link Service} to another. + * + * @param service {@link service} object to newly assigned. + */ + protected changeService(service: Service): void; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message to remote client. + * + * @param invoke An {@link Invoke} messgae to send to remote client. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle a replied {@link Invoke} message. + * + * The default {@link Client.replyData Client.replyData()} shifts chain to its parent {@link User} and belonged + * {@link Service} objects, by calling the the {@link User.replyData User.replyData()} and + * {@link Service.replyData Service.replyData()} methods. + * + * Note that, {@link Client} represents a remote client, not *an user*, a specific *web page* or *service*. Do not + * define logics about user or account information. It must be declared in the parent {@link User} class. Also, + * don't define processes of a specific a web page or service. Defines them in the child {@link Service} class. + * + * ```typescript + * class protocol.service.Client + * { + * public replyData(invoke: protocol.Invoke): void + * { + * // SHIFT TO PARENT USER + * // THE PARENT USER ALSO MAY SHIFT TO ITS PARENT SERVER + * this.getUser().replyData(invoke); + * + * // SHIFT TO BELOGED SERVICE + * if (this.getService() != null) + * this.getService().replyData(invoke); + * } + * } + * + * class MyClient extends protocol.service.Client + * { + * public replyData(invoke: protocol.Invoke): void + * { + * if (invoke.getListener() == "do_something_in_client_level") + * this.do_something_in_client_level(); + * else + * super.replyData(invoke); + * } + * } + * ``` + * + * @param invoke An {@link Invoke invoke} message to be handled in {@link Client} level. + */ + replyData(invoke: protocol.Invoke): void; + } +} +/** + * A system template for Cloud Service. + * + * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) + * @author Jeongho Nam + */ +declare namespace samchon.templates.service { + /** + * A cloud server. + * + * The {@link Server} is an abstract server class, who can build a real-time cloud server, that is following the + * web-socket protocol. Extends this {@link Server} and related classes and overrides abstract methods under below. + * After the overridings, open this {@link Server cloud server} using the {@link open open()} method. + * + * - Objects in composite relationship and their factory methods + * - {@link User}: {@link Server.createUser Server.createUser()} + * - {@link Client}: {@link User.createClient User.createClient()} + * - {@link Service}: {@link Client.createService Client.createService()} + * - {@link Invoke} message chains; {@link IProtocol.replyData replyData} + * - {@link Server.replyData} + * - {@link User.replyData} + * - {@link Client.replyData} + * - {@link Service.replyData} + * + * + * + * + * + * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) + * @author Jeongho Nam + */ + abstract class Server extends protocol.WebServer implements protocol.IProtocol { + /** + * @hidden + */ + private session_map_; + /** + * @hidden + */ + private account_map_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating {@link User} object. + * + * @return A newly created {@link User} object. + */ + protected abstract createUser(): User; + /** + * Test wheter an {@link User} exists with the *accountID*. + * + * @param accountID Account id of {@link User} to find. + * @return Exists or not. + */ + has(accountID: string): boolean; + /** + * Get an {@link User} object by its *accountID*. + * + * @param accountID Account id of {@link User} to get. + * @return An {@link User} object. + */ + get(accountID: string): User; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message to all remote clients through the belonged {@link User} and {@link Client} + * objects. Sending the {@link Invoke} message to all remote clients, it's came true by passing through + * {@link User.sendData User.sendData()}. And the {@link User.sendData} also pass through the + * {@link Client.sendData Client.sendData()}. + * + * ```typescript + * class protocol.service.Server + * { + * public sendData(invoke: Invoke): void + * { + * for (user: User in this) + * for (client: Client in user) + * client.sendData(invoke); + * } + * } + * ``` + * + * @param invoke {@link Invoke} message to send to all remote clients. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle a replied {@link Invoke} message. + * + * The {@link Server.replyData Server.replyData()} is an abstract method that handling {@link Invoke} message + * that should be handled in the {@link Server} level. Overrides this {@link replyData replyData()} method and + * defines what to do with the {@link Invoke} message in this {@link Server} level. + * + * @param invoke An {@link Invoke invoke} message to be handled in {@link Server} level. + */ + abstract replyData(invoke: protocol.Invoke): void; + /** + * Add a newly connected remote client. + * + * When a {@link WebClientDriver remote client} connects to this cloud server, then {@link Server} queries the + * {WebClientDriver.getSessionID session id} of the {@link WebClientDriver remote client}. If the + * {WebClientDriver.getSessionID session id} is new one, then creates a new {@link User} object. + * + * At next, creates a {@link Client} object who represents the newly connected remote client and insert the + * {@link Client} object to the matched {@link User} object which is new or ordinary one following the + * {WebClientDriver.getSessionID session id}. At last, a {@link Service} object can be created with referencing + * the {@link WebClientDriver.getPath path}. + * + * List of objects can be created by this method. + * - {@link User} by {@link createUser createUser()}. + * - {@link Client} by {@link User.createClient User.createClient()}. + * - {@link Service} by {@link Client.createService Client.createService()}. + * + * @param driver A web communicator for remote client. + */ + addClient(driver: protocol.WebClientDriver): void; + /** + * @hidden + */ + private _Erase_user(user); + } +} +declare namespace samchon.templates.service { + /** + * A service. + * + * The {@link Service} is an abstract class who represents a service, that is providing functions a specific page. + * + * Extends the {@link Service} class and defines its own service, which to be provided for the specific weg page, + * by overriding the {@link replyData replyData()} method. Note that, the service, functions for the specific page + * should be defined in this {@link Service} class, not its parent {@link Client} class who represents a remote client + * and takes communication responsibility. + * + * + * + * + * + * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) + * @author Jeongho Nam + */ + abstract class Service implements protocol.IProtocol { + /** + * @hidden + */ + private client_; + /** + * @hidden + */ + private path_; + /** + * Construct from parent {@link Client} and requested path. + * + * @param client Driver of remote client. + * @param path Requested path that identifies this {@link Service}. + */ + constructor(client: Client, path: string); + /** + * Default Destructor. + * + * This {@link destructor destructor()} method is call when the {@link Service} object is destructed and the + * {@link Service} object is destructed when its parent {@link Client} object has + * {@link Client.destructor destructed} or the {@link Client} object {@link Client.changeService changed} its + * child {@link Service service} object to another one. + * + * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically + * by those *destruction* cases. Also, if your derived {@link Service} class has something to do on the + * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. + */ + protected destructor(): void; + /** + * Get client. + */ + getClient(): Client; + /** + * Get requested path. + */ + getPath(): string; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message to remote system through parent {@link Client} object ({@link Client.sendData}). + * + * @param invoke An {@link Invoke} message to send to the remte system. + */ + sendData(invoke: protocol.Invoke): void; + /** + * @inheritdoc + */ + abstract replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.templates.service { + /** + * An user. + * + * The {@link User} is an abstract class groupping {@link Client} objects, who communicates with remote client, with + * same *session id*. This {@link User} represents a *remote user* literally. Within framework of remote system, + * an {@link User} corresponds to a web-browser and a {@link Client} represents a window in the web-browser. + * + * Extends this {@link User} class and override the {@link createClient} method, a factory method creating a child + * {@link Client} object. I repeat, the {@link User} class represents a *remote user*, groupping {@link Client} + * objects with same *session id*. If your cloud server has some processes to be handled in the **user level**, then + * defines method in this {@link User} class. Methods managing **account** under below are some of them: + * + * - {@link setAccount setAccount()} + * - {@link getAccountID getAccountID()} + * - {@link getAuthority getAuthority()} + * + * The children {@link Client} objects, they're contained with their key, the {@link Client.getNo sequence number}. + * If you {@link User.erase erase} the children {@link Client} object by yourself, then their connection with the + * remote clients will be {@link Client.close closed} and their {@link Client.destructor destruction method} will be + * called. If you remove {@link clear all children}, then this {@link User} object will be also + * {@link destructor destructed} and erased from the parent {@link Server} object. + * + * + * + * + * + * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) + * @author Jeongho Nam + */ + abstract class User extends collections.HashMapCollection implements protocol.IProtocol { + /** + * @hidden + */ + private server_; + /** + * @hidden + */ + private session_id_; + /** + * @hidden + */ + private sequence_; + /** + * @hidden + */ + private account_id_; + /** + * @hidden + */ + private authority_; + /** + * Construct from its parent {@link Server}. + * + * @param server The parent {@link Server} object. + */ + constructor(server: Server); + /** + * Default Destructor. + * + * This {@link destructor destructor()} method is called when the {@link User} object is destructed. The + * {@link User} object is destructed when connections with the remote clients are all closed, that is all the + * children {@link Client} objects are all removed, and 30 seconds has left. If some remote client connects + * within the 30 seconds, then the {@link User} object doesn't be destructed. + * + * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically + * by those *destruction* cases. Also, if your derived {@link User} class has something to do on the + * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. + * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. + * + * ```typescript + * class MyUser extends protocol.service.User + * { + * protected destructor(): void + * { + * // DO SOMETHING + * this.do_something(); + * + * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS + * super.destructor(); + * } + * } + * ``` + */ + protected destructor(): void; + /** + * Factory method creating a {@link Client} object. + * + * @param driver A web communicator for remote client. + * @return A newly created {@link Client} object. + */ + protected abstract createClient(driver: protocol.WebClientDriver): Client; + /** + * @hidden + */ + private _Handle_erase_client(event); + /** + * Get parent {@lin Server} object. + * + * @return Parent {@link Server} object. + */ + getServer(): Server; + /** + * Get account id. + * + * @return Account ID. + */ + getAccountID(): string; + /** + * Get authority. + * + * @return Authority + */ + getAuthority(): number; + /** + * Set *account id* and *authority*. + * + * The {@link setAccount setAccount()} is a method configuring *account id* and *authority* of this {@link User}. + * + * After the configuring, the {@link getAccountID account id} is enrolled into the parent {@link Server} as a + * **key** for this {@link User} object. You can test existence and access this {@link User} object from + * {@link Server.has Server.has()} and {@link Server.get Server.get()} with the {@link getAccountID account id}. + * Of course, if ordinary {@link getAccountID account id} had existed, then the ordinary **key** will be + * replaced. + * + * As you suggest, this {@link setAccount setAccount()} is something like a **log-in** function. If what you want + * is not **logging-in**, but **logging-out**, then configure the *account id* to empty string ``""```` or call + * the {@link lgout logout()} method. + * + * @param id To be account id. + * @param authority To be authority. + */ + setAccount(id: string, authority: number): void; + /** + * Log-out. + * + * This {@link logout logout()} method configures {@link getAccountID account id} to empty string and + * {@link getAuthority authority} to zero. + * + * The ordinary {@link getAccountID account id} will be also erased from the parent {@link Server} object. You + * can't access this {@link User} object from {@link Server.has Server.has()} and {@link Server.get Server.get()} + * with the ordinary {@link getAccountID account id} more. + */ + logout(): void; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message to all remote clients through the belonged {@link Client} objects. Sending the + * {@link Invoke} message to all remote clients, it's came true by passing through the + * {@link Client.sendData Client.sendData()} methods. + * + * ```typescript + * class protocol.service.User + * { + * public sendData(invoke: Invoke): void + * { + * for (let it = this.begin(); !it.equals(this.end()); it = it.next()) + * it.second.sendData(invoke); + * } + * } + * ``` + * + * @param invoke {@link Invoke} message to send to all remote clients. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle a replied {@link Invoke} message. + * + * The default {@link User.replyData User.replyData()} shifts chain to its parent {@link Server} object, by + * calling the {@link Server.replyData Server.replyData()} method. If there're some {@link Invoke} message to be + * handled in this {@link User} level, then override this method and defines what to do with the {@link Invoke} + * message in this {@link User} level. + * + * ```typescript + * class protocol.service.User + * { + * public replyData(invoke: protocol.Invoke): void + * { + * this.getServer().replyData(invoke); + * } + * } + * + * class MyUser extends protocol.service.User + * { + * public replyData(invoke: protocol.Invoke): void + * { + * if (invoke.apply(this) == false) // IS TARGET TO BE HANDLED IN THIS USER LEVEL + * super.replyData(invoke); // SHIFT TO SERVER + * } + * } + * ``` + * + * @param invoke An {@link Invoke invoke} message to be handled in {@link User} level. + */ + replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.templates.slave { + /** + * An {@link Invoke} message which represents a **process**. + * + * + * + * #### [Inherited] {@link Invoke} + * @copydoc Invoke + */ + class PInvoke extends protocol.Invoke { + /** + * @hidden + */ + private history_; + /** + * @hidden + */ + private slave_system_; + /** + * @hidden + */ + private hold_; + /** + * Initializer Constructor. + * + * @param invoke Original {@link Invoke} message. + * @param history {@link InvokeHistory} object archiving execution time. + * @param slaveSystem Related {@link SlaveSystem} object who gets those processes from its master. + */ + constructor(invoke: protocol.Invoke, history: InvokeHistory, slaveSystem: SlaveSystem); + /** + * Get history object. + * + * Get {@link InvokeHistory} object who is archiving execution time of this process. + */ + getHistory(): InvokeHistory; + /** + * Is the reporting hold? + */ + isHold(): boolean; + /** + * Hold reporting completion to master. + */ + hold(): void; + /** + * Report completion. + */ + complete(): void; + } +} +declare namespace samchon.templates.slave { + interface ISlaveClient extends SlaveSystem { + connect(ip: string, port: number): void; + } + abstract class SlaveClient extends SlaveSystem implements ISlaveClient { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + protected abstract createServerConnector(): protocol.IServerConnector; + /** + * @inheritdoc + */ + connect(ip: string, port: number): void; + } +} +declare namespace samchon.templates.slave { + interface ISlaveServer extends SlaveSystem, protocol.IServer { + } + abstract class SlaveServer extends SlaveSystem implements ISlaveServer { + /** + * @hidden + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + addClient(driver: protocol.IClientDriver): void; + } +} diff --git a/samchon/samchon-tests.ts b/samchon/samchon-tests.ts new file mode 100644 index 0000000000..3c805025ac --- /dev/null +++ b/samchon/samchon-tests.ts @@ -0,0 +1,2 @@ +import samchon = require("samchon"); +console.log(samchon); \ No newline at end of file diff --git a/samchon/tsconfig.json b/samchon/tsconfig.json new file mode 100644 index 0000000000..ec6c511b01 --- /dev/null +++ b/samchon/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": false, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "samchon-tests.ts" + ] +} \ No newline at end of file diff --git a/sax/index.d.ts b/sax/index.d.ts index c17ebd6928..4c556d8aab 100644 --- a/sax/index.d.ts +++ b/sax/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for sax js +// Type definitions for sax-js 1.x // Project: https://github.com/isaacs/sax-js // Definitions by: Asana // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -63,6 +63,7 @@ export declare class SAXParser { strict: boolean; opt: SAXOptions; tag: string; + ENTITIES: {[key: string]: string}; // Events onerror(e: Error): void; diff --git a/sax/sax-tests.ts b/sax/sax-tests.ts index 353ead08e0..4d9a90293d 100644 --- a/sax/sax-tests.ts +++ b/sax/sax-tests.ts @@ -13,6 +13,8 @@ import fs = require("fs"); let parser = sax.parser(/*strict=*/true, opts); + parser.ENTITIES["foo"] = "bar"; + parser.onerror = function(e: Error) { }; diff --git a/scripts/fix-tslint.ts b/scripts/fix-tslint.ts new file mode 100644 index 0000000000..940257e945 --- /dev/null +++ b/scripts/fix-tslint.ts @@ -0,0 +1,50 @@ +// Usage: ts-node fix-tslint.ts + +/// + +import assert = require("assert"); +import * as fs from 'fs'; +import * as path from 'path'; +import JSON = require("comment-json"); + +function repeat(s: string, count: number) { + return Array(count + 1).join(s); +} + +const home = path.join(__dirname, '..'); + +for (const dirName of fs.readdirSync(home)) { + if (dirName.startsWith(".") || dirName === "node_modules" || dirName === "scripts") { + continue; + } + + const dir = path.join(home, dirName); + const stats = fs.lstatSync(dir); + if (stats.isDirectory()) { + fixTslint(dir); + // Also do it for old versions + for (const subdir of fs.readdirSync(dir)) { + if (/^v\d+$/.test(subdir)) { + fixTslint(path.join(dir, subdir)); + } + } + } +} + +function fixTslint(dir: string): void { + const target = path.join(dir, 'tslint.json'); + if (!fs.existsSync(target)) return; + let json = JSON.parse(fs.readFileSync(target, 'utf-8')); + json = fix(json); + const text = Object.keys(json).length === 1 ? '{ "extends": "../tslint.json" }' : JSON.stringify(json, undefined, 4); + fs.writeFileSync(target, text + "\n", "utf-8"); +} + +function fix(config: any): any { + const out: any = {}; + for (const key in config) { + let value = config[key]; + out[key] = value; + } + return out; +} diff --git a/scripts/lint.js b/scripts/lint.js index ea3ec1d778..4d47ce3406 100644 --- a/scripts/lint.js +++ b/scripts/lint.js @@ -12,7 +12,7 @@ if (pkg.includes("/") && pkg[pkg.length - 1] !== "/") { tslintPath = path.join("..", tslintPath); } -const cmd = `node ${tslintPath}/lib/tslint-cli --format stylish "**/*.d.ts"`; +const cmd = `node ${tslintPath}/lib/tslint-cli --format stylish "**/*.ts"`; console.log(cmd); try { diff --git a/scripts/new-package.js b/scripts/new-package.js deleted file mode 100644 index 360fdff85f..0000000000 --- a/scripts/new-package.js +++ /dev/null @@ -1,121 +0,0 @@ -/// -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -const http_1 = require("http"); -const fs_1 = require("fs"); -const path = require("path"); -const newPackageName = process.argv[2]; -if (!newPackageName) { - throw new Error("Usage: node scripts/new-package.js new-package-name"); -} -run().catch(e => { - console.error(e); - process.exit(1); -}); -function run() { - return __awaiter(this, void 0, void 0, function* () { - const files = [ - ["index.d.ts", yield getIndex()], - [`${newPackageName}-tests.ts`, ""], - ["tsconfig.json", `${JSON.stringify(getTSConfig(), undefined, 4)}\n`], - ["tslint.json", '{ "extends": "../tslint.json" }\n'], - ]; - try { - yield pify1(fs_1.mkdir, newPackageName); - yield Promise.all(files.map(([name, text]) => write(name, text))); - } - catch (e) { - if (e.code === "EEXIST") { - console.warn(`Module “${newPackageName}” already exists!`); - } - else { - console.error(`Error creating module files: ${e}\nCleaning Up.`); - yield Promise.all(files.map(([name]) => rm(name))); - yield pify1(fs_1.rmdir, newPackageName); - } - process.exit(1); - } - }); -} -function getIndex() { - return __awaiter(this, void 0, void 0, function* () { - let version = "x.x"; - let project = "https://github.com/baz/foo (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.)"; - try { - const reg = JSON.parse(yield loadString(`http://registry.npmjs.org/${newPackageName}`)); - const { latest } = reg["dist-tags"]; - const { homepage } = reg.versions[latest]; - version = latest.split(".").slice(0, 2).join("."); - if (homepage !== undefined) - project = homepage; - } - catch (e) { - console.warn(`Warning: could not retrieve version/homepage information: ${e.message}`); - } - return `// Type definitions for ${newPackageName} ${version} -// Project: ${project} -// Definitions by: My Self -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -Fill the header in! -`; - }); -} -function getTSConfig() { - return { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - `${newPackageName}-tests.ts` - ] - }; -} -function write(name, content) { - return new Promise((resolve, reject) => { - fs_1.writeFile(path.join(newPackageName, name), content, err => err ? reject(err) : resolve()); - }); -} -function rm(name) { - return pify1(fs_1.unlink, path.join(newPackageName, name)).catch((e) => { - if (e.code === "ENOENT") - return; - throw e; - }); -} -function pify1(fn, arg) { - return new Promise((resolve, reject) => { - fn(arg, err => err ? reject(err) : resolve()); - }); -} -function loadString(url) { - return new Promise((resolve, reject) => { - http_1.get(url, (res) => { - if (res.statusCode !== 200) { - return reject(new Error(`HTTP Error ${res.statusCode}: ${http_1.STATUS_CODES[res.statusCode || 500]} for ${url}`)); - } - let rawData = ""; - res.on("data", chunk => rawData += chunk); - res.on("end", () => resolve(rawData)); - }).on("error", e => reject(e)); - }); -} diff --git a/scripts/new-package.ts b/scripts/new-package.ts deleted file mode 100644 index 6e9384c896..0000000000 --- a/scripts/new-package.ts +++ /dev/null @@ -1,131 +0,0 @@ -/// - -import { get, STATUS_CODES } from "http" -import { mkdir, writeFile, unlink, rmdir } from "fs" -import * as path from "path" - -interface Package { - name: string - description: string - version: string - homepage?: string -} - -interface Registry { - name: string - description: string - "dist-tags": { latest: string } - versions: { [version: string]: Package } -} - -const newPackageName = process.argv[2] -if (!newPackageName) { - throw new Error("Usage: node scripts/new-package.js new-package-name") -} - -run().catch(e => { - console.error(e) - process.exit(1) -}) - -async function run() { - const files: [string, string][] = [ - ["index.d.ts", await getIndex()], - [`${newPackageName}-tests.ts`, ""], - ["tsconfig.json", `${JSON.stringify(getTSConfig(), undefined, 4)}\n`], - ["tslint.json", '{ "extends": "../tslint.json" }\n'], - ] - - try { - await pify1(mkdir, newPackageName) - await Promise.all(files.map(([name, text]) => write(name, text))) - } catch (e) { - if (e.code === "EEXIST") { - console.warn(`Module “${newPackageName}” already exists!`) - } else { - console.error(`Error creating module files: ${e}\nCleaning Up.`) - await Promise.all(files.map(([name]) => rm(name))) - await pify1(rmdir, newPackageName) - } - process.exit(1) - } -} - -async function getIndex() { - let version = "x.x" - let project = "https://github.com/baz/foo (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.)" - try { - const reg: Registry = JSON.parse(await loadString(`http://registry.npmjs.org/${newPackageName}`)) - - const { latest } = reg["dist-tags"] - const { homepage } = reg.versions[latest] - - version = latest.split(".").slice(0, 2).join(".") - if (homepage !== undefined) project = homepage - } catch (e) { - console.warn(`Warning: could not retrieve version/homepage information: ${e.message}`) - } - - return `// Type definitions for ${newPackageName} ${version} -// Project: ${project} -// Definitions by: My Self -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -Fill the header in! -` -} - -function getTSConfig() { - return { - "compilerOptions": { - "module": "commonjs", - "lib": ["es6"], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - `${newPackageName}-tests.ts` - ] - } -} - -function write(name: string, content: string) { - return new Promise((resolve, reject) => { - writeFile(path.join(newPackageName, name), content, err => err ? reject(err): resolve()) - }) -} - -function rm(name: string) { - return pify1(unlink, path.join(newPackageName, name)).catch((e: NodeJS.ErrnoException) => { - if (e.code === "ENOENT") return - throw e - }) -} - -function pify1 void) => void, A>(fn: F, arg: A) { - return new Promise((resolve, reject) => { - fn(arg, err => err ? reject(err): resolve()) - }) -} - -function loadString(url: string): Promise { - return new Promise((resolve, reject) => { - get(url, (res) => { - if (res.statusCode !== 200) { - return reject(new Error(`HTTP Error ${res.statusCode}: ${STATUS_CODES[res.statusCode || 500]} for ${url}`)) - } - let rawData = "" - res.on("data", chunk => rawData += chunk) - res.on("end", () => resolve(rawData)) - }).on("error", e => reject(e)) - }) -} diff --git a/selenium-webdriver/chrome.d.ts b/selenium-webdriver/chrome.d.ts index 2ecff8d2f8..ce26566f02 100644 --- a/selenium-webdriver/chrome.d.ts +++ b/selenium-webdriver/chrome.d.ts @@ -1,418 +1,414 @@ import * as webdriver from './index'; import * as remote from './remote'; -declare namespace chrome { +/** + * Creates a new WebDriver client for Chrome. + * + * @extends {webdriver.WebDriver} + */ +export class Driver extends webdriver.WebDriver { /** - * Creates a new WebDriver client for Chrome. - * - * @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 */ - class Driver extends webdriver.WebDriver { - /** - * @param {(webdriver.Capabilities|Options)=} opt_config The configuration - * options. - * @param {remote.DriverService=} opt_service The session to use; will use - * the {@link getDefaultService default service} by default. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow to use, or - * {@code null} to use the currently active flow. - * @constructor - */ - constructor(opt_config?: Options | webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); - } - - interface IOptionsValues { - args: string[]; - binary?: string; - detach: boolean; - extensions: string[]; - localState?: any; - logFile?: string; - prefs?: any; - } - - interface IPerfLoggingPrefs { - enableNetwork: boolean; - enablePage: boolean; - enableTimeline: boolean; - tracingCategories: string; - bufferUsageReportingInterval: number; - } - - /** - * Class for managing ChromeDriver specific options. - */ - class Options { - /** - * @constructor - */ - constructor(); - - /** - * Extracts the ChromeDriver specific options from the given capabilities - * object. - * @param {!webdriver.Capabilities} capabilities The capabilities object. - * @return {!Options} The ChromeDriver options. - */ - static fromCapabilities(capabilities: webdriver.Capabilities): Options; - - - /** - * Add additional command line arguments to use when launching the Chrome - * browser. Each argument may be specified with or without the '--' prefix - * (e.g. '--foo' and 'foo'). Arguments with an associated value should be - * delimited by an '=': 'foo=bar'. - * @param {...(string|!Array.)} var_args The arguments to add. - * @return {!Options} A self reference. - */ - addArguments(...var_args: string[]): Options; - - - /** - * List of Chrome command line switches to exclude that ChromeDriver by default - * passes when starting Chrome. Do not prefix switches with '--'. - * - * @param {...(string|!Array)} var_args The switches to exclude. - * @return {!Options} A self reference. - */ - excludeSwitches(...var_args: string[]): Options; - - - /** - * Add additional extensions to install when launching Chrome. Each extension - * should be specified as the path to the packed CRX file, or a Buffer for an - * extension. - * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The - * extensions to add. - * @return {!Options} A self reference. - */ - addExtensions(...var_args: any[]): Options; - - - /** - * Sets the path to the Chrome binary to use. On Mac OS X, this path should - * reference the actual Chrome executable, not just the application binary - * (e.g. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'). - * - * The binary path be absolute or relative to the chromedriver server - * executable, but it must exist on the machine that will launch Chrome. - * - * @param {string} path The path to the Chrome binary to use. - * @return {!Options} A self reference. - */ - setChromeBinaryPath(path: string): Options; - - - /** - * Sets whether to leave the started Chrome browser running if the controlling - * ChromeDriver service is killed before {@link webdriver.WebDriver#quit()} is - * called. - * @param {boolean} detach Whether to leave the browser running if the - * chromedriver service is killed before the session. - * @return {!Options} A self reference. - */ - detachDriver(detach: boolean): Options; - - - /** - * Sets the user preferences for Chrome's user profile. See the 'Preferences' - * file in Chrome's user data directory for examples. - * @param {!Object} prefs Dictionary of user preferences to use. - * @return {!Options} A self reference. - */ - setUserPreferences(prefs: any): Options; - - - /** - * Sets the logging preferences for the new session. - * @param {!webdriver.logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; - - /** - * Sets the performance logging preferences. Options include: - * - * - `enableNetwork`: Whether or not to collect events from Network domain. - * - `enablePage`: Whether or not to collect events from Page domain. - * - `enableTimeline`: Whether or not to collect events from Timeline domain. - * Note: when tracing is enabled, Timeline domain is implicitly disabled, - * unless `enableTimeline` is explicitly set to true. - * - `tracingCategories`: A comma-separated string of Chrome tracing categories - * for which trace events should be collected. An unspecified or empty - * string disables tracing. - * - `bufferUsageReportingInterval`: The requested number of milliseconds - * between DevTools trace buffer usage events. For example, if 1000, then - * once per second, DevTools will report how full the trace buffer is. If a - * report indicates the buffer usage is 100%, a warning will be issued. - * - * @param {{enableNetwork: boolean, - * enablePage: boolean, - * enableTimeline: boolean, - * tracingCategories: string, - * bufferUsageReportingInterval: number}} prefs The performance - * logging preferences. - * @return {!Options} A self reference. - */ - setPerfLoggingPrefs(prefs: IPerfLoggingPrefs): Options; - - - /** - * Sets preferences for the 'Local State' file in Chrome's user data - * directory. - * @param {!Object} state Dictionary of local state preferences. - * @return {!Options} A self reference. - */ - setLocalState(state: any): Options; - - - /** - * Sets the name of the activity hosting a Chrome-based Android WebView. This - * option must be set to connect to an [Android WebView]( - * https://sites.google.com/a/chromium.org/chromedriver/getting-started/getting-started---android) - * - * @param {string} name The activity name. - * @return {!Options} A self reference. - */ - androidActivity(name: string): Options; - - - /** - * Sets the device serial number to connect to via ADB. If not specified, the - * ChromeDriver will select an unused device at random. An error will be - * returned if all devices already have active sessions. - * - * @param {string} serial The device serial number to connect to. - * @return {!Options} A self reference. - */ - androidDeviceSerial(serial: string): Options; - - - /** - * Configures the ChromeDriver to launch Chrome on Android via adb. This - * function is shorthand for - * {@link #androidPackage options.androidPackage('com.android.chrome')}. - * @return {!Options} A self reference. - */ - androidChrome(): Options; - - - /** - * Sets the package name of the Chrome or WebView app. - * - * @param {?string} pkg The package to connect to, or `null` to disable Android - * and switch back to using desktop Chrome. - * @return {!Options} A self reference. - */ - androidPackage(pkg: string): Options; - - - /** - * Sets the process name of the Activity hosting the WebView (as given by `ps`). - * If not specified, the process name is assumed to be the same as - * {@link #androidPackage}. - * - * @param {string} processName The main activity name. - * @return {!Options} A self reference. - */ - androidProcess(processName: string): Options; - - - /** - * Sets whether to connect to an already-running instead of the specified - * {@linkplain #androidProcess app} instead of launching the app with a clean - * data directory. - * - * @param {boolean} useRunning Whether to connect to a running instance. - * @return {!Options} A self reference. - */ - androidUseRunningApp(useRunning: boolean): Options; - - - /** - * Sets the path to Chrome's log file. This path should exist on the machine - * that will launch Chrome. - * @param {string} path Path to the log file to use. - * @return {!Options} A self reference. - */ - setChromeLogFile(path: string): Options; - - - /** - * Sets the directory to store Chrome minidumps in. This option is only - * supported when ChromeDriver is running on Linux. - * @param {string} path The directory path. - * @return {!Options} A self reference. - */ - setChromeMinidumpPath(path: string): Options; - - - /** - * Configures Chrome to emulate a mobile device. For more information, refer - * to the ChromeDriver project page on [mobile emulation][em]. Configuration - * options include: - * - * - `deviceName`: The name of a pre-configured [emulated device][devem] - * - `width`: screen width, in pixels - * - `height`: screen height, in pixels - * - `pixelRatio`: screen pixel ratio - * - * __Example 1: Using a Pre-configured Device__ - * - * let options = new chrome.Options().setMobileEmulation( - * {deviceName: 'Google Nexus 5'}); - * - * let driver = new chrome.Driver(options); - * - * __Example 2: Using Custom Screen Configuration__ - * - * let options = new chrome.Options().setMobileEmulation({ - * width: 360, - * height: 640, - * pixelRatio: 3.0 - * }); - * - * let driver = new chrome.Driver(options); - * - * - * [em]: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation - * [devem]: https://developer.chrome.com/devtools/docs/device-mode - * - * @param {?({deviceName: string}| - * {width: number, height: number, pixelRatio: number})} config The - * mobile emulation configuration, or `null` to disable emulation. - * @return {!Options} A self reference. - */ - setMobileEmulation(config: any): Options; - - /** - * Sets the proxy settings for the new session. - * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - - /** - * Converts this options instance to a {@link webdriver.Capabilities} object. - * @param {webdriver.Capabilities=} opt_capabilities The capabilities to merge - * these options into, if any. - * @return {!webdriver.Capabilities} The capabilities. - */ - toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; - } - - /** - * Creates {@link remote.DriverService} instances that manage a ChromeDriver - * server. - */ - class ServiceBuilder { - /** - * @param {string=} opt_exe Path to the server executable to use. If omitted, - * the builder will attempt to locate the chromedriver on the current - * PATH. - * @throws {Error} If provided executable does not exist, or the chromedriver - * cannot be found on the PATH. - * @constructor - */ - constructor(opt_exe?: string); - - /** - * Sets the port to start the ChromeDriver on. - * @param {number} port The port to use, or 0 for any free port. - * @return {!ServiceBuilder} A self reference. - * @throws {Error} If the port is invalid. - */ - usingPort(port: number): ServiceBuilder; - - - /** - * Sets which port adb is listening to. _The ChromeDriver will connect to adb - * if an {@linkplain Options#androidPackage Android session} is requested, but - * adb **must** be started beforehand._ - * - * @param {number} port Which port adb is running on. - * @return {!ServiceBuilder} A self reference. - */ - setAdbPort(port: number): ServiceBuilder; - - - /** - * Sets the path of the log file the driver should log to. If a log file is - * not specified, the driver will log to stderr. - * @param {string} path Path of the log file to use. - * @return {!ServiceBuilder} A self reference. - */ - loggingTo(path: string): ServiceBuilder; - - - /** - * Enables verbose logging. - * @return {!ServiceBuilder} A self reference. - */ - enableVerboseLogging(): ServiceBuilder; - - - /** - * Sets the number of threads the driver should use to manage HTTP requests. - * By default, the driver will use 4 threads. - * @param {number} n The number of threads to use. - * @return {!ServiceBuilder} A self reference. - */ - setNumHttpThreads(n: number): ServiceBuilder; - - - /** - * Sets the base path for WebDriver REST commands (e.g. '/wd/hub'). - * By default, the driver will accept commands relative to '/'. - * @param {string} path The base path to use. - * @return {!ServiceBuilder} A self reference. - */ - setUrlBasePath(path: string): ServiceBuilder; - - - /** - * Defines the stdio configuration for the driver service. See - * {@code child_process.spawn} for more information. - * @param {(string|!Array.)} config The - * configuration to use. - * @return {!ServiceBuilder} A self reference. - */ - setStdio(config: string | Array): ServiceBuilder; - - - /** - * Defines the environment to start the server under. This settings will be - * inherited by every browser session started by the server. - * @param {!Object.} env The environment to use. - * @return {!ServiceBuilder} A self reference. - */ - withEnvironment(env: { [key: string]: string }): ServiceBuilder; - - - /** - * Creates a new DriverService using this instance's current configuration. - * @return {remote.DriverService} A new driver service using this instance's - * current configuration. - * @throws {Error} If the driver exectuable was not specified and a default - * could not be found on the current PATH. - */ - build(): remote.DriverService; - } - - /** - * Returns the default ChromeDriver service. If such a service has not been - * configured, one will be constructed using the default configuration for - * a ChromeDriver executable found on the system PATH. - * @return {!remote.DriverService} The default ChromeDriver service. - */ - function getDefaultService(): remote.DriverService; - - /** - * Sets the default service to use for new ChromeDriver instances. - * @param {!remote.DriverService} service The service to use. - * @throws {Error} If the default service is currently running. - */ - function setDefaultService(service: remote.DriverService): void; + constructor(opt_config?: Options | webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); } -export = chrome; +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. + */ +export class Options { + /** + * @constructor + */ + constructor(); + + /** + * Extracts the ChromeDriver specific options from the given capabilities + * object. + * @param {!webdriver.Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + + /** + * Add additional command line arguments to use when launching the Chrome + * browser. Each argument may be specified with or without the '--' prefix + * (e.g. '--foo' and 'foo'). Arguments with an associated value should be + * delimited by an '=': 'foo=bar'. + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: string[]): Options; + + + /** + * List of Chrome command line switches to exclude that ChromeDriver by default + * passes when starting Chrome. Do not prefix switches with '--'. + * + * @param {...(string|!Array)} var_args The switches to exclude. + * @return {!Options} A self reference. + */ + excludeSwitches(...var_args: string[]): Options; + + + /** + * Add additional extensions to install when launching Chrome. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: any[]): Options; + + + /** + * Sets the path to the Chrome binary to use. On Mac OS X, this path should + * reference the actual Chrome executable, not just the application binary + * (e.g. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'). + * + * The binary path be absolute or relative to the chromedriver server + * executable, but it must exist on the machine that will launch Chrome. + * + * @param {string} path The path to the Chrome binary to use. + * @return {!Options} A self reference. + */ + setChromeBinaryPath(path: string): Options; + + + /** + * Sets whether to leave the started Chrome browser running if the controlling + * ChromeDriver service is killed before {@link webdriver.WebDriver#quit()} is + * called. + * @param {boolean} detach Whether to leave the browser running if the + * chromedriver service is killed before the session. + * @return {!Options} A self reference. + */ + detachDriver(detach: boolean): Options; + + + /** + * Sets the user preferences for Chrome's user profile. See the 'Preferences' + * file in Chrome's user data directory for examples. + * @param {!Object} prefs Dictionary of user preferences to use. + * @return {!Options} A self reference. + */ + setUserPreferences(prefs: any): Options; + + + /** + * Sets the logging preferences for the new session. + * @param {!webdriver.logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the performance logging preferences. Options include: + * + * - `enableNetwork`: Whether or not to collect events from Network domain. + * - `enablePage`: Whether or not to collect events from Page domain. + * - `enableTimeline`: Whether or not to collect events from Timeline domain. + * Note: when tracing is enabled, Timeline domain is implicitly disabled, + * unless `enableTimeline` is explicitly set to true. + * - `tracingCategories`: A comma-separated string of Chrome tracing categories + * for which trace events should be collected. An unspecified or empty + * string disables tracing. + * - `bufferUsageReportingInterval`: The requested number of milliseconds + * between DevTools trace buffer usage events. For example, if 1000, then + * once per second, DevTools will report how full the trace buffer is. If a + * report indicates the buffer usage is 100%, a warning will be issued. + * + * @param {{enableNetwork: boolean, + * enablePage: boolean, + * enableTimeline: boolean, + * tracingCategories: string, + * bufferUsageReportingInterval: number}} prefs The performance + * logging preferences. + * @return {!Options} A self reference. + */ + setPerfLoggingPrefs(prefs: IPerfLoggingPrefs): Options; + + + /** + * Sets preferences for the 'Local State' file in Chrome's user data + * directory. + * @param {!Object} state Dictionary of local state preferences. + * @return {!Options} A self reference. + */ + setLocalState(state: any): Options; + + + /** + * Sets the name of the activity hosting a Chrome-based Android WebView. This + * option must be set to connect to an [Android WebView]( + * https://sites.google.com/a/chromium.org/chromedriver/getting-started/getting-started---android) + * + * @param {string} name The activity name. + * @return {!Options} A self reference. + */ + androidActivity(name: string): Options; + + + /** + * Sets the device serial number to connect to via ADB. If not specified, the + * ChromeDriver will select an unused device at random. An error will be + * returned if all devices already have active sessions. + * + * @param {string} serial The device serial number to connect to. + * @return {!Options} A self reference. + */ + androidDeviceSerial(serial: string): Options; + + + /** + * Configures the ChromeDriver to launch Chrome on Android via adb. This + * function is shorthand for + * {@link #androidPackage options.androidPackage('com.android.chrome')}. + * @return {!Options} A self reference. + */ + androidChrome(): Options; + + + /** + * Sets the package name of the Chrome or WebView app. + * + * @param {?string} pkg The package to connect to, or `null` to disable Android + * and switch back to using desktop Chrome. + * @return {!Options} A self reference. + */ + androidPackage(pkg: string): Options; + + + /** + * Sets the process name of the Activity hosting the WebView (as given by `ps`). + * If not specified, the process name is assumed to be the same as + * {@link #androidPackage}. + * + * @param {string} processName The main activity name. + * @return {!Options} A self reference. + */ + androidProcess(processName: string): Options; + + + /** + * Sets whether to connect to an already-running instead of the specified + * {@linkplain #androidProcess app} instead of launching the app with a clean + * data directory. + * + * @param {boolean} useRunning Whether to connect to a running instance. + * @return {!Options} A self reference. + */ + androidUseRunningApp(useRunning: boolean): Options; + + + /** + * Sets the path to Chrome's log file. This path should exist on the machine + * that will launch Chrome. + * @param {string} path Path to the log file to use. + * @return {!Options} A self reference. + */ + setChromeLogFile(path: string): Options; + + + /** + * Sets the directory to store Chrome minidumps in. This option is only + * supported when ChromeDriver is running on Linux. + * @param {string} path The directory path. + * @return {!Options} A self reference. + */ + setChromeMinidumpPath(path: string): Options; + + + /** + * Configures Chrome to emulate a mobile device. For more information, refer + * to the ChromeDriver project page on [mobile emulation][em]. Configuration + * options include: + * + * - `deviceName`: The name of a pre-configured [emulated device][devem] + * - `width`: screen width, in pixels + * - `height`: screen height, in pixels + * - `pixelRatio`: screen pixel ratio + * + * __Example 1: Using a Pre-configured Device__ + * + * let options = new chrome.Options().setMobileEmulation( + * {deviceName: 'Google Nexus 5'}); + * + * let driver = new chrome.Driver(options); + * + * __Example 2: Using Custom Screen Configuration__ + * + * let options = new chrome.Options().setMobileEmulation({ + * width: 360, + * height: 640, + * pixelRatio: 3.0 + * }); + * + * let driver = new chrome.Driver(options); + * + * + * [em]: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation + * [devem]: https://developer.chrome.com/devtools/docs/device-mode + * + * @param {?({deviceName: string}| + * {width: number, height: number, pixelRatio: number})} config The + * mobile emulation configuration, or `null` to disable emulation. + * @return {!Options} A self reference. + */ + setMobileEmulation(config: any): Options; + + /** + * Sets the proxy settings for the new session. + * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + + /** + * Converts this options instance to a {@link webdriver.Capabilities} object. + * @param {webdriver.Capabilities=} opt_capabilities The capabilities to merge + * these options into, if any. + * @return {!webdriver.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; +} + +/** + * Creates {@link remote.DriverService} instances that manage a ChromeDriver + * server. + */ +export class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the chromedriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the chromedriver + * cannot be found on the PATH. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the ChromeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + + /** + * Sets which port adb is listening to. _The ChromeDriver will connect to adb + * if an {@linkplain Options#androidPackage Android session} is requested, but + * adb **must** be started beforehand._ + * + * @param {number} port Which port adb is running on. + * @return {!ServiceBuilder} A self reference. + */ + setAdbPort(port: number): ServiceBuilder; + + + /** + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. + */ + loggingTo(path: string): ServiceBuilder; + + + /** + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(): ServiceBuilder; + + + /** + * Sets the number of threads the driver should use to manage HTTP requests. + * By default, the driver will use 4 threads. + * @param {number} n The number of threads to use. + * @return {!ServiceBuilder} A self reference. + */ + setNumHttpThreads(n: number): ServiceBuilder; + + + /** + * Sets the base path for WebDriver REST commands (e.g. '/wd/hub'). + * By default, the driver will accept commands relative to '/'. + * @param {string} path The base path to use. + * @return {!ServiceBuilder} A self reference. + */ + setUrlBasePath(path: string): ServiceBuilder; + + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} config The + * configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string | Array): ServiceBuilder; + + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: { [key: string]: string }): ServiceBuilder; + + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; +} + +/** + * Returns the default ChromeDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a ChromeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default ChromeDriver service. + */ +export 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. + */ +export function setDefaultService(service: remote.DriverService): void; diff --git a/selenium-webdriver/edge.d.ts b/selenium-webdriver/edge.d.ts index fd59756c3d..b18a959700 100644 --- a/selenium-webdriver/edge.d.ts +++ b/selenium-webdriver/edge.d.ts @@ -1,129 +1,124 @@ import * as webdriver from './index'; import * as remote from './remote'; -declare namespace edge { - - class Driver extends webdriver.WebDriver { - /** - * @param {(capabilities.Capabilities|Options)=} opt_config The configuration - * options. - * @param {remote.DriverService=} opt_service The session to use; will use - * the {@linkplain #getDefaultService default service} by default. - * @param {promise.ControlFlow=} opt_flow The control flow to use, or - * {@code null} to use the currently active flow. - */ - constructor(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); - - /** - * This function is a no-op as file detectors are not supported by this - * implementation. - * @override - */ - setFileDetector(): void; - } +export 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); /** - * Class for managing MicrosoftEdgeDriver specific options. + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override */ - class Options { - - /** - * Extracts the MicrosoftEdgeDriver specific options from the given - * capabilities object. - * @param {!capabilities.Capabilities} caps The capabilities object. - * @return {!Options} The MicrosoftEdgeDriver options. - */ - static fromCapabilities(cap: webdriver.Capabilities): Options; - - /** - * Sets the proxy settings for the new session. - * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - /** - * Sets the page load strategy for Edge. - * Supported values are 'normal', 'eager', and 'none'; - * - * @param {string} pageLoadStrategy The page load strategy to use. - * @return {!Options} A self reference. - */ - setPageLoadStrategy(pageLoadStrategy: string): Options; - - /** - * Converts this options instance to a {@link capabilities.Capabilities} - * object. - * @param {capabilities.Capabilities=} opt_capabilities The capabilities to - * merge these options into, if any. - * @return {!capabilities.Capabilities} The capabilities. - */ - toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; - } - - /** - * Creates {@link remote.DriverService} instances that manage a - * MicrosoftEdgeDriver server in a child process. - */ - class ServiceBuilder { - /** - * @param {string=} opt_exe Path to the server executable to use. If omitted, - * the builder will attempt to locate the MicrosoftEdgeDriver on the current - * PATH. - * @throws {Error} If provided executable does not exist, or the - * MicrosoftEdgeDriver cannot be found on the PATH. - */ - constructor(opt_exe?: string); - - /** - * Defines the stdio configuration for the driver service. See - * {@code child_process.spawn} for more information. - * @param {(string|!Array.)} - * config The configuration to use. - * @return {!ServiceBuilder} A self reference. - */ - setStdio(config: string | Array): ServiceBuilder; - - /** - * Sets the port to start the MicrosoftEdgeDriver on. - * @param {number} port The port to use, or 0 for any free port. - * @return {!ServiceBuilder} A self reference. - * @throws {Error} If the port is invalid. - */ - usingPort(port: number): ServiceBuilder; - - /** - * Defines the environment to start the server under. This settings will be - * inherited by every browser session started by the server. - * @param {!Object.} env The environment to use. - * @return {!ServiceBuilder} A self reference. - */ - withEnvironment(env: Object): ServiceBuilder; - - /** - * Creates a new DriverService using this instance's current configuration. - * @return {!remote.DriverService} A new driver service using this instance's - * current configuration. - * @throws {Error} If the driver exectuable was not specified and a default - * could not be found on the current PATH. - */ - build(): remote.DriverService; - } - - /** - * Returns the default MicrosoftEdgeDriver service. If such a service has - * not been configured, one will be constructed using the default configuration - * for an MicrosoftEdgeDriver executable found on the system PATH. - * @return {!remote.DriverService} The default MicrosoftEdgeDriver service. - */ - function getDefaultService(): remote.DriverService; - - /** - * Sets the default service to use for new MicrosoftEdgeDriver instances. - * @param {!remote.DriverService} service The service to use. - * @throws {Error} If the default service is currently running. - */ - function setDefaultService(service: remote.DriverService): void; + setFileDetector(): void; } -export = edge; +/** + * Class for managing MicrosoftEdgeDriver specific options. + */ +export class Options { + + /** + * Extracts the MicrosoftEdgeDriver specific options from the given + * capabilities object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The MicrosoftEdgeDriver options. + */ + static fromCapabilities(cap: webdriver.Capabilities): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Sets the page load strategy for Edge. + * Supported values are 'normal', 'eager', and 'none'; + * + * @param {string} pageLoadStrategy The page load strategy to use. + * @return {!Options} A self reference. + */ + setPageLoadStrategy(pageLoadStrategy: string): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; +} + +/** + * Creates {@link remote.DriverService} instances that manage a + * MicrosoftEdgeDriver server in a child process. + */ +export class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the MicrosoftEdgeDriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the + * MicrosoftEdgeDriver cannot be found on the PATH. + */ + constructor(opt_exe?: string); + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string | Array): ServiceBuilder; + + /** + * Sets the port to start the MicrosoftEdgeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; +} + +/** + * Returns the default MicrosoftEdgeDriver service. If such a service has + * not been configured, one will be constructed using the default configuration + * for an MicrosoftEdgeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default MicrosoftEdgeDriver service. + */ +export 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. + */ +export function setDefaultService(service: remote.DriverService): void; diff --git a/selenium-webdriver/executors.d.ts b/selenium-webdriver/executors.d.ts index 6cded31fec..c7bf15ef8d 100644 --- a/selenium-webdriver/executors.d.ts +++ b/selenium-webdriver/executors.d.ts @@ -1,15 +1,11 @@ import * as webdriver from './index'; -declare namespace executors { - /** - * Creates a command executor that uses WebDriver's JSON wire protocol. - * @param {(string|!promise.Promise)} url The server's URL, - * or a promise that will resolve to that URL. - * @param {?string=} opt_proxy (optional) The URL of the HTTP proxy for the - * client to use. - * @returns {!./lib/command.Executor} The new command executor. - */ - function createExecutor(url: string | webdriver.promise.Promise, opt_agent?: string, opt_proxy?: string): webdriver.Executor; -} - -export = 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. + */ +export function createExecutor(url: string | webdriver.promise.Promise, opt_agent?: string, opt_proxy?: string): webdriver.Executor; diff --git a/selenium-webdriver/firefox.d.ts b/selenium-webdriver/firefox.d.ts index 25542f144f..7678c404ce 100644 --- a/selenium-webdriver/firefox.d.ts +++ b/selenium-webdriver/firefox.d.ts @@ -1,257 +1,253 @@ import * as webdriver from './index'; import * as remote from './remote'; -declare namespace firefox { +/** + * Manages a Firefox subprocess configured for use with WebDriver. + */ +export class Binary { /** - * Manages a Firefox subprocess configured for use with WebDriver. + * @param {string=} opt_exe Path to the Firefox binary to use. If not + * specified, will attempt to locate Firefox on the current system. + * @constructor */ - 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; - } + constructor(opt_exe?: string); /** - * Models a Firefox proifle directory for use with the FirefoxDriver. The - * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} - * is called. + * 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. */ - 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); + addArguments(...var_args: string[]): void; - /** - * 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. + * 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. */ - 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; + launch(profile: string): webdriver.promise.Promise; - /** - * 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} + * Kills the managed Firefox process. + * @return {!promise.Promise} A promise for when the process has terminated. */ - 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; - } + kill(): webdriver.promise.Promise; } -export = firefox; +/** + * Models a Firefox proifle directory for use with the FirefoxDriver. The + * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} + * is called. + */ +export 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. + */ +export 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} + */ +export function findWires(): string; + +/** + * @param {(string|!Binary)} binary . + * @return {!remote.DriverService} . + */ +export 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. + */ +export function prepareProfile(profile: string | any, port: number): any; + +/** + * A WebDriver client for Firefox. + */ +export 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; +} diff --git a/selenium-webdriver/http.d.ts b/selenium-webdriver/http.d.ts index b4ade88430..a0a25a7955 100644 --- a/selenium-webdriver/http.d.ts +++ b/selenium-webdriver/http.d.ts @@ -1,156 +1,152 @@ import * as webdriver from './index'; -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. + */ +export 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 + */ +export class HttpRequest { /** - * Converts a headers map to a HTTP header block string. - * @param {!Map} headers The map to convert. - * @return {string} The headers as a string. + * @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. */ - function headersToString(headers: any): string; + constructor(method: string, path: string, opt_data?: Object); - /** - * 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; + /** @override */ + toString(): string; } -export = http; +/** + * Represents a HTTP response message. + * @final + */ +export 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; +} + + +export function post(path: string): any; +export function del(path: string): any; +export function get(path: string): any; +export function resource(method: string, path: string): any; + +/** + * A basic HTTP client used to send messages to a remote end. + */ +export 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. + */ +export 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} + */ +export 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 {?} . + */ +export 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. + */ +export 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. + */ +export function buildPath(path: string, parameters: Object): string; diff --git a/selenium-webdriver/ie.d.ts b/selenium-webdriver/ie.d.ts index 5d9b51c64d..9e8cab2457 100644 --- a/selenium-webdriver/ie.d.ts +++ b/selenium-webdriver/ie.d.ts @@ -1,211 +1,205 @@ import * as webdriver from './index'; -declare namespace ie { +/** + * A WebDriver client for Microsoft's Internet Explorer. + */ +export 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); /** - * A WebDriver client for Microsoft's Internet Explorer. + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override */ - 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; - } - + setFileDetector(): void; } -export = ie; +/** + * Class for managing IEDriver specific options. + */ +export 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: string[]): 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; +} diff --git a/selenium-webdriver/index.d.ts b/selenium-webdriver/index.d.ts index 17fba9ceae..39d56d7d5b 100644 --- a/selenium-webdriver/index.d.ts +++ b/selenium-webdriver/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Selenium WebDriverJS 2.53.1 +// Type definitions for Selenium WebDriverJS 2.53 // 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 @@ -10,2090 +10,1004 @@ import * as ie from './ie'; import * as opera from './opera'; import * as safari from './safari'; -declare namespace webdriver { +export namespace error { + class IError extends Error { + constructor(opt_error?: string); - namespace error { - class IError extends Error { - constructor(opt_error?: string); - - code(): number; - } - - /** - * The base WebDriver error type. This error type is only used directly when a - * more appropriate category is not defined for the offending error. - */ - class WebDriverError extends IError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An attempt was made to select an element that cannot be selected. - */ - class ElementNotSelectableError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An element command could not be completed because the element is not visible - * on the page. - */ - class ElementNotVisibleError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * The arguments passed to a command are either invalid or malformed. - */ - class InvalidArgumentError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An illegal attempt was made to set a cookie under a different domain than - * the current page. - */ - class InvalidCookieDomainError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * The coordinates provided to an interactions operation are invalid. - */ - class InvalidElementCoordinatesError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An element command could not be completed because the element is in an - * invalid state, e.g. attempting to click an element that is no longer attached - * to the document. - */ - class InvalidElementStateError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * Argument was an invalid selector. - */ - class InvalidSelectorError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * Occurs when a command is directed to a session that does not exist. - */ - class NoSuchSessionError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An error occurred while executing JavaScript supplied by the user. - */ - class JavascriptError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * The target for mouse interaction is not in the browser’s viewport and cannot - * be brought into that viewport. - */ - class MoveTargetOutOfBoundsError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An attempt was made to operate on a modal dialog when one was not open. - */ - class NoSuchAlertError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An element could not be located on the page using the given search - * parameters. - */ - class NoSuchElementError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A request to switch to a frame could not be satisfied because the frame - * could not be found. - */ - class NoSuchFrameError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A request to switch to a window could not be satisfied because the window - * could not be found. - */ - class NoSuchWindowError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A script did not complete before its timeout expired. - */ - class ScriptTimeoutError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A new session could not be created. - */ - class SessionNotCreatedError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An element command failed because the referenced element is no longer - * attached to the DOM. - */ - class StaleElementReferenceError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An operation did not completErrorCodee before its timeout expired. - */ - class TimeoutError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A request to set a cookie’s value could not be satisfied. - */ - class UnableToSetCookieError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A screen capture operation was not possible. - */ - class UnableToCaptureScreenError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A modal dialog was open, blocking this operation. - */ - class UnexpectedAlertOpenError extends WebDriverError { - /** - * @param {string=} opt_error the error message, if any. - * @param {string=} opt_text the text of the open dialog, if available. - */ - constructor(opt_error?: string, opt_text?: string); - - /** - * @return {(string|undefined)} The text displayed with the unhandled alert, - * if available. - */ - getAlertText(): string; - } - - /** - * A command could not be executed because the remote end is not aware of it. - */ - class UnknownCommandError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * The requested command matched a known URL but did not match an method for - * that URL. - */ - class UnknownMethodError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * Reports an unsupport operation. - */ - class UnsupportedOperationError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - } - - namespace logging { - - /** - * A hash describing log preferences. - * @typedef {Object.} - */ - class Preferences { - setLevel(type: string, 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; - - /** - * Defines a message level that may be used to control logging output. - * - * @final - */ - class Level { - name_: string; - value_: number; - /** - * @param {string} name the level's name. - * @param {number} level the level's numeric value. - */ - constructor(name: string, level: number); - - /** @override */ - toString(): string; - - /** This logger's name. */ - name: string; - - /** The numeric log level. */ - value: number; - - /** - * Indicates no log messages should be recorded. - * @const - */ - static OFF: Level; - /** - * Log messages with a level of `1000` or higher. - * @const - */ - static SEVERE: Level; - /** - * Log messages with a level of `900` or higher. - * @const - */ - static WARNING: Level; - /** - * Log messages with a level of `800` or higher. - * @const - */ - static INFO: Level; - /** - * Log messages with a level of `700` or higher. - * @const - */ - static DEBUG: Level; - /** - * Log messages with a level of `500` or higher. - * @const - */ - static FINE: Level; - /** - * Log messages with a level of `400` or higher. - * @const - */ - static FINER: Level; - /** - * Log messages with a level of `300` or higher. - * @const - */ - static FINEST: Level; - /** - * Indicates all log messages should be recorded. - * @const - */ - static ALL: Level; - } - - /** - * Converts a level name or value to a {@link webdriver.logging.Level} value. - * If the name/value is not recognized, {@link webdriver.logging.Level.ALL} - * will be returned. - * @param {(number|string)} nameOrValue The log level name, or value, to - * convert . - * @return {!webdriver.logging.Level} The converted level. - */ - function getLevel(nameOrValue: string | number): Level; - - interface IEntryJSON { - level: string; - message: string; - timestamp: number; - type: string; - } - - /** - * A single log entry. - */ - class Entry { - /** - * @param {(!webdriver.logging.Level|string)} level The entry level. - * @param {string} message The log message. - * @param {number=} opt_timestamp The time this entry was generated, in - * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the - * current time will be used. - * @param {string=} opt_type The log type, if known. - * @constructor - */ - constructor(level: Level | string | number, message: string, opt_timestamp?: number, opt_type?: string | IType); - - /** @type {!webdriver.logging.Level} */ - level: Level; - - /** @type {string} */ - message: string; - - /** @type {number} */ - timestamp: number; - - /** @type {string} */ - type: string; - - /** - * @return {{level: string, message: string, timestamp: number, - * type: string}} The JSON representation of this entry. - */ - toJSON(): IEntryJSON; - } - - /** - * An object used to log debugging messages. Loggers use a hierarchical, - * dot-separated naming scheme. For instance, 'foo' is considered the parent of - * the 'foo.bar' and an ancestor of 'foo.bar.baz'. - * - * Each logger may be assigned a {@linkplain #setLevel log level}, which - * controls which level of messages will be reported to the - * {@linkplain #addHandler handlers} attached to this instance. If a log level - * is not explicitly set on a logger, it will inherit its parent. - * - * This class should never be directly instantiated. Instead, users should - * obtain logger references using the {@linkplain ./logging.getLogger() - * getLogger()} function. - * - * @final - */ - class Logger { - /** - * @param {string} name the name of this logger. - * @param {Level=} opt_level the initial level for this logger. - */ - constructor(name: string, opt_level?: Level); - - /** @private {string} */ - name_: string; - /** @private {Level} */ - level_: Level; - /** @private {Logger} */ - parent_: Logger; - /** @private {Set} */ - handlers_: any; - - /** @return {string} the name of this logger. */ - getName(): string; - - /** - * @param {Level} level the new level for this logger, or `null` if the logger - * should inherit its level from its parent logger. - */ - setLevel(level: Level): void; - - /** @return {Level} the log level for this logger. */ - getLevel(): Level; - - /** - * @return {!Level} the effective level for this logger. - */ - getEffectiveLevel(): Level; - - /** - * @param {!Level} level the level to check. - * @return {boolean} whether messages recorded at the given level are loggable - * by this instance. - */ - isLoggable(level: Level): boolean; - - /** - * Adds a handler to this logger. The handler will be invoked for each message - * logged with this instance, or any of its descendants. - * - * @param {function(!Entry)} handler the handler to add. - */ - addHandler(handler: any): void; - - /** - * Removes a handler from this logger. - * - * @param {function(!Entry)} handler the handler to remove. - * @return {boolean} whether a handler was successfully removed. - */ - removeHandler(handler: any): void; - - /** - * Logs a message at the given level. The message may be defined as a string - * or as a function that will return the message. If a function is provided, - * it will only be invoked if this logger's - * {@linkplain #getEffectiveLevel() effective log level} includes the given - * `level`. - * - * @param {!Level} level the level at which to log the message. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - log(level: Level, loggable: string | Function): void; - - /** - * Logs a message at the {@link Level.SEVERE} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - severe(loggable: string | Function): void; - - /** - * Logs a message at the {@link Level.WARNING} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - warning(loggable: string | Function): void; - - /** - * Logs a message at the {@link Level.INFO} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - info(loggable: string | Function): void; - - /** - * Logs a message at the {@link Level.DEBUG} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - debug(loggable: string | Function): void; - - /** - * Logs a message at the {@link Level.FINE} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - fine(loggable: string | Function): void; - - /** - * Logs a message at the {@link Level.FINER} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - finer(loggable: string | Function): void; - - /** - * Logs a message at the {@link Level.FINEST} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - finest(loggable: string | Function): void; - } - - /** - * Maintains a collection of loggers. - * - * @final - */ - class LogManager { - /** - * Retrieves a named logger, creating it in the process. This function will - * implicitly create the requested logger, and any of its parents, if they - * do not yet exist. - * - * @param {string} name the logger's name. - * @return {!Logger} the requested logger. - */ - getLogger(name: string): Logger; - - /** - * Creates a new logger. - * - * @param {string} name the logger's name. - * @param {!Logger} parent the logger's parent. - * @return {!Logger} the new logger. - * @private - */ - createLogger_(name: string, parent: Logger): Logger; - } - } - - namespace promise { - //region Functions - - /** - * Given an array of promises, will return a promise that will be fulfilled - * with the fulfillment values of the input array's values. If any of the - * input array's promises are rejected, the returned promise will be rejected - * with the same reason. - * - * @param {!Array<(T|!ManagedPromise)>} arr An array of - * promises to wait on. - * @return {!ManagedPromise>} A promise that is - * fulfilled with an array containing the fulfilled values of the - * input array, or rejected with the same reason as the first - * rejected value. - * @template T - */ - function all(arr: Array>): Promise; - - /** - * Invokes the appropriate callback function as soon as a promised - * {@code value} is resolved. This function is similar to - * {@link webdriver.promise.when}, except it does not return a new promise. - * @param {*} value The value to observe. - * @param {Function} callback The function to call when the value is - * resolved successfully. - * @param {Function=} opt_errback The function to call when the value is - * rejected. - */ - function asap(value: any, callback: Function, opt_errback?: Function): void; - - /** - * @return {!webdriver.promise.ControlFlow} The currently active control flow. - */ - function controlFlow(): ControlFlow; - - /** - * Creates a new control flow. The provided callback will be invoked as the - * first task within the new flow, with the flow as its sole argument. Returns - * a promise that resolves to the callback result. - * @param {function(!ControlFlow)} callback The entry point - * to the newly created flow. - * @return {!ManagedPromise} A promise that resolves to the callback - * result. - */ - function createFlow(callback: (flow: ControlFlow) => R): Promise; - - /** - * Determines whether a {@code value} should be treated as a promise. - * Any object whose 'then' property is a function will be considered a promise. - * - * @param {*} value The value to test. - * @return {boolean} Whether the value is a promise. - */ - function isPromise(value: any): boolean; - - /** - * Tests is a function is a generator. - * @param {!Function} fn The function to test. - * @return {boolean} Whether the function is a generator. - */ - function isGenerator(fn: Function): boolean; - - /** - * Creates a promise that will be resolved at a set time in the future. - * @param {number} ms The amount of time, in milliseconds, to wait before - * resolving the promise. - * @return {!ManagedPromise} The promise. - */ - function delayed(ms: number): Promise; - - /** - * Calls a function for each element in an array, and if the function returns - * true adds the element to a new array. - * - * If the return value of the filter function is a promise, this function - * will wait for it to be fulfilled before determining whether to insert the - * element into the new array. - * - * If the filter function throws or returns a rejected promise, the promise - * returned by this function will be rejected with the same reason. Only the - * first failure will be reported; all subsequent errors will be silently - * ignored. - * - * @param {!(Array|ManagedPromise>)} arr The - * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array): ( - * boolean|ManagedPromise)} fn The function - * to call for each element in the array. - * @param {SELF=} opt_self The object to be used as the value of 'this' within - * {@code fn}. - * @template TYPE, SELF - */ - function filter(arr: Array | Promise>, fn: (element: T, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; - - /** - * Creates a new deferred object. - * @return {!webdriver.promise.Deferred} The new deferred object. - */ - function defer(): Deferred; - - /** - * Creates a promise that has been resolved with the given value. - * @param {T=} opt_value The resolved value. - * @return {!ManagedPromise} The resolved promise. - * @template T - */ - function fulfilled(opt_value?: T): Promise; - - /** - * Calls a function for each element in an array and inserts the result into a - * new array, which is used as the fulfillment value of the promise returned - * by this function. - * - * If the return value of the mapping function is a promise, this function - * will wait for it to be fulfilled before inserting it into the new array. - * - * If the mapping function throws or returns a rejected promise, the - * promise returned by this function will be rejected with the same reason. - * Only the first failure will be reported; all subsequent errors will be - * silently ignored. - * - * @param {!(Array|ManagedPromise>)} arr The - * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array): ?} fn The - * function to call for each element in the array. This function should - * expect three arguments (the element, the index, and the array itself. - * @param {SELF=} opt_self The object to be used as the value of 'this' within - * {@code fn}. - * @template TYPE, SELF - */ - function map(arr: Array | Promise>, fn: (self: any, type: any, index: number, array: 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 - */ - function rejected(opt_reason?: any): Promise; - - /** - * Wraps a function that expects a node-style callback as its final - * argument. This callback expects two arguments: an error value (which will be - * null if the call succeeded), and the success value as the second argument. - * The callback will the resolve or reject the returned promise, based on its - * arguments. - * @param {!Function} fn The function to wrap. - * @param {...?} var_args The arguments to apply to the function, excluding the - * final callback. - * @return {!ManagedPromise} A promise that will be resolved with the - * result of the provided function's callback. - */ - function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; - - /** - * Consumes a {@code GeneratorFunction}. Each time the generator yields a - * promise, this function will wait for it to be fulfilled before feeding the - * fulfilled value back into {@code next}. Likewise, if a yielded promise is - * rejected, the rejection error will be passed to {@code throw}. - * - * __Example 1:__ the Fibonacci Sequence. - * - * promise.consume(function* fibonacci() { - * var n1 = 1, n2 = 1; - * for (var i = 0; i < 4; ++i) { - * var tmp = yield n1 + n2; - * n1 = n2; - * n2 = tmp; - * } - * return n1 + n2; - * }).then(function(result) { - * console.log(result); // 13 - * }); - * - * __Example 2:__ a generator that throws. - * - * promise.consume(function* () { - * yield promise.delayed(250).then(function() { - * throw Error('boom'); - * }); - * }).catch(function(e) { - * console.log(e.toString()); // Error: boom - * }); - * - * @param {!Function} generatorFn The generator function to execute. - * @param {Object=} opt_self The object to use as 'this' when invoking the - * initial generator. - * @param {...*} var_args Any arguments to pass to the initial generator. - * @return {!ManagedPromise} A promise that will resolve to the - * generator's final result. - * @throws {TypeError} If the given function is not a generator. - */ - function consume(generatorFn: Function, opt_self?: any, ...var_args: any[]): Promise; - - /** - * Registers an observer on a promised {@code value}, returning a new promise - * that will be resolved when the value is. If {@code value} is not a promise, - * then the return promise will be immediately resolved. - * @param {*} value The value to observe. - * @param {Function=} opt_callback The function to call when the value is - * resolved successfully. - * @param {Function=} opt_errback The function to call when the value is - * rejected. - * @return {!ManagedPromise} A new promise. - */ - function when(value: T | Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; - - /** - * Returns a promise that will be resolved with the input value in a - * fully-resolved state. If the value is an array, each element will be fully - * resolved. Likewise, if the value is an object, all keys will be fully - * resolved. In both cases, all nested arrays and objects will also be - * fully resolved. All fields are resolved in place; the returned promise will - * resolve on {@code value} and not a copy. - * - * Warning: This function makes no checks against objects that contain - * cyclical references: - * - * var value = {}; - * value['self'] = value; - * promise.fullyResolved(value); // Stack overflow. - * - * @param {*} value The value to fully resolve. - * @return {!ManagedPromise} A promise for a fully resolved version - * of the input value. - */ - function fullyResolved(value: any): Promise; - - /** - * Changes the default flow to use when no others are active. - * @param {!ControlFlow} flow The new default flow. - * @throws {Error} If the default flow is not currently active. - */ - function setDefaultFlow(flow: ControlFlow): void; - - //endregion - - /** - * Error used when the computation of a promise is cancelled. - */ - class CancellationError extends Error { - /** - * @param {string=} opt_msg The cancellation message. - */ - constructor(opt_msg?: string); - } - - interface IThenable { - /** - * Cancels the computation of this promise's value, rejecting the promise in - * the process. This method is a no-op if the promise has already been - * resolved. - * - * @param {(string|Error)=} opt_reason The reason this promise is being - * cancelled. This value will be wrapped in a {@link CancellationError}. - */ - cancel(opt_reason?: string | Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - - /** - * Registers listeners for when this instance is resolved. - * - * @param {?(function(T): (R|IThenable))=} opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param {?(function(*): (R|IThenable))=} opt_errback - * The function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - then(opt_callback?: (value: T) => R | IThenable, opt_errback?: (error: any) => 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; - } - - /** - * 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: (resolve: IFulfilledCallback, reject: IRejectedCallback) => void, opt_flow?: ControlFlow); - - //region Methods - - /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. - * @param {*} reason The reason this promise is being cancelled. If not an - * {@code Error}, one will be created using the value's string - * representation. - */ - cancel(opt_reason?: string | Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - - /** - * Registers listeners for when this instance is resolved. This function most - * overridden by subtypes. - * - * @param opt_callback The function to call if this promise is - * successfully resolved. The function should expect a single argument: the - * promise's resolved value. - * @param opt_errback The function to call if this promise is - * rejected. The function should expect a single argument: the rejection - * reason. - * @return A new promise which will be resolved - * with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => IThenable | 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 for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } catch (ex) { - * console.error(ex); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().catch(function(ex) { - * console.error(ex); - * }); - * - * @param {function(*): (R|IThenable)} errback The - * function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - catch(errback: Function): Promise; - - - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - *
    
    -       *   // Synchronous API:
    -       *   try {
    -       *     doSynchronousWork();
    -       *   } finally {
    -       *     cleanUp();
    -       *   }
    -       *
    -       *   // Asynchronous promise API:
    -       *   doAsynchronousWork().thenFinally(cleanUp);
    -       * 
    - * - * Note: similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - *
    
    -       *   try {
    -       *     throw Error('one');
    -       *   } finally {
    -       *     throw Error('two');  // Hides Error: one
    -       *   }
    -       *
    -       *   webdriver.promise.rejected(Error('one'))
    -       *       .thenFinally(function() {
    -       *         throw Error('two');  // Hides Error: one
    -       *       });
    -       * 
    - * - * - * @param {function(): (R|webdriver.promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled - * with the callback result. - * @template R - */ - thenFinally(callback: Function): Promise; - - //endregion - } - - /** - * Represents a value that will be resolved at some point in the future. This - * class represents the protected 'producer' half of a Promise - each Deferred - * has a {@code promise} property that may be returned to consumers for - * registering callbacks, reserving the ability to resolve the deferred to the - * producer. - * - *

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

    If this Deferred is cancelled, the cancellation reason will be forward to - * the Deferred's canceller function (if provided). The canceller may return a - * truth-y value to override the reason provided for rejection. - * - * @extends {webdriver.promise.Promise} - */ - class Deferred extends Promise { - //region Constructors - - /** - * - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow - * this instance was created under. This should only be provided during - * unit tests. - * @constructor - */ - constructor(opt_flow?: ControlFlow); - - //endregion - - static State_: { - BLOCKED: number; - PENDING: number; - REJECTED: number; - RESOLVED: number; - }; - - //region Properties - - /** - * The consumer promise for this instance. Provides protected access to the - * callback registering functions. - * @type {!webdriver.promise.Promise} - */ - promise: Promise; - - //endregion - - //region Methods - - /** - * Rejects this promise. If the error is itself a promise, this instance will - * be chained to it and be rejected with the error's resolved value. - * @param {*=} opt_error The rejection reason, typically either a - * {@code Error} or a {@code string}. - */ - reject(opt_error?: any): void; - errback(opt_error?: any): void; - - /** - * Resolves this promise with the given value. If the value is itself a - * promise and not a reference to this deferred, this instance will wait for - * it before resolving. - * @param {*=} opt_value The resolved value. - */ - fulfill(opt_value?: T): void; - - /** - * Removes all of the listeners previously registered on this deferred. - * @throws {Error} If this deferred has already been resolved. - */ - removeAll(): void; - - //endregion - } - - interface IControlFlowTimer { - clearInterval: (ms: number) => void; - clearTimeout: (ms: number) => void; - setInterval: (fn: Function, ms: number) => number; - setTimeout: (fn: Function, ms: number) => number; - } - - interface IEventType { - /** 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; - } - - /** - * 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: IEventType; - - /** - * Returns a string representation of this control flow, which is its current - * {@link #getSchedule() schedule}, sans task stack traces. - * @return {string} The string representation of this contorl flow. - * @override - */ - toString(): string; - - /** - * Resets this instance, clearing its queue and removing all event listeners. - */ - reset(): void; - - /** - * Generates an annotated string describing the internal state of this control - * flow, including the currently executing as well as pending tasks. If - * {@code opt_includeStackTraces === true}, the string will include the - * stack trace from when each task was scheduled. - * @param {string=} opt_includeStackTraces Whether to include the stack traces - * from when each task was scheduled. Defaults to false. - * @return {string} String representation of this flow's internal state. - */ - getSchedule(opt_includeStackTraces?: boolean): string; - - /** - * Schedules a task for execution. If there is nothing currently in the - * queue, the task will be executed in the next turn of the event loop. If - * the task function is a generator, the task will be executed using - * {@link webdriver.promise.consume}. - * - * @param {function(): (T|promise.Promise)} fn The function to - * call to start the task. If the function returns a - * {@link webdriver.promise.Promise}, this instance will wait for it to be - * resolved before starting the next task. - * @param {string=} opt_description A description of the task. - * @return {!promise.Promise} A promise that will be resolved - * with the result of the action. - * @template T - */ - execute(fn: () => (T | Promise), opt_description?: string): Promise; - - /** - * Inserts a {@code setTimeout} into the command queue. This is equivalent to - * a thread sleep in a synchronous programming language. - * - * @param {number} ms The timeout delay, in milliseconds. - * @param {string=} opt_description A description to accompany the timeout. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * the result of the action. - */ - timeout(ms: number, opt_description?: string): Promise; - - /** - * Schedules a task that shall wait for a condition to hold. Each condition - * function may return any value, but it will always be evaluated as a boolean. - * - * Condition functions may schedule sub-tasks with this instance, however, - * their execution time will be factored into whether a wait has timed out. - * - * In the event a condition returns a Promise, the polling loop will wait for - * it to be resolved before evaluating whether the condition has been satisfied. - * The resolution time for a promise is factored into whether a wait has timed - * out. - * - * If the condition function throws, or returns a rejected promise, the - * wait task will fail. - * - * If the condition is defined as a promise, the flow will wait for it to - * settle. If the timeout expires before the promise settles, the promise - * returned by this function will be rejected. - * - * If this function is invoked with `timeout === 0`, or the timeout is omitted, - * the flow will wait indefinitely for the condition to be satisfied. - * - * @param {(!promise.Promise|function())} condition The condition to poll, - * or a promise to wait on. - * @param {number=} opt_timeout How long to wait, in milliseconds, for the - * condition to hold before timing out. If omitted, the flow will wait - * indefinitely. - * @param {string=} opt_message An optional error message to include if the - * wait times out; defaults to the empty string. - * @return {!promise.Promise} A promise that will be fulfilled - * when the condition has been satisified. The promise shall be rejected if - * the wait times out waiting for the condition. - * @throws {TypeError} If condition is not a function or promise or if timeout - * is not a number >= 0. - * @template T - */ - wait(condition: Promise | Function, opt_timeout?: number, opt_message?: string): Promise; - } - } - - namespace until { - /** - * Defines a condition to - */ - class Condition { - /** - * @param {string} message A descriptive error message. Should complete the - * sentence 'Waiting [...]' - * @param {function(!webdriver.WebDriver): OUT} fn The condition function to - * evaluate on each iteration of the wait loop. - * @constructor - */ - constructor(message: string, fn: (webdriver: WebDriver) => any); - - /** @return {string} A description of this condition. */ - description(): string; - - /** @type {function(!webdriver.WebDriver): OUT} */ - fn(webdriver: WebDriver): any; - } - - /** - * Creates a condition that will wait until the input driver is able to switch - * to the designated frame. The target frame may be specified as - * - * 1. a numeric index into - * [window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window.frames) - * for the currently selected frame. - * 2. a {@link ./webdriver.WebElement}, which must reference a FRAME or IFRAME - * element on the current page. - * 3. a locator which may be used to first locate a FRAME or IFRAME on the - * current page before attempting to switch to it. - * - * Upon successful resolution of this condition, the driver will be left - * focused on the new frame. - * - * @param {!(number|./webdriver.WebElement|By| - * function(!./webdriver.WebDriver): !./webdriver.WebElement)} frame - * The frame identifier. - * @return {!Condition} A new condition. - */ - function ableToSwitchToFrame(frame: number | WebElement | By | ((webdriver: WebDriver) => WebElement)): Condition; - - /** - * Creates a condition that waits for an alert to be opened. Upon success, the - * returned promise will be fulfilled with the handle for the opened alert. - * - * @return {!Condition} The new condition. - */ - function alertIsPresent(): Condition; - - /** - * Creates a condition that will wait for the given element to be disabled. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isEnabled - */ - function elementIsDisabled(element: WebElement): Condition; - - /** - * Creates a condition that will wait for the given element to be enabled. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isEnabled - */ - function elementIsEnabled(element: WebElement): Condition; - - /** - * Creates a condition that will wait for the given element to be deselected. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isSelected - */ - function elementIsNotSelected(element: WebElement): Condition; - - /** - * Creates a condition that will wait for the given element to be in the DOM, - * yet not visible to the user. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isDisplayed - */ - function elementIsNotVisible(element: WebElement): Condition; - - /** - * Creates a condition that will wait for the given element to be selected. - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isSelected - */ - function elementIsSelected(element: WebElement): Condition; - - /** - * Creates a condition that will wait for the given element to become visible. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isDisplayed - */ - function elementIsVisible(element: WebElement): Condition; - - /** - * Creates a condition that will loop until an element is - * {@link ./webdriver.WebDriver#findElement found} with the given locator. - * - * @param {!(By|Function)} locator The locator to use. - * @return {!until.Condition.} The new condition. - */ - function elementLocated(locator: By | Function): Condition; - - /** - * Creates a condition that will wait for the given element's - * {@link webdriver.WebDriver#getText visible text} to contain the given - * substring. - * - * @param {!webdriver.WebElement} element The element to test. - * @param {string} substr The substring to search for. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#getText - */ - function elementTextContains(element: WebElement, substr: string): Condition; - - /** - * Creates a condition that will wait for the given element's - * {@link webdriver.WebDriver#getText visible text} to match the given - * {@code text} exactly. - * - * @param {!webdriver.WebElement} element The element to test. - * @param {string} text The expected text. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#getText - */ - function elementTextIs(element: WebElement, text: string): Condition; - - /** - * Creates a condition that will wait for the given element's - * {@link webdriver.WebDriver#getText visible text} to match a regular - * expression. - * - * @param {!webdriver.WebElement} element The element to test. - * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition} The new condition. - * @see webdriver.WebDriver#getText - */ - function elementTextMatches(element: WebElement, regex: RegExp): Condition; - - /** - * Creates a condition that will loop until at least one element is - * {@link webdriver.WebDriver#findElement found} with the given locator. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * to use. - * @return {!until.Condition.>} The new - * condition. - */ - function elementsLocated(locator: By | Function): Condition; - - /** - * Creates a condition that will wait for the given element to become stale. An - * element is considered stale once it is removed from the DOM, or a new page - * has loaded. - * - * @param {!webdriver.WebElement} element The element that should become stale. - * @return {!until.Condition} The new condition. - */ - function stalenessOf(element: WebElement): Condition; - - /** - * Creates a condition that will wait for the current page's title to contain - * the given substring. - * - * @param {string} substr The substring that should be present in the page - * title. - * @return {!until.Condition.} The new condition. - */ - function titleContains(substr: string): Condition; - - /** - * Creates a condition that will wait for the current page's title to match the - * given value. - * - * @param {string} title The expected page title. - * @return {!until.Condition} The new condition. - */ - function titleIs(title: string): Condition; - - /** - * Creates a condition that will wait for the current page's title to match the - * given regular expression. - * - * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. - */ - function titleMatches(regex: RegExp): Condition; - } - - interface ILocation { - x: number; - y: number; - } - - interface ISize { - width: number; - height: number; - } - - interface IButton { - LEFT: string; - MIDDLE: string; - RIGHT: string; + code(): 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 - * + * The base WebDriver error type. This error type is only used directly when a + * more appropriate category is not defined for the offending error. + */ + class WebDriverError extends IError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An attempt was made to select an element that cannot be selected. + */ + class ElementNotSelectableError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element command could not be completed because the element is not visible + * on the page. + */ + class ElementNotVisibleError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The arguments passed to a command are either invalid or malformed. + */ + class InvalidArgumentError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An illegal attempt was made to set a cookie under a different domain than + * the current page. + */ + class InvalidCookieDomainError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The coordinates provided to an interactions operation are invalid. + */ + class InvalidElementCoordinatesError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element command could not be completed because the element is in an + * invalid state, e.g. attempting to click an element that is no longer attached + * to the document. + */ + class InvalidElementStateError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Argument was an invalid selector. + */ + class InvalidSelectorError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Occurs when a command is directed to a session that does not exist. + */ + class NoSuchSessionError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An error occurred while executing JavaScript supplied by the user. + */ + class JavascriptError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The target for mouse interaction is not in the browser’s viewport and cannot + * be brought into that viewport. + */ + class MoveTargetOutOfBoundsError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An attempt was made to operate on a modal dialog when one was not open. + */ + class NoSuchAlertError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element could not be located on the page using the given search + * parameters. + */ + class NoSuchElementError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to switch to a frame could not be satisfied because the frame + * could not be found. + */ + class NoSuchFrameError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to switch to a window could not be satisfied because the window + * could not be found. + */ + class NoSuchWindowError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A script did not complete before its timeout expired. + */ + class ScriptTimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A new session could not be created. + */ + class SessionNotCreatedError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element command failed because the referenced element is no longer + * attached to the DOM. + */ + class StaleElementReferenceError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An operation did not completErrorCodee before its timeout expired. + */ + class TimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to set a cookie’s value could not be satisfied. + */ + class UnableToSetCookieError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A screen capture operation was not possible. + */ + class UnableToCaptureScreenError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A modal dialog was open, blocking this operation. + */ + class UnexpectedAlertOpenError extends WebDriverError { + /** + * @param {string=} opt_error the error message, if any. + * @param {string=} opt_text the text of the open dialog, if available. + */ + constructor(opt_error?: string, opt_text?: string); + + /** + * @return {(string|undefined)} The text displayed with the unhandled alert, + * if available. + */ + getAlertText(): string; + } + + /** + * A command could not be executed because the remote end is not aware of it. + */ + class UnknownCommandError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The requested command matched a known URL but did not match an method for + * that URL. + */ + class UnknownMethodError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Reports an unsupport operation. + */ + class UnsupportedOperationError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } +} + +export namespace logging { + + /** + * A hash describing log preferences. + * @typedef {Object.} + */ + class Preferences { + setLevel(type: string, 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 Button: IButton; - - 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 - * keys or strings, appends each of the values to a string, - * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns - * the resulting 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. - */ - chord: (...var_args: Array) => string; - } + var Type: IType; /** - * 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 + * Defines a message level that may be used to control logging output. * - * @enum {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(); - * - */ - class ActionSequence { - - //region Constructors - - /** - * @param {!webdriver.WebDriver} driver The driver instance to use. - * @constructor - */ - constructor(driver: WebDriver); - - //endregion - - //region Methods - - /** - * Executes this action sequence. - * @return {!webdriver.promise.Promise} A promise that will be resolved once - * this sequence has completed. - */ - perform(): webdriver.promise.Promise; - - /** - * Moves the mouse. The location to move to may be specified in terms of the - * mouse's current location, an offset relative to the top-left corner of an - * element, or an element (in which case the middle of the element is used). - * - * @param {(!./webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, as either another WebElement or an offset in - * pixels. - * @param {{x: number, y: number}=} opt_offset If the target {@code location} - * is defined as a {@link ./webdriver.WebElement}, this parameter defines - * an offset within that element. The offset should be specified in pixels - * relative to the top-left corner of the element's bounding box. If - * omitted, the element's center will be used as the target offset. - * @return {!ActionSequence} A self reference. - */ - mouseMove(location: WebElement | ILocation, opt_offset?: ILocation): ActionSequence; - - /** - * Presses a mouse button. The mouse button will not be released until - * {@link #mouseUp} is called, regardless of whether that call is made in this - * sequence or another. The behavior for out-of-order events (e.g. mouseDown, - * click) is undefined. - * - * If an element is provided, the mouse will first be moved to the center - * of that element. This is equivalent to: - * - * sequence.mouseMove(element).mouseDown() - * - * Warning: this method currently only supports the left mouse button. See - * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either - * the element to interact with or the button to click with. - * Defaults to {@link input.Button.LEFT} if neither an element nor - * button is specified. - * @param {input.Button=} opt_button The button to use. Defaults to - * {@link input.Button.LEFT}. Ignored if a button is provided as the - * first argument. - * @return {!ActionSequence} A self reference. - */ - mouseDown(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; - - /** - * Releases a mouse button. Behavior is undefined for calling this function - * without a previous call to {@link #mouseDown}. - * - * If an element is provided, the mouse will first be moved to the center - * of that element. This is equivalent to: - * - * sequence.mouseMove(element).mouseUp() - * - * Warning: this method currently only supports the left mouse button. See - * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either - * the element to interact with or the button to click with. - * Defaults to {@link input.Button.LEFT} if neither an element nor - * button is specified. - * @param {input.Button=} opt_button The button to use. Defaults to - * {@link input.Button.LEFT}. Ignored if a button is provided as the - * first argument. - * @return {!ActionSequence} A self reference. - */ - mouseUp(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; - - /** - * Convenience function for performing a 'drag and drop' manuever. The target - * element may be moved to the location of another element, or by an offset (in - * pixels). - * - * @param {!./webdriver.WebElement} element The element to drag. - * @param {(!./webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, either as another WebElement or an offset in - * pixels. - * @return {!ActionSequence} A self reference. - */ - dragAndDrop(element: WebElement, location: WebElement | ILocation): ActionSequence; - - /** - * Clicks a mouse button. - * - * If an element is provided, the mouse will first be moved to the center - * of that element. This is equivalent to: - * - * sequence.mouseMove(element).click() - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either - * the element to interact with or the button to click with. - * Defaults to {@link input.Button.LEFT} if neither an element nor - * button is specified. - * @param {input.Button=} opt_button The button to use. Defaults to - * {@link input.Button.LEFT}. Ignored if a button is provided as the - * first argument. - * @return {!ActionSequence} A self reference. - */ - click(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; - - /** - * Double-clicks a mouse button. - * - * If an element is provided, the mouse will first be moved to the center of - * that element. This is equivalent to: - * - * sequence.mouseMove(element).doubleClick() - * - * Warning: this method currently only supports the left mouse button. See - * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either - * the element to interact with or the button to click with. - * Defaults to {@link input.Button.LEFT} if neither an element nor - * button is specified. - * @param {input.Button=} opt_button The button to use. Defaults to - * {@link input.Button.LEFT}. Ignored if a button is provided as the - * first argument. - * @return {!ActionSequence} A self reference. - */ - doubleClick(opt_elementOrButton?: WebElement | string, opt_button?: string): 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 targeted at the currently focused element. - * - * @param {...(string|!input.Key|!Array<(string|!input.Key)>)} var_args - * The keys to type. - * @return {!ActionSequence} A self reference. - * @throws {Error} If the key is not a valid modifier key. - */ - sendKeys(...var_args: Array>): ActionSequence; - - //endregion - } - - - /** - * Class for defining sequences of user touch interactions. Each sequence - * will not be executed until {@link #perform} is called. - * - * Example: - * - * new webdriver.TouchSequence(driver). - * tapAndHold({x: 0, y: 0}). - * move({x: 3, y: 4}). - * release({x: 10, y: 10}). - * perform(); - */ - class TouchSequence { - /* - * @param {!webdriver.WebDriver} driver The driver instance to use. - * @constructor - */ - constructor(driver: WebDriver); - - - /** - * Executes this action sequence. - * @return {!webdriver.promise.Promise} A promise that will be resolved once - * this sequence has completed. - */ - perform(): webdriver.promise.Promise; - - - /** - * Taps an element. - * - * @param {!webdriver.WebElement} elem The element to tap. - * @return {!webdriver.TouchSequence} A self reference. - */ - tap(elem: WebElement): TouchSequence; - - - /** - * Double taps an element. - * - * @param {!webdriver.WebElement} elem The element to double tap. - * @return {!webdriver.TouchSequence} A self reference. - */ - doubleTap(elem: WebElement): TouchSequence; - - - /** - * Long press on an element. - * - * @param {!webdriver.WebElement} elem The element to long press. - * @return {!webdriver.TouchSequence} A self reference. - */ - longPress(elem: WebElement): TouchSequence; - - - /** - * Touch down at the given location. - * - * @param {{ x: number, y: number }} location The location to touch down at. - * @return {!webdriver.TouchSequence} A self reference. - */ - tapAndHold(location: ILocation): TouchSequence; - - - /** - * Move a held {@linkplain #tapAndHold touch} to the specified location. - * - * @param {{x: number, y: number}} location The location to move to. - * @return {!webdriver.TouchSequence} A self reference. - */ - move(location: ILocation): TouchSequence; - - - /** - * Release a held {@linkplain #tapAndHold touch} at the specified location. - * - * @param {{x: number, y: number}} location The location to release at. - * @return {!webdriver.TouchSequence} A self reference. - */ - release(location: ILocation): TouchSequence; - - - /** - * Scrolls the touch screen by the given offset. - * - * @param {{x: number, y: number}} offset The offset to scroll to. - * @return {!webdriver.TouchSequence} A self reference. - */ - scroll(offset: IOffset): TouchSequence; - - /** - * Scrolls the touch screen, starting on `elem` and moving by the specified - * offset. - * - * @param {!webdriver.WebElement} elem The element where scroll starts. - * @param {{x: number, y: number}} offset The offset to scroll to. - * @return {!webdriver.TouchSequence} A self reference. - */ - scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; - - /** - * Flick, starting anywhere on the screen, at speed xspeed and yspeed. - * - * @param {{xspeed: number, yspeed: number}} speed The speed to flick in each - direction, in pixels per second. - * @return {!webdriver.TouchSequence} A self reference. - */ - flick(speed: ISpeed): TouchSequence; - - /** - * Flick starting at elem and moving by x and y at specified speed. - * - * @param {!webdriver.WebElement} elem The element where flick starts. - * @param {{x: number, y: number}} offset The offset to flick to. - * @param {number} speed The speed to flick at in pixels per second. - * @return {!webdriver.TouchSequence} A self reference. - */ - flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence; - } - - interface IOffset { - x: number; - y: number; - } - - interface ISpeed { - xspeed: number; - yspeed: number; - } - - /** - * Represents a modal dialog such as {@code alert}, {@code confirm}, or - * {@code prompt}. Provides functions to retrieve the message displayed with - * the alert, accept or dismiss the alert, and set the response text (in the - * case of {@code prompt}). - */ - class Alert { - /** - * @param {!WebDriver} driver The driver controlling the browser this alert - * is attached to. - * @param {string} text The message text displayed with this alert. - */ - constructor(driver: WebDriver, text: string); - - //region Methods - - /** - * Retrieves the message text displayed with this alert. For instance, if the - * alert were opened with alert('hello'), then this would return 'hello'. - * @return {!webdriver.promise.Promise} A promise that will be resolved to the - * text displayed with this alert. - */ - getText(): webdriver.promise.Promise; - - /** - * Sets the username and password in an alert prompting for credentials (such - * as a Basic HTTP Auth prompt). This method will implicitly - * {@linkplain #accept() submit} the dialog. - * - * @param {string} username The username to send. - * @param {string} password The password to send. - * @return {!promise.Promise} A promise that will be resolved when this - * command has completed. - */ - authenticateAs(username: string, password: string): webdriver.promise.Promise; - - /** - * Accepts this alert. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * this command has completed. - */ - accept(): webdriver.promise.Promise; - - /** - * Dismisses this alert. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * this command has completed. - */ - dismiss(): webdriver.promise.Promise; - - /** - * Sets the response text on this alert. This command will return an error if - * the underlying alert does not support response text (e.g. window.alert and - * window.confirm). - * @param {string} text The text to set. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * this command has completed. - */ - sendKeys(text: string): webdriver.promise.Promise; - - //endregion - - } - - /** - * AlertPromise is a promise that will be fulfilled with an Alert. This promise - * serves as a forward proxy on an Alert, allowing calls to be scheduled - * directly on this instance before the underlying Alert has been fulfilled. In - * other words, the following two statements are equivalent: - * - * driver.switchTo().alert().dismiss(); - * driver.switchTo().alert().then(function(alert) { - * return alert.dismiss(); - * }); - * - * @implements {promise.Thenable.} * @final */ - class AlertPromise extends Alert implements webdriver.promise.IThenable{ + class Level { + name_: string; + value_: number; /** - * @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. + * @param {string} name the level's name. + * @param {number} level the level's numeric value. */ - constructor(driver: WebDriver, alert: webdriver.promise.Promise); + constructor(name: string, level: number); - //region Methods + /** @override */ + toString(): string; + + /** This logger's name. */ + name: string; + + /** The numeric log level. */ + value: number; + + /** + * Indicates no log messages should be recorded. + * @const + */ + static OFF: Level; + /** + * Log messages with a level of `1000` or higher. + * @const + */ + static SEVERE: Level; + /** + * Log messages with a level of `900` or higher. + * @const + */ + static WARNING: Level; + /** + * Log messages with a level of `800` or higher. + * @const + */ + static INFO: Level; + /** + * Log messages with a level of `700` or higher. + * @const + */ + static DEBUG: Level; + /** + * Log messages with a level of `500` or higher. + * @const + */ + static FINE: Level; + /** + * Log messages with a level of `400` or higher. + * @const + */ + static FINER: Level; + /** + * Log messages with a level of `300` or higher. + * @const + */ + static FINEST: Level; + /** + * Indicates all log messages should be recorded. + * @const + */ + static ALL: Level; + } + + /** + * Converts a level name or value to a {@link logging.Level} value. + * If the name/value is not recognized, {@link logging.Level.ALL} + * will be returned. + * @param {(number|string)} nameOrValue The log level name, or value, to + * convert . + * @return {!logging.Level} The converted level. + */ + function getLevel(nameOrValue: string | number): Level; + + interface IEntryJSON { + level: string; + message: string; + timestamp: number; + type: string; + } + + /** + * A single log entry. + */ + class Entry { + /** + * @param {(!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 | IType); + + /** @type {!logging.Level} */ + level: Level; + + /** @type {string} */ + message: string; + + /** @type {number} */ + timestamp: number; + + /** @type {string} */ + type: string; + + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + } + + /** + * An object used to log debugging messages. Loggers use a hierarchical, + * dot-separated naming scheme. For instance, 'foo' is considered the parent of + * the 'foo.bar' and an ancestor of 'foo.bar.baz'. + * + * Each logger may be assigned a {@linkplain #setLevel log level}, which + * controls which level of messages will be reported to the + * {@linkplain #addHandler handlers} attached to this instance. If a log level + * is not explicitly set on a logger, it will inherit its parent. + * + * This class should never be directly instantiated. Instead, users should + * obtain logger references using the {@linkplain ./logging.getLogger() + * getLogger()} function. + * + * @final + */ + class Logger { + /** + * @param {string} name the name of this logger. + * @param {Level=} opt_level the initial level for this logger. + */ + constructor(name: string, opt_level?: Level); + + /** @private {string} */ + name_: string; + /** @private {Level} */ + level_: Level; + /** @private {Logger} */ + parent_: Logger; + /** @private {Set} */ + handlers_: any; + + /** @return {string} the name of this logger. */ + getName(): string; + + /** + * @param {Level} level the new level for this logger, or `null` if the logger + * should inherit its level from its parent logger. + */ + setLevel(level: Level): void; + + /** @return {Level} the log level for this logger. */ + getLevel(): Level; + + /** + * @return {!Level} the effective level for this logger. + */ + getEffectiveLevel(): Level; + + /** + * @param {!Level} level the level to check. + * @return {boolean} whether messages recorded at the given level are loggable + * by this instance. + */ + isLoggable(level: Level): boolean; + + /** + * Adds a handler to this logger. The handler will be invoked for each message + * logged with this instance, or any of its descendants. + * + * @param {function(!Entry)} handler the handler to add. + */ + addHandler(handler: any): void; + + /** + * Removes a handler from this logger. + * + * @param {function(!Entry)} handler the handler to remove. + * @return {boolean} whether a handler was successfully removed. + */ + removeHandler(handler: any): void; + + /** + * Logs a message at the given level. The message may be defined as a string + * or as a function that will return the message. If a function is provided, + * it will only be invoked if this logger's + * {@linkplain #getEffectiveLevel() effective log level} includes the given + * `level`. + * + * @param {!Level} level the level at which to log the message. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + log(level: Level, loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.SEVERE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + severe(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.WARNING} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + warning(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.INFO} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + info(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.DEBUG} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + debug(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.FINE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + fine(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.FINER} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finer(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.FINEST} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finest(loggable: string | Function): void; + } + + /** + * Maintains a collection of loggers. + * + * @final + */ + class LogManager { + /** + * Retrieves a named logger, creating it in the process. This function will + * implicitly create the requested logger, and any of its parents, if they + * do not yet exist. + * + * @param {string} name the logger's name. + * @return {!Logger} the requested logger. + */ + getLogger(name: string): Logger; + + /** + * Creates a new logger. + * + * @param {string} name the logger's name. + * @param {!Logger} parent the logger's parent. + * @return {!Logger} the new logger. + * @private + */ + createLogger_(name: string, parent: Logger): Logger; + } +} + +export namespace promise { + // region Functions + + /** + * Given an array of promises, will return a promise that will be fulfilled + * with the fulfillment values of the input array's values. If any of the + * input array's promises are rejected, the returned promise will be rejected + * with the same reason. + * + * @param {!Array<(T|!ManagedPromise)>} arr An array of + * promises to wait on. + * @return {!ManagedPromise} A promise that is + * fulfilled with an array containing the fulfilled values of the + * input array, or rejected with the same reason as the first + * rejected value. + * @template T + */ + function all(arr: Array>): Promise; + + /** + * Invokes the appropriate callback function as soon as a promised + * {@code value} is resolved. This function is similar to + * {@link 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 {!promise.ControlFlow} The currently active control flow. + */ + function controlFlow(): ControlFlow; + + /** + * Creates a new control flow. The provided callback will be invoked as the + * first task within the new flow, with the flow as its sole argument. Returns + * a promise that resolves to the callback result. + * @param {function(!ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!ManagedPromise} A promise that resolves to the callback + * result. + */ + function createFlow(callback: (flow: ControlFlow) => R): Promise; + + /** + * Determines whether a {@code value} should be treated as a promise. + * Any object whose 'then' property is a function will be considered a promise. + * + * @param {*} value The value to test. + * @return {boolean} Whether the value is a promise. + */ + function isPromise(value: any): boolean; + + /** + * Tests is a function is a generator. + * @param {!Function} fn The function to test. + * @return {boolean} Whether the function is a generator. + */ + function isGenerator(fn: Function): boolean; + + /** + * Creates a promise that will be resolved at a set time in the future. + * @param {number} ms The amount of time, in milliseconds, to wait before + * resolving the promise. + * @return {!ManagedPromise} The promise. + */ + function delayed(ms: number): Promise; + + /** + * Calls a function for each element in an array, and if the function returns + * true adds the element to a new array. + * + * If the return value of the filter function is a promise, this function + * will wait for it to be fulfilled before determining whether to insert the + * element into the new array. + * + * If the filter function throws or returns a rejected promise, the promise + * returned by this function will be rejected with the same reason. Only the + * first failure will be reported; all subsequent errors will be silently + * ignored. + * + * @param {!(Array|ManagedPromise>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array): ( + * boolean|ManagedPromise)} fn The function + * to call for each element in the array. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function filter(arr: T[] | Promise, fn: (element: T, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; + + /** + * Creates a new deferred object. + * @return {!promise.Deferred} The new deferred object. + */ + function defer(): Deferred; + + /** + * Creates a promise that has been resolved with the given value. + * @param {T=} opt_value The resolved value. + * @return {!ManagedPromise} The resolved promise. + * @template T + */ + function fulfilled(opt_value?: T): Promise; + + /** + * Calls a function for each element in an array and inserts the result into a + * new array, which is used as the fulfillment value of the promise returned + * by this function. + * + * If the return value of the mapping function is a promise, this function + * will wait for it to be fulfilled before inserting it into the new array. + * + * If the mapping function throws or returns a rejected promise, the + * promise returned by this function will be rejected with the same reason. + * Only the first failure will be reported; all subsequent errors will be + * silently ignored. + * + * @param {!(Array|ManagedPromise>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array): ?} fn The + * function to call for each element in the array. This function should + * expect three arguments (the element, the index, and the array itself. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function map(arr: T[] | Promise, fn: (self: any, type: any, 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 + */ + function rejected(opt_reason?: any): Promise; + + /** + * Wraps a function that expects a node-style callback as its final + * argument. This callback expects two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * The callback will the resolve or reject the returned promise, based on its + * arguments. + * @param {!Function} fn The function to wrap. + * @param {...?} var_args The arguments to apply to the function, excluding the + * final callback. + * @return {!ManagedPromise} A promise that will be resolved with the + * result of the provided function's callback. + */ + function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; + + /** + * Consumes a {@code GeneratorFunction}. Each time the generator yields a + * promise, this function will wait for it to be fulfilled before feeding the + * fulfilled value back into {@code next}. Likewise, if a yielded promise is + * rejected, the rejection error will be passed to {@code throw}. + * + * __Example 1:__ the Fibonacci Sequence. + * + * promise.consume(function* fibonacci() { + * var n1 = 1, n2 = 1; + * for (var i = 0; i < 4; ++i) { + * var tmp = yield n1 + n2; + * n1 = n2; + * n2 = tmp; + * } + * return n1 + n2; + * }).then(function(result) { + * console.log(result); // 13 + * }); + * + * __Example 2:__ a generator that throws. + * + * promise.consume(function* () { + * yield promise.delayed(250).then(function() { + * throw Error('boom'); + * }); + * }).catch(function(e) { + * console.log(e.toString()); // Error: boom + * }); + * + * @param {!Function} generatorFn The generator function to execute. + * @param {Object=} opt_self The object to use as 'this' when invoking the + * initial generator. + * @param {...*} var_args Any arguments to pass to the initial generator. + * @return {!ManagedPromise} A promise that will resolve to the + * generator's final result. + * @throws {TypeError} If the given function is not a generator. + */ + function consume(generatorFn: Function, opt_self?: any, ...var_args: any[]): Promise; + + /** + * Registers an observer on a promised {@code value}, returning a new promise + * that will be resolved when the value is. If {@code value} is not a promise, + * then the return promise will be immediately resolved. + * @param {*} value The value to observe. + * @param {Function=} opt_callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + * @return {!ManagedPromise} A new promise. + */ + function when(value: T | Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + + /** + * Returns a promise that will be resolved with the input value in a + * fully-resolved state. If the value is an array, each element will be fully + * resolved. Likewise, if the value is an object, all keys will be fully + * resolved. In both cases, all nested arrays and objects will also be + * fully resolved. All fields are resolved in place; the returned promise will + * resolve on {@code value} and not a copy. + * + * Warning: This function makes no checks against objects that contain + * cyclical references: + * + * var value = {}; + * value['self'] = value; + * promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!ManagedPromise} A promise for a fully resolved version + * of the input value. + */ + function fullyResolved(value: any): Promise; + + /** + * Changes the default flow to use when no others are active. + * @param {!ControlFlow} flow The new default flow. + * @throws {Error} If the default flow is not currently active. + */ + function setDefaultFlow(flow: ControlFlow): void; + + // endregion + + /** + * Error used when the computation of a promise is cancelled. + */ + class CancellationError extends Error { + /** + * @param {string=} opt_msg The cancellation message. + */ + constructor(opt_msg?: string); + } + + interface IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. + * + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. + */ + cancel(opt_reason?: string | Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. + * + * @param {?(function(T): (R|IThenable))=} opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + then(opt_callback?: (value: T) => R | IThenable, opt_errback?: (error: any) => 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; + } + + /** + * 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 | undefined): 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: (resolve: IFulfilledCallback, reject: IRejectedCallback) => void, opt_flow?: ControlFlow); + + // region Methods /** * Cancels the computation of this promise's value, rejecting the promise in the @@ -2120,7 +1034,7 @@ declare namespace webdriver { * @return A new promise which will be resolved * with the result of the invoked callback. */ - then(opt_callback?: Function, opt_errback?: Function): webdriver.promise.Promise; + then(opt_callback?: (value: T) => IThenable | R, opt_errback?: (error: any) => any): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous @@ -2139,14 +1053,14 @@ declare namespace webdriver { * }); * * - * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * @param {function(*): (R|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 + * @return {!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; + thenCatch(errback: (error: any) => any): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous @@ -2171,7 +1085,7 @@ declare namespace webdriver { * resolved with the result of the invoked callback. * @template R */ - catch(errback: Function): webdriver.promise.Promise; + catch(errback: Function): Promise; /** @@ -2200,2854 +1114,3935 @@ declare namespace webdriver { * throw Error('two'); // Hides Error: one * } * - * webdriver.promise.rejected(Error('one')) + * promise.rejected(Error('one')) * .thenFinally(function() { * throw Error('two'); // Hides Error: one * }); * * * - * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * @param {function(): (R|promise.Promise.)} callback The function * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * @return {!promise.Promise.} A promise that will be fulfilled * with the callback result. * @template R */ - thenFinally(callback: Function): webdriver.promise.Promise; - } + thenFinally(callback: Function): Promise; - /** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ - class UnhandledAlertError extends webdriver.error.UnexpectedAlertOpenError { + // endregion } /** - * Recognized browser names. - * @enum {string} + * 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 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 {promise.Promise} */ - interface IBrowser { - ANDROID: string; - CHROME: string; - EDGE: string; - FIREFOX: string; - IE: string; - INTERNET_EXPLORER: string; - IPAD: string; - IPHONE: string; - OPERA: string; - PHANTOM_JS: string; - SAFARI: string; - HTMLUNIT: string; + class Deferred extends Promise { + // region Constructors + + /** + * + * @param {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 {!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 } - var Browser: IBrowser; + interface IControlFlowTimer { + clearInterval: (ms: number) => void; + clearTimeout: (ms: number) => void; + setInterval: (fn: Function, ms: number) => number; + setTimeout: (fn: Function, ms: number) => number; + } - interface ProxyConfig { - proxyType: string; - proxyAutoconfigUrl?: string; - ftpProxy?: string; - httpProxy?: string; - sslProxy?: string; - noProxy?: string; + interface IEventType { + /** 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; } /** - * 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. + * 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. * - * - {@code SELENIUM_BROWSER}: defines the target browser in the form - * {@code browser[:version][:platform]}. + * Each task scheduled within this flow may return a + * {@link 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. * - * - {@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}. + * Tasks and each callback registered on a {@link 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. * - * - {@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. + * Each time a ControlFlow empties its task queue, it will fire an + * {@link 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 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. * - * 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 + * @extends {EventEmitter} + * @final */ - class Builder { - - //region Constructors - + class ControlFlow extends EventEmitter { /** * @constructor */ constructor(); - //endregion - - //region Methods + /** + * Events that may be emitted by an {@link promise.ControlFlow}. + * @enum {string} + */ + static EventType: IEventType; /** - * 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. + * 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 */ - disableEnvironmentOverrides(): Builder; - - /** - * Creates a new WebDriver client based on this builder's current - * configuration. - * - * While this method will immediately return a new WebDriver instance, any - * commands issued against it will be deferred until the associated browser - * has been fully initialized. Users may call {@link #buildAsync()} to obtain - * a promise that will not be fulfilled until the browser has been created - * (the difference is purely in style). - * - * @return {!webdriver.WebDriver} A new WebDriver instance. - * @throws {Error} If the current configuration is invalid. - * @see #buildAsync() - */ - build(): WebDriver; - - /** - * Creates a new WebDriver client based on this builder's current - * configuration. This method returns a promise that will not be fulfilled - * until the new browser session has been fully initialized. - * - * __Note:__ this method is purely a convenience wrapper around - * {@link #build()}. - * - * @return {!promise.Promise} A promise that will be - * fulfilled with the newly created WebDriver instance once the browser - * has been fully initialized. - * @see #build() - */ - buildAsync(): webdriver.promise.Promise; - - /** - * Configures the target browser for clients created by this instance. - * Any calls to {@link #withCapabilities} after this function will - * overwrite these settings. - * - *

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

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

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

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

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

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

    
    -   *   driver.get('http://www.google.com');
    -   *   var searchForm = driver.findElement(By.tagName('form'));
    -   *   var searchBox = searchForm.findElement(By.name('q'));
    -   *   searchBox.sendKeys('webdriver');
    -   * 
    - * - * The WebElement is implemented as a promise for compatibility with the promise - * API. It will always resolve itself when its internal state has been fully - * resolved and commands may be issued against the element. This can be used to - * catch errors when an element cannot be located on the page: - *
    
    -   *   driver.findElement(By.id('not-there')).then(function(element) {
    -   *     alert('Found an element that was not expected to be there!');
    -   *   }, function(error) {
    -   *     alert('The element was not found, as expected');
    -   *   });
    -   * 
    - */ - interface IWebElement { - //region Methods - - /** - * Schedules a command to click on this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the click command has completed. - */ - click(): webdriver.promise.Promise; - - /** - * Schedules a command to type a sequence on the DOM element represented by - * this instance. - * - * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is - * processed in the key sequence, 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 input.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', - * Key.CONTROL, 'a', Key.NULL, - * 'now text is'); - * // Alternatively: - * element.sendKeys('text was', - * Key.chord(Key.CONTROL, 'a'), - * 'now text is'); - * - * - The end of the key sequence 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 analogous 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 input.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 - * punctuation keys will be synthesized according to a standard QWERTY en-us - * keyboard layout. - * - * @param {...(number|string|!IThenable<(number|string)>)} var_args The - * sequence of keys to type. Number keys may be referenced numerically or - * by string (1 or '1'). 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. The 'style' attribute is converted as best can be to a - * text representation with a trailing semi-colon. The following are deemed to - * be 'boolean' attributes and will be returned as thus: - * - *

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

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

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

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

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

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

    -     * var link = element.findElement(firstVisibleLink);
    -     *
    -     * function firstVisibleLink(element) {
    -     *   var links = element.findElements(By.tagName('a'));
    -     *   return webdriver.promise.filter(links, function(link) {
    -     *     return links.isDisplayed();
    -     *   }).then(function(visibleLinks) {
    -     *     return visibleLinks[0];
    -     *   });
    -     * }
    -     * 
    - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the element. - * @return {!webdriver.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locator: By | Function): WebElementPromise; - - /** - * Schedules a command to test if there is at least one descendant of this - * element that matches the given search criteria. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the element. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with whether an element could be located on the page. - */ - isElementPresent(locator: By | Function): webdriver.promise.Promise; - - /** - * Schedules a command to find all of the descendants of this element that - * match the given search criteria. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the elements. - * @return {!webdriver.promise.Promise.>} A - * promise that will resolve to an array of WebElements. - */ - findElements(locator: By | Function): webdriver.promise.Promise; - } - - /** - * Defines an object that can be asynchronously serialized to its WebDriver - * wire representation. - * - * @constructor - * @template T - */ - interface Serializable { - /** - * Returns either this instance's serialized represention, if immediately - * available, or a promise for its serialized representation. This function is - * conceptually equivalent to objects that have a {@code toJSON()} property, - * except the serialize() result may be a promise or an object containing a - * promise (which are not directly JSON friendly). - * - * @return {!(T|IThenable.)} This instance's serialized wire format. - */ - serialize(): T | webdriver.promise.IThenable; - } - - /** - * Represents a DOM element. WebElements can be found by searching from the - * document root using a {@link webdriver.WebDriver} instance, or by searching - * under another WebElement: - * - * driver.get('http://www.google.com'); - * var searchForm = driver.findElement(By.tagName('form')); - * var searchBox = searchForm.findElement(By.name('q')); - * searchBox.sendKeys('webdriver'); - * - * The WebElement is implemented as a promise for compatibility with the promise - * API. It will always resolve itself when its internal state has been fully - * resolved and commands may be issued against the element. This can be used to - * catch errors when an element cannot be located on the page: - * - * driver.findElement(By.id('not-there')).then(function(element) { - * alert('Found an element that was not expected to be there!'); - * }, function(error) { - * alert('The element was not found, as expected'); - * }); - * - * @extends {webdriver.Serializable.} - */ - class WebElement implements Serializable { - /** - * @param {!WebDriver} driver the parent WebDriver instance for this element. - * @param {(!IThenable|string)} id The server-assigned opaque ID for - * the underlying DOM element. - */ - constructor(driver: webdriver.WebDriver, id: webdriver.promise.Promise | string); - - /** - * @param {string} id The raw ID. - * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key. - * @return {!Object} The element ID for use with WebDriver's wire protocol. - */ - static buildId(id: string, opt_noLegacy?: boolean): Object; - - /** - * Extracts the encoded WebElement ID from the object. - * - * @param {?} obj The object to extract the ID from. - * @return {string} the extracted ID. - * @throws {TypeError} if the object is not a valid encoded ID. - */ - static extractId(obj: IWebElementId): string; - - /** - * @param {?} obj the object to test. - * @return {boolean} whether the object is a valid encoded WebElement ID. - */ - static isId(obj: IWebElementId): boolean; - - /** - * Compares two WebElements for equality. - * - * @param {!WebElement} a A WebElement. - * @param {!WebElement} b A WebElement. - * @return {!promise.Promise} A promise that will be - * resolved to whether the two WebElements are equal. - */ - static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; - - /** - * @return {!webdriver.WebDriver} The parent driver for this instance. - */ - getDriver(): webdriver.WebDriver; - - /** - * @return {!promise.Promise} A promise that resolves to - * the server-assigned opaque ID assigned to this element. - */ - getId(): webdriver.promise.Promise; - - /** - * @deprecated Use {@link #getId()} instead. - */ - getRawId(): any; - - /** - * Schedule a command to find a descendant of this element. If the element - * cannot be found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will - * be returned by the driver. Unlike other commands, this error cannot be - * suppressed. In other words, scheduling a command to find an element doubles - * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@link #isElementPresent} instead. - * - * The search criteria for an element may be defined using one of the - * factories in the {@link webdriver.By} namespace, or as a short-hand - * {@link webdriver.By.Hash} object. For example, the following two statements - * are equivalent: - * - * var e1 = element.findElement(By.id('foo')); - * var e2 = element.findElement({id:'foo'}); - * - * You may also provide a custom locator function, which takes as input - * this WebDriver instance and returns a {@link webdriver.WebElement}, or a - * promise that will resolve to a WebElement. For example, to find the first - * visible link on a page, you could write: - * - * var link = element.findElement(firstVisibleLink); - * - * function firstVisibleLink(element) { - * var links = element.findElements(By.tagName('a')); - * return webdriver.promise.filter(links, function(link) { - * return links.isDisplayed(); - * }).then(function(visibleLinks) { - * return visibleLinks[0]; - * }); - * } - * - * @param {!(by.By|Function)} locator The locator strategy to use when - * searching for the element. - * @return {!WebElementPromise} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locator: By | Function): WebElementPromise; - - /** - * Schedules a command to test if there is at least one descendant of this - * element that matches the given search criteria. - * - * @param {!(by.By|Function)} locator The locator strategy to use when - * searching for the element. - * @return {!promise.Promise} A promise that will be - * resolved with whether an element could be located on the page. - * @deprecated This method will be removed in Selenium 3.0 for consistency - * with the other Selenium language bindings. This method is equivalent - * to - * - * element.findElements(locator).then(e => !!e.length); - */ - isElementPresent(locator: By | Function): webdriver.promise.Promise; - - /** - * Schedules a command to find all of the descendants of this element that - * match the given search criteria. - * - * @param {!(by.By|Function)} locator The locator strategy to use when - * searching for the element. - * @return {!promise.Promise>} A - * promise that will resolve to an array of WebElements. - */ - findElements(locator: By | Function): webdriver.promise.Promise; - - /** - * Schedules a command to click on this element. - * @return {!webdriver.promise.Promise.} A promise that will be resolved - * when the click command has completed. - */ - click(): webdriver.promise.Promise; - - /** - * Schedules a command to type a sequence on the DOM element represented by this - * promsieinstance. - * - * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is - * processed in the keysequence, that key state is toggled until one of the - * following occurs: - * - * - The modifier key is encountered again in the sequence. At this point the - * state of the key is toggled (along with the appropriate keyup/down events). - * - The {@link webdriver.Key.NULL} key is encountered in the sequence. When - * this key is encountered, all modifier keys current in the down state are - * released (with accompanying keyup events). The NULL key can be used to - * simulate common keyboard shortcuts: - * - * element.sendKeys('text was', - * webdriver.Key.CONTROL, 'a', webdriver.Key.NULL, - * 'now text is'); - * // Alternatively: - * element.sendKeys('text was', - * webdriver.Key.chord(webdriver.Key.CONTROL, 'a'), - * 'now text is'); - * - * - The end of the keysequence is encountered. When there are no more keys - * to type, all depressed modifier keys are released (with accompanying keyup - * events). - * - * If this element is a file input ({@code }), the - * specified key sequence should specify the path to the file to attach to - * the element. This is analgous to the user clicking 'Browse...' and entering - * the path into the file select dialog. - * - * var form = driver.findElement(By.css('form')); - * var element = form.findElement(By.css('input[type=file]')); - * element.sendKeys('/path/to/file.txt'); - * form.submit(); - * - * For uploads to function correctly, the entered path must reference a file - * on the _browser's_ machine, not the local machine running this script. When - * running against a remote Selenium server, a {@link webdriver.FileDetector} - * may be used to transparently copy files to the remote machine before - * attempting to upload them in the browser. - * - * __Note:__ On browsers where native keyboard events are not supported - * (e.g. Firefox on OS X), key events will be synthesized. Special - * punctionation keys will be synthesized according to a standard QWERTY en-us - * keyboard layout. - * - * @param {...(string|!webdriver.promise.Promise)} var_args The sequence - * of keys to type. All arguments will be joined into a single sequence. - * @return {!webdriver.promise.Promise.} A promise that will be resolved - * when all keys have been typed. - */ - sendKeys(...var_args: Array>): webdriver.promise.Promise; - - /** - * Schedules a command to query for the tag/node name of this element. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with the element's tag name. - */ - getTagName(): webdriver.promise.Promise; - - /** - * Schedules a command to query for the computed style of the element - * represented by this instance. If the element inherits the named style from - * its parent, the parent will be queried for its value. Where possible, color - * values will be converted to their hex representation (e.g. #00ff00 instead of - * rgb(0, 255, 0)). - * - * _Warning:_ the value returned will be as the browser interprets it, so - * it may be tricky to form a proper assertion. - * - * @param {string} cssStyleProperty The name of the CSS style property to look - * up. - * @return {!promise.Promise} A promise that will be - * resolved with the requested CSS value. - */ - getCssValue(cssStyleProperty: string): webdriver.promise.Promise; - - /** - * Schedules a command to query for the value of the given attribute of the - * element. Will return the current value, even if it has been modified after - * the page has been loaded. More exactly, this method will return the value of - * the given attribute, unless that attribute is not present, in which case the - * value of the property with the same name is returned. If neither value is - * set, null is returned (for example, the 'value' property of a textarea - * element). The 'style' attribute is converted as best can be to a - * text representation with a trailing semi-colon. The following are deemed to - * be 'boolean' attributes and will return either 'true' or null: - * - * async, autofocus, autoplay, checked, compact, complete, controls, declare, - * defaultchecked, defaultselected, defer, disabled, draggable, ended, - * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, - * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, - * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, - * selected, spellcheck, truespeed, willvalidate - * - * Finally, the following commonly mis-capitalized attribute/property names - * are evaluated as expected: - * - * - 'class' - * - 'readonly' - * - * @param {string} attributeName The name of the attribute to query. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with the attribute's value. The returned value will always be - * either a string or null. - */ - getAttribute(attributeName: string): webdriver.promise.Promise; - - /** - * Get the visible (i.e. not hidden by CSS) innerText of this element, including - * sub-elements, without any leading or trailing whitespace. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with the element's visible text. - */ - getText(): webdriver.promise.Promise; - - /** - * Schedules a command to compute the size of this element's bounding box, in - * pixels. - * @return {!webdriver.promise.Promise.<{width: number, height: number}>} A - * promise that will be resolved with the element's size as a - * {@code {width:number, height:number}} object. - */ - getSize(): webdriver.promise.Promise; - - /** - * Schedules a command to compute the location of this element in page space. - * @return {!webdriver.promise.Promise.<{x: number, y: number}>} A promise that - * will be resolved to the element's location as a - * {@code {x:number, y:number}} object. - */ - getLocation(): webdriver.promise.Promise; - - /** - * Schedules a command to query whether the DOM element represented by this - * instance is enabled, as dicted by the {@code disabled} attribute. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with whether this element is currently enabled. - */ - isEnabled(): webdriver.promise.Promise; - - /** - * Schedules a command to query whether this element is selected. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with whether this element is currently selected. - */ - isSelected(): webdriver.promise.Promise; - - /** - * Schedules a command to submit the form containing this element (or this - * element if it is a FORM element). This command is a no-op if the element is - * not contained in a form. - * @return {!webdriver.promise.Promise.} A promise that will be resolved - * when the form has been submitted. - */ - submit(): webdriver.promise.Promise; - - /** - * Schedules a command to clear the `value` of this element. This command has - * no effect if the underlying DOM element is neither a text INPUT element - * nor a TEXTAREA element. - * @return {!promise.Promise} A promise that will be resolved - * when the element has been cleared. - */ - clear(): webdriver.promise.Promise; - - /** - * Schedules a command to test whether this element is currently displayed. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with whether this element is currently visible on the page. - */ - isDisplayed(): webdriver.promise.Promise; - - /** - * Take a screenshot of the visible region encompassed by this element's - * bounding rectangle. - * - * @param {boolean=} opt_scroll Optional argument that indicates whether the - * element should be scrolled into view before taking a screenshot. - * Defaults to false. - * @return {!promise.Promise} A promise that will be - * resolved to the screenshot as a base-64 encoded PNG. - */ - takeScreenshot(opt_scroll?: boolean): webdriver.promise.Promise; - - /** - * Schedules a command to retrieve the outer HTML of this element. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with the element's outer HTML. - */ - getOuterHtml(): webdriver.promise.Promise; - - /** - * Schedules a command to retrieve the inner HTML of this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's inner HTML. - */ - getInnerHtml(): webdriver.promise.Promise; - - /** @override */ - serialize(): webdriver.promise.Promise; - } - - /** - * WebElementPromise is a promise that will be fulfilled with a WebElement. - * This serves as a forward proxy on WebElement, allowing calls to be - * scheduled without directly on this instance before the underlying - * WebElement has been fulfilled. In other words, the following two statements - * are equivalent: - *
    
    -   *     driver.findElement({id: 'my-button'}).click();
    -   *     driver.findElement({id: 'my-button'}).then(function(el) {
    -   *       return el.click();
    -   *     });
    -   * 
    - * - * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this - * element. - * @param {!webdriver.promise.Promise.} el A promise - * that will resolve to the promised element. - * @constructor - * @extends {webdriver.WebElement} - * @implements {webdriver.promise.Thenable.} - * @final - */ - class WebElementPromise extends WebElement implements webdriver.promise.IThenable { - /** - * @param {!WebDriver} driver The parent WebDriver instance for this - * element. - * @param {!promise.Promise} el A promise - * that will resolve to the promised element. - */ - constructor(driver: webdriver.WebDriver, el: webdriver.promise.Promise); - - /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. This method is a no-op if the promise has alreayd been resolved. - * - * @param {string=} opt_reason The reason this promise is being cancelled. - */ - cancel(opt_reason?: string): void; - - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - - - /** - * Registers listeners for when this instance is resolved. - * - * @param opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be - * resolved with the result of the invoked callback. - */ - then(opt_callback?: (value: WebElement) => webdriver.promise.Promise, opt_errback?: (error: any) => any): webdriver.promise.Promise; - - /** - * Registers listeners for when this instance is resolved. - * - * @param opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be - * resolved with the result of the invoked callback. - */ - then(opt_callback?: (value: WebElement) => R, opt_errback?: (error: any) => any): webdriver.promise.Promise; - - - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - *
    
    -     *   // Synchronous API:
    -     *   try {
    -     *     doSynchronousWork();
    -     *   } catch (ex) {
    -     *     console.error(ex);
    -     *   }
    -     *
    -     *   // Asynchronous promise API:
    -     *   doAsynchronousWork().thenCatch(function(ex) {
    -     *     console.error(ex);
    -     *   });
    -     * 
    - * - * @param {function(*): (R|webdriver.promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!webdriver.promise.Promise.} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - thenCatch(errback: (error: any) => any): webdriver.promise.Promise; - - - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - *
    
    -     *   // Synchronous API:
    -     *   try {
    -     *     doSynchronousWork();
    -     *   } finally {
    -     *     cleanUp();
    -     *   }
    -     *
    -     *   // Asynchronous promise API:
    -     *   doAsynchronousWork().thenFinally(cleanUp);
    -     * 
    - * - * Note: similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - *
    
    -     *   try {
    -     *     throw Error('one');
    -     *   } finally {
    -     *     throw Error('two');  // Hides Error: one
    -     *   }
    -     *
    -     *   webdriver.promise.rejected(Error('one'))
    -     *       .thenFinally(function() {
    -     *         throw Error('two');  // Hides Error: one
    -     *       });
    -     * 
    - * - * - * @param {function(): (R|webdriver.promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled - * with the callback result. - * @template R - */ - thenFinally(callback: () => any): webdriver.promise.Promise; - - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } catch (ex) { - * console.error(ex); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().catch(function(ex) { - * console.error(ex); - * }); - * - * @param {function(*): (R|IThenable)} errback The - * function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - catch(errback: Function): webdriver.promise.Promise; - } - - /** - * Contains information about a WebDriver session. - */ - class Session { - - //region Constructors - - /** - * @param {string} id The session ID. - * @param {!(Object|webdriver.Capabilities)} capabilities The session - * capabilities. - * @constructor - */ - constructor(id: string, capabilities: Capabilities | Object); - - //endregion - - //region Methods - - /** - * @return {string} This session's ID. - */ - getId(): string; - - /** - * @return {!webdriver.Capabilities} This session's capabilities. - */ - getCapabilities(): webdriver.Capabilities; - - /** - * Retrieves the value of a specific capability. - * @param {string} key The capability to retrieve. - * @return {*} The capability value. - */ - getCapability(key: string): any; - - /** - * Returns the JSON representation of this object, which is just the string - * session ID. - * @return {string} The JSON representation of this Session. - */ - toJSON(): string; - - //endregion + wait(condition: Promise | Function, opt_timeout?: number, opt_message?: string): Promise; } } -export = webdriver; +export namespace until { + /** + * Defines a condition to + */ + class Condition { + /** + * @param {string} message A descriptive error message. Should complete the + * sentence 'Waiting [...]' + * @param {function(!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): OUT} */ + fn(webdriver: WebDriver): any; + } + + /** + * Creates a condition that will wait until the input driver is able to switch + * to the designated frame. The target frame may be specified as + * + * 1. a numeric index into + * [window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window.frames) + * for the currently selected frame. + * 2. a {@link ./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|./WebElement|By| + * function(!./WebDriver): !./WebElement)} frame + * The frame identifier. + * @return {!Condition} A new condition. + */ + function ableToSwitchToFrame(frame: number | WebElement | By | ((webdriver: WebDriver) => WebElement)): Condition; + + /** + * Creates a condition that waits for an alert to be opened. Upon success, the + * returned promise will be fulfilled with the handle for the opened alert. + * + * @return {!Condition} The new condition. + */ + function alertIsPresent(): Condition; + + /** + * Creates a condition that will wait for the given element to be disabled. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isEnabled + */ + function elementIsDisabled(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be enabled. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isEnabled + */ + function elementIsEnabled(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be deselected. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see 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 {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isDisplayed + */ + function elementIsNotVisible(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be selected. + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isSelected + */ + function elementIsSelected(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to become visible. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isDisplayed + */ + function elementIsVisible(element: WebElement): Condition; + + /** + * Creates a condition that will loop until an element is + * {@link ./WebDriver#findElement found} with the given locator. + * + * @param {!(By|Function)} locator The locator to use. + * @return {!until.Condition.} The new condition. + */ + function elementLocated(locator: By | Function): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link WebDriver#getText visible text} to contain the given + * substring. + * + * @param {!WebElement} element The element to test. + * @param {string} substr The substring to search for. + * @return {!until.Condition.} The new condition. + * @see WebDriver#getText + */ + function elementTextContains(element: WebElement, substr: string): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link WebDriver#getText visible text} to match the given + * {@code text} exactly. + * + * @param {!WebElement} element The element to test. + * @param {string} text The expected text. + * @return {!until.Condition.} The new condition. + * @see WebDriver#getText + */ + function elementTextIs(element: WebElement, text: string): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link WebDriver#getText visible text} to match a regular + * expression. + * + * @param {!WebElement} element The element to test. + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition} The new condition. + * @see WebDriver#getText + */ + function elementTextMatches(element: WebElement, regex: RegExp): Condition; + + /** + * Creates a condition that will loop until at least one element is + * {@link WebDriver#findElement found} with the given locator. + * + * @param {!(Locator|By.Hash|Function)} locator The locator + * to use. + * @return {!until.Condition.>} The new + * condition. + */ + function elementsLocated(locator: By | Function): Condition; + + /** + * Creates a condition that will wait for the given element to become stale. An + * element is considered stale once it is removed from the DOM, or a new page + * has loaded. + * + * @param {!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; +} + +interface IButton { + LEFT: string; + MIDDLE: string; + RIGHT: string; +} + +/** + * 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} + */ +export var Button: IButton; + +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 + * keys or strings, appends each of the values to a string, + * and adds the chord termination key ({@link Key.NULL}) and returns + * the resulting 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. + */ + chord: (...var_args: Array) => string; +} + +/** + * 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} + */ +export 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(); + * + */ +export class ActionSequence { + + // region Constructors + + /** + * @param {!WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Executes this action sequence. + * @return {!promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): 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 {(!./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 ./WebElement}, this parameter defines + * an offset within that element. The offset should be specified in pixels + * relative to the top-left corner of the element's bounding box. If + * omitted, the element's center will be used as the target offset. + * @return {!ActionSequence} A self reference. + */ + mouseMove(location: WebElement | ILocation, opt_offset?: ILocation): ActionSequence; + + /** + * Presses a mouse button. The mouse button will not be released until + * {@link #mouseUp} is called, regardless of whether that call is made in this + * sequence or another. The behavior for out-of-order events (e.g. mouseDown, + * click) is undefined. + * + * If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + * + * sequence.mouseMove(element).mouseDown() + * + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + mouseDown(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; + + /** + * Releases a mouse button. Behavior is undefined for calling this function + * without a previous call to {@link #mouseDown}. + * + * If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + * + * sequence.mouseMove(element).mouseUp() + * + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + mouseUp(opt_elementOrButton?: WebElement | string, opt_button?: string): 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 {!./WebElement} element The element to drag. + * @param {(!./WebElement|{x: number, y: number})} location The + * location to drag to, either as another WebElement or an offset in + * pixels. + * @return {!ActionSequence} A self reference. + */ + dragAndDrop(element: WebElement, location: WebElement | ILocation): ActionSequence; + + /** + * Clicks a mouse button. + * + * If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + * + * sequence.mouseMove(element).click() + * + * @param {(./WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + click(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; + + /** + * Double-clicks a mouse button. + * + * If an element is provided, the mouse will first be moved to the center of + * that element. This is equivalent to: + * + * sequence.mouseMove(element).doubleClick() + * + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + doubleClick(opt_elementOrButton?: WebElement | string, opt_button?: string): 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 {!Key} key The modifier key to push. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!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 {!Key} key The modifier key to release. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!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 targeted at the currently focused element. + * + * @param {...(string|!input.Key|!Array<(string|!input.Key)>)} var_args + * The keys to type. + * @return {!ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + sendKeys(...var_args: Array>): ActionSequence; + + // endregion +} + + +/** + * Class for defining sequences of user touch interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + * Example: + * + * new TouchSequence(driver). + * tapAndHold({x: 0, y: 0}). + * move({x: 3, y: 4}). + * release({x: 10, y: 10}). + * perform(); + */ +export class TouchSequence { + /* + * @param {!WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: WebDriver); + + + /** + * Executes this action sequence. + * @return {!promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): promise.Promise; + + + /** + * Taps an element. + * + * @param {!WebElement} elem The element to tap. + * @return {!TouchSequence} A self reference. + */ + tap(elem: WebElement): TouchSequence; + + + /** + * Double taps an element. + * + * @param {!WebElement} elem The element to double tap. + * @return {!TouchSequence} A self reference. + */ + doubleTap(elem: WebElement): TouchSequence; + + + /** + * Long press on an element. + * + * @param {!WebElement} elem The element to long press. + * @return {!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 {!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 {!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 {!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 {!TouchSequence} A self reference. + */ + scroll(offset: IOffset): TouchSequence; + + /** + * Scrolls the touch screen, starting on `elem` and moving by the specified + * offset. + * + * @param {!WebElement} elem The element where scroll starts. + * @param {{x: number, y: number}} offset The offset to scroll to. + * @return {!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 {!TouchSequence} A self reference. + */ + flick(speed: ISpeed): TouchSequence; + + /** + * Flick starting at elem and moving by x and y at specified speed. + * + * @param {!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 {!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}). + */ +export class Alert { + /** + * @param {!WebDriver} driver The driver controlling the browser this alert + * is attached to. + * @param {string} text The message text displayed with this alert. + */ + constructor(driver: WebDriver, text: string); + + // region Methods + + /** + * Retrieves the message text displayed with this alert. For instance, if the + * alert were opened with alert('hello'), then this would return 'hello'. + * @return {!promise.Promise} A promise that will be resolved to the + * text displayed with this alert. + */ + getText(): 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): promise.Promise; + + /** + * Accepts this alert. + * @return {!promise.Promise} A promise that will be resolved when + * this command has completed. + */ + accept(): promise.Promise; + + /** + * Dismisses this alert. + * @return {!promise.Promise} A promise that will be resolved when + * this command has completed. + */ + dismiss(): 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 {!promise.Promise} A promise that will be resolved when + * this command has completed. + */ + sendKeys(text: string): promise.Promise; + + // endregion + +} + +/** + * AlertPromise is a promise that will be fulfilled with an Alert. This promise + * serves as a forward proxy on an Alert, allowing calls to be scheduled + * directly on this instance before the underlying Alert has been fulfilled. In + * other words, the following two statements are equivalent: + * + * driver.switchTo().alert().dismiss(); + * driver.switchTo().alert().then(function(alert) { + * return alert.dismiss(); + * }); + * + * @implements {promise.Thenable.} + * @final + */ +export class AlertPromise extends Alert implements promise.IThenable { + /** + * @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: promise.Promise); + + // region Methods + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. + * @param {*} reason The reason this promise is being cancelled. If not an + * {@code Error}, one will be created using the value's string + * representation. + */ + cancel(opt_reason?: string | Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: Function, opt_errback?: Function): promise.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|promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): 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
    +   *   }
    +   *
    +   *   promise.rejected(Error('one'))
    +   *       .thenFinally(function() {
    +   *         throw Error('two');  // Hides Error: one
    +   *       });
    +   * 
    + * + * + * @param {function(): (R|promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: Function): promise.Promise; +} + +/** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ +export class UnhandledAlertError extends error.UnexpectedAlertOpenError { +} + +/** + * Recognized browser names. + * @enum {string} + */ +interface IBrowser { + ANDROID: string; + CHROME: string; + EDGE: string; + FIREFOX: string; + IE: string; + INTERNET_EXPLORER: string; + IPAD: string; + IPHONE: string; + OPERA: string; + PHANTOM_JS: string; + SAFARI: string; + HTMLUNIT: string; +} + +export var Browser: IBrowser; + +interface ProxyConfig { + proxyType: string; + proxyAutoconfigUrl?: string; + ftpProxy?: string; + httpProxy?: string; + sslProxy?: string; + noProxy?: string; +} + +/** + * Creates new {@link 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 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 + */ +export class Builder { + + // region Constructors + + /** + * @constructor + */ + constructor(); + + // endregion + + // region Methods + + /** + * Configures this builder to ignore any environment variable overrides and to + * only use the configuration specified through this instance's API. + * + * @return {!Builder} A self reference. + */ + disableEnvironmentOverrides(): Builder; + + /** + * Creates a new WebDriver client based on this builder's current + * configuration. + * + * While this method will immediately return a new WebDriver instance, any + * commands issued against it will be deferred until the associated browser + * has been fully initialized. Users may call {@link #buildAsync()} to obtain + * a promise that will not be fulfilled until the browser has been created + * (the difference is purely in style). + * + * @return {!WebDriver} 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(): promise.Promise; + + /** + * Configures the target browser for clients created by this instance. + * Any calls to {@link #withCapabilities} after this function will + * overwrite these settings. + * + *

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

    As an alternative to this method, you may also set the + * {@code SELENIUM_REMOTE_URL} environment variable. + * + * @param {string} url The URL of a remote server to use. + * @return {!Builder} A self reference. + */ + usingServer(url: string): Builder; + + /** + * Sets the URL of the proxy to use for the WebDriver's HTTP connections. + * If this method is never called, the Builder will create a connection + * without a proxy. + * + * @param {string} proxy The URL of a proxy to use. + * @return {!Builder} A self reference. + */ + usingWebDriverProxy(proxy: string): Builder; + + /** + * Sets the desired capabilities when requesting a new session. This will + * overwrite any previously set capabilities. + * @param {!(Object|Capabilities)} capabilities The desired + * capabilities for a new session. + * @return {!Builder} A self reference. + */ + withCapabilities(capabilities: Object | Capabilities): Builder; + + // endregion +} + +/** + * Describes a mechanism for locating an element on the page. + * @final + */ +export 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 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#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): !./promise.Promise} + * A new JavaScript-based locator function. + */ + static js(script: string | Function, ...var_args: any[]): (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 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 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(By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ +type ByHash = { className: string } | + { css: string } | + { id: string } | + { js: string } | + { linkText: string } | + { name: string } | + { partialLinkText: string } | + { tagName: string } | + { xpath: string }; + +/** + * Common webdriver capability keys. + * @enum {string} + */ +interface ICapability { + + /** + * Indicates whether a driver should accept all SSL certs by default. This + * capability only applies when requesting a new session. To query whether + * a driver can handle insecure SSL certs, see + * {@link Capability.SECURE_SSL}. + */ + ACCEPT_SSL_CERTS: string; + + + /** + * The browser name. Common browser names are defined in the + * {@link 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 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 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; +} + +export var Capability: ICapability; + +export class Capabilities { + // region Constructors + + /** + * @param {(Capabilities|Object)=} opt_other Another set of + * capabilities to merge into this instance. + * @constructor + */ + constructor(opt_other?: Capabilities | Object); + + // endregion + + // region Methods + + /** @return {!Object} The JSON representation of this instance. */ + toJSON(): any; + + /** + * Merges another set of capabilities into this instance. Any duplicates in + * the provided set will override those already set on this instance. + * @param {!(Capabilities|Object)} other The capabilities to + * merge into this instance. + * @return {!Capabilities} A self reference. + */ + merge(other: Capabilities | Object): Capabilities; + + /** + * @param {string} key The capability to set. + * @param {*} value The capability value. Capability values must be JSON + * serializable. Pass {@code null} to unset the capability. + * @return {!Capabilities} A self reference. + */ + set(key: string, value: any): Capabilities; + + /** + * Sets the logging preferences. Preferences may be specified as a + * {@link logging.Preferences} instance, or a as a map of log-type to + * log-level. + * @param {!(logging.Preferences|Object.)} prefs The + * logging preferences. + * @return {!Capabilities} A self reference. + */ + setLoggingPrefs(prefs: logging.Preferences | Object): Capabilities; + + /** + * Sets the proxy configuration for this instance. + * @param {ProxyConfig} proxy The desired proxy configuration. + * @return {!Capabilities} A self reference. + */ + setProxy(proxy: ProxyConfig): Capabilities; + + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!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 {!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 {!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 {!Capabilities} A basic set of capabilities for Android. + */ + static android(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Chrome. + */ + static chrome(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Microsoft Edge. + */ + static edge(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Firefox. + */ + static firefox(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for + * Internet Explorer. + */ + static ie(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for iPad. + */ + static ipad(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for iPhone. + */ + static iphone(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Opera. + */ + static opera(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for + * PhantomJS. + */ + static phantomjs(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Safari. + */ + static safari(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for HTMLUnit. + */ + static htmlunit(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for HTMLUnit + * with enabled Javascript. + */ + static htmlunitwithjs(): Capabilities; + + // endregion +} + +/** + * An enumeration of valid command string. + */ +interface ICommandName { + GET_SERVER_STATUS: string; + + NEW_SESSION: string; + GET_SESSIONS: string; + DESCRIBE_SESSION: string; + + CLOSE: string; + QUIT: string; + + GET_CURRENT_URL: string; + GET: string; + GO_BACK: string; + GO_FORWARD: string; + REFRESH: string; + + ADD_COOKIE: string; + GET_COOKIE: string; + GET_ALL_COOKIES: string; + DELETE_COOKIE: string; + DELETE_ALL_COOKIES: string; + + GET_ACTIVE_ELEMENT: string; + FIND_ELEMENT: string; + FIND_ELEMENTS: string; + FIND_CHILD_ELEMENT: string; + FIND_CHILD_ELEMENTS: string; + + CLEAR_ELEMENT: string; + CLICK_ELEMENT: string; + SEND_KEYS_TO_ELEMENT: string; + SUBMIT_ELEMENT: string; + + GET_CURRENT_WINDOW_HANDLE: string; + GET_WINDOW_HANDLES: string; + GET_WINDOW_POSITION: string; + SET_WINDOW_POSITION: string; + GET_WINDOW_SIZE: string; + SET_WINDOW_SIZE: string; + MAXIMIZE_WINDOW: string; + + SWITCH_TO_WINDOW: string; + SWITCH_TO_FRAME: string; + GET_PAGE_SOURCE: string; + GET_TITLE: string; + + EXECUTE_SCRIPT: string; + EXECUTE_ASYNC_SCRIPT: string; + + GET_ELEMENT_TEXT: string; + GET_ELEMENT_TAG_NAME: string; + IS_ELEMENT_SELECTED: string; + IS_ELEMENT_ENABLED: string; + IS_ELEMENT_DISPLAYED: string; + GET_ELEMENT_LOCATION: string; + GET_ELEMENT_LOCATION_IN_VIEW: string; + GET_ELEMENT_SIZE: string; + GET_ELEMENT_ATTRIBUTE: string; + GET_ELEMENT_VALUE_OF_CSS_PROPERTY: string; + ELEMENT_EQUALS: string; + + SCREENSHOT: string; + IMPLICITLY_WAIT: string; + SET_SCRIPT_TIMEOUT: string; + SET_TIMEOUT: string; + + ACCEPT_ALERT: string; + DISMISS_ALERT: string; + GET_ALERT_TEXT: string; + SET_ALERT_TEXT: string; + + EXECUTE_SQL: string; + GET_LOCATION: string; + SET_LOCATION: string; + GET_APP_CACHE: string; + GET_APP_CACHE_STATUS: string; + CLEAR_APP_CACHE: string; + IS_BROWSER_ONLINE: string; + SET_BROWSER_ONLINE: string; + + GET_LOCAL_STORAGE_ITEM: string; + GET_LOCAL_STORAGE_KEYS: string; + SET_LOCAL_STORAGE_ITEM: string; + REMOVE_LOCAL_STORAGE_ITEM: string; + CLEAR_LOCAL_STORAGE: string; + GET_LOCAL_STORAGE_SIZE: string; + + GET_SESSION_STORAGE_ITEM: string; + GET_SESSION_STORAGE_KEYS: string; + SET_SESSION_STORAGE_ITEM: string; + REMOVE_SESSION_STORAGE_ITEM: string; + CLEAR_SESSION_STORAGE: string; + GET_SESSION_STORAGE_SIZE: string; + + SET_SCREEN_ORIENTATION: string; + GET_SCREEN_ORIENTATION: string; + + // These belong to the Advanced user interactions - an element is + // optional for these commands. + CLICK: string; + DOUBLE_CLICK: string; + MOUSE_DOWN: string; + MOUSE_UP: string; + MOVE_TO: string; + SEND_KEYS_TO_ACTIVE_ELEMENT: string; + + // These belong to the Advanced Touch API + TOUCH_SINGLE_TAP: string; + TOUCH_DOWN: string; + TOUCH_UP: string; + TOUCH_MOVE: string; + TOUCH_SCROLL: string; + TOUCH_DOUBLE_TAP: string; + TOUCH_LONG_PRESS: string; + TOUCH_FLICK: string; + + GET_AVAILABLE_LOG_TYPES: string; + GET_LOG: string; + GET_SESSION_LOGS: string; + + UPLOAD_FILE: string; +} + +export var CommandName: ICommandName; + +/** + * Describes a command to be executed by the WebDriverJS framework. + * @param {!CommandName} name The name of this command. + * @constructor + */ +export class Command { + // region Constructors + + /** + * @param {!CommandName} name The name of this command. + * @constructor + */ + constructor(name: string); + + // endregion + + // region Methods + + /** + * @return {!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 {!Command} A self reference. + */ + setParameter(name: string, value: any): Command; + + /** + * Sets the parameters for this command. + * @param {!Object.<*>} parameters The command parameters. + * @return {!Command} A self reference. + */ + setParameters(parameters: any): Command; + + /** + * Returns a named command parameter. + * @param {string} key The parameter key to look up. + * @return {*} The parameter value, or undefined if it has not been set. + */ + getParameter(key: string): any; + + /** + * @return {!Object.<*>} The parameters to send with this command. + */ + getParameters(): any; + + // endregion +} + +/** + * Handles the execution of WebDriver {@link Command commands}. + * @interface + */ +export 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): promise.Promise +} + +/** + * Wraps a promised {@link Executor}, ensuring no commands are executed until + * the wrapped executor has been fully resolved. + * @implements {Executor} + */ +export class DeferredExecutor { + /** + * @param {!promise.Promise} delegate The promised delegate, which + * may be provided by any promise-like thenable object. + */ + constructor(delegate: promise.Promise); +} + +/** + * Describes an event listener registered on an {@linkplain EventEmitter}. + */ +export class Listener { + /** + * @param {!Function} fn The acutal listener function. + * @param {(Object|undefined)} scope The object in whose scope to invoke the + * listener. + * @param {boolean} oneshot Whether this listener should only be used once. + */ + constructor(fn: Function, scope: Object, oneshot: boolean); +} + +/** + * Object that can emit events for others to listen for. This is used instead + * of Closure's event system because it is much more light weight. The API is + * based on Node's EventEmitters. + */ +export class EventEmitter { + // region Constructors + + /** + * @constructor + */ + constructor(); + + // endregion + + // region Methods + + /** + * Fires an event and calls all listeners. + * @param {string} type The type of event to emit. + * @param {...*} var_args Any arguments to pass to each listener. + */ + emit(type: string, ...var_args: any[]): void; + + /** + * Returns a mutable list of listeners for a specific type of event. + * @param {string} type The type of event to retrieve the listeners for. + * @return {!Set} The registered listeners for the given event + * type. + */ + listeners(type: string): any; + + /** + * Registers a listener. + * @param {string} type The type of event to listen for. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_self The object in whose scope to invoke the listener. + * @param {boolean=} opt_oneshot Whether the listener should b (e removed after + * the first event is fired. + * @return {!EventEmitter} A self reference. + * @private + */ + addListener(type: string, fn: Function, opt_scope?: any, opt_oneshot?: boolean): EventEmitter; + + + /** + * Registers a one-time listener which will be called only the first time an + * event is emitted, after which it will be removed. + * @param {string} type The type of event to listen for. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!EventEmitter} A self reference. + */ + once(type: string, fn: any, opt_scope?: any): EventEmitter; + + /** + * An alias for {@code #addListener()}. + * @param {string} type The type of event to listen for. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!EventEmitter} A self reference. + */ + on(type: string, fn: Function, opt_scope?: any): EventEmitter; + + /** + * Removes a previously registered event listener. + * @param {string} type The type of event to unregister. + * @param {!Function} listenerFn The handler function to remove. + * @return {!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 {!EventEmitter} A self reference. + */ + removeAllListeners(opt_type?: string): EventEmitter; + + // endregion +} + + +/** + * Interface for navigating back and forth in the browser history. + */ +export class Navigation { + // region Constructors + + /** + * Interface for navigating back and forth in the browser history. + * + * This class should never be instantiated directly. Insead, obtain an instance + * with + * + * navigate() + * + * @see WebDriver#navigate() + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Schedules a command to navigate to a new URL. + * @param {string} url The URL to navigate to. + * @return {!promise.Promise.} A promise that will be resolved + * when the URL has been loaded. + */ + to(url: string): promise.Promise; + + /** + * Schedules a command to move backwards in the browser history. + * @return {!promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + back(): promise.Promise; + + /** + * Schedules a command to move forwards in the browser history. + * @return {!promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + forward(): promise.Promise; + + /** + * Schedules a command to refresh the current page. + * @return {!promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + refresh(): 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. + */ +export class Options { + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Schedules a command to add a cookie. + * @param {string} name The cookie name. + * @param {string} value The cookie value. + * @param {string=} opt_path The cookie path. + * @param {string=} opt_domain The cookie domain. + * @param {boolean=} opt_isSecure Whether the cookie is secure. + * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified + * as a number, should be in milliseconds since midnight, + * January 1, 1970 UTC. + * @return {!promise.Promise} A promise that will be resolved + * when the cookie has been added to the page. + */ + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number | Date): promise.Promise; + + /** + * Schedules a command to delete all cookies visible to the current page. + * @return {!promise.Promise} A promise that will be resolved when all + * cookies have been deleted. + */ + deleteAllCookies(): 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 {!promise.Promise} A promise that will be resolved when the + * cookie has been deleted. + */ + deleteCookie(name: string): 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 {!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(): 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 {!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): promise.Promise; + + /** + * @return {!Logs} The interface for managing driver + * logs. + */ + logs(): Logs; + + /** + * @return {!Timeouts} The interface for managing driver + * timeouts. + */ + timeouts(): Timeouts; + + /** + * @return {!Window} The interface for managing the + * current window. + */ + window(): Window; + + // endregion +} + +/** + * An interface for managing timeout behavior for WebDriver instances. + */ +export class Timeouts { + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Specifies the amount of time the driver should wait when searching for an + * element if it is not immediately present. + *

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

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

    + * Increasing the implicit wait timeout should be used judiciously as it + * will have an adverse effect on test run time, especially when used with + * slower location strategies like XPath. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!promise.Promise} A promise that will be resolved when the + * implicit wait timeout has been set. + */ + implicitlyWait(ms: number): 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 {!promise.Promise} A promise that will be resolved when the + * script timeout has been set. + */ + setScriptTimeout(ms: number): 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 {!promise.Promise} A promise that will be resolved when + * the timeout has been set. + */ + pageLoadTimeout(ms: number): promise.Promise; + + // endregion +} + +/** + * An interface for managing the current window. + */ +export class Window { + + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Retrieves the window's current position, relative to the top left corner of + * the screen. + * @return {!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(): 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 {!promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setPosition(x: number, y: number): promise.Promise; + + /** + * Retrieves the window's current size. + * @return {!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(): promise.Promise; + + /** + * Resizes the current window. + * @param {number} width The desired window width. + * @param {number} height The desired window height. + * @return {!promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setSize(width: number, height: number): promise.Promise; + + /** + * Maximizes the current window. + * @return {!promise.Promise} A promise that will be resolved when the + * command has completed. + */ + maximize(): promise.Promise; + + // endregion +} + +/** + * Interface for managing WebDriver log records. + */ +export class Logs { + + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region + + /** + * Fetches available log entries for the given type. + * + *

    Note that log buffers are reset after each call, meaning that + * available log entries correspond to those entries not yet returned for a + * given log type. In practice, this means that this call will return the + * available log entries since the last call, or from the start of the + * session. + * + * @param {!logging.Type} type The desired log type. + * @return {!promise.Promise.>} A + * promise that will resolve to a list of log entries for the specified + * type. + */ + get(type: string): promise.Promise; + + /** + * Retrieves the log types available to this driver. + * @return {!promise.Promise.>} A + * promise that will resolve to a list of available log types. + */ + getAvailableLogTypes(): promise.Promise; + + // endregion +} + +/** + * An interface for changing the focus of the driver to another frame or window. + */ +export class TargetLocator { + + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Schedules a command retrieve the {@code document.activeElement} element on + * the current document, or {@code document.body} if activeElement is not + * available. + * @return {!WebElement} The active element. + */ + activeElement(): WebElementPromise; + + /** + * Schedules a command to switch focus of all future commands to the first frame + * on the page. + * @return {!promise.Promise} A promise that will be resolved when the + * driver has changed focus to the default content. + */ + defaultContent(): promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * frame on the page. The target frame may be specified as one of the + * following: + * + * - A number that specifies a (zero-based) index into [window.frames]( + * https://developer.mozilla.org/en-US/docs/Web/API/Window.frames). + * - A {@link WebElement} reference, which correspond to a `frame` or `iframe` + * DOM element. + * - The `null` value, to select the topmost frame on the page. Passing `null` + * is the same as calling {@link #defaultContent defaultContent()}. + * + * If the specified frame can not be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchFrameError}. + * + * @param {(number|WebElement|null)} id The frame locator. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified frame. + */ + frame(nameOrIndex: number | WebElement): promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * window. Windows may be specified by their {@code window.name} attribute or + * by its handle (as returned by {@link WebDriver#getWindowHandles}). + * + * If the specified window cannot be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchWindowError}. + * + * @param {string} nameOrHandle The name or window handle of the window to + * switch focus to. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified window. + */ + window(nameOrHandle: string): promise.Promise; + + /** + * Schedules a command to change focus to the active modal dialog, such as + * those opened by `window.alert()`, `window.confirm()`, and + * `window.prompt()`. The returned promise will be rejected with a + * {@linkplain error.NoSuchAlertError} if there are no open alerts. + * + * @return {!AlertPromise} The open alert. + */ + alert(): AlertPromise; + + // endregion +} + +/** + * Used with {@link 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 WebElement WebElement's} will enter all + * key sequences exactly as entered. You may set a + * {@linkplain 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/). + */ +export 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} driver The driver for the current browser. + * @param {string} path The path to process. + * @return {!promise.Promise} A promise for the processed + * file path. + * @package + */ + handleFile(driver: WebDriver, path: string): promise.Promise; +} + +/** + * Creates a new WebDriver client, which provides control over a browser. + * + * Every WebDriver command returns a {@code 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')); + * }); + * + */ +export class WebDriver { + // region Constructors + + /** + * @param {!(Session|promise.Promise)} session Either a + * known session or a promise that will be resolved to a session. + * @param {!command.Executor} executor The executor to use when sending + * commands to the browser. + * @param {promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + */ + constructor(session: Session | promise.Promise, executor: Executor, opt_flow?: promise.ControlFlow); + + // endregion + + // region StaticMethods + + /** + * Creates a new WebDriver client for an existing session. + * @param {!command.Executor} executor Command executor to use when querying + * for session details. + * @param {string} sessionId ID of the session to attach to. + * @param {promise.ControlFlow=} opt_flow The control flow all + * driver commands should execute under. Defaults to the + * {@link promise.controlFlow() currently active} control flow. + * @return {!WebDriver} A new client for the specified session. + */ + static attachToSession(executor: Executor, sessionId: string, opt_flow?: promise.ControlFlow): WebDriver; + + /** + * Creates a new WebDriver session. + * @param {!command.Executor} executor The executor to create the new session + * with. + * @param {!./capabilities.Capabilities} desiredCapabilities The desired + * capabilities for the new session. + * @param {promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under, including the initial session creation. + * Defaults to the {@link promise.controlFlow() currently active} + * control flow. + * @return {!WebDriver} The driver for the newly created session. + */ + static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: promise.ControlFlow): WebDriver; + + // endregion + + // region Methods + + /** + * @return {!promise.ControlFlow} The control flow used by this + * instance. + */ + controlFlow(): promise.ControlFlow; + + /** + * Schedules a {@link command.Command} to be executed by this driver's + * {@link command.Executor}. + * + * @param {!command.Command} command The command to schedule. + * @param {string} description A description of the command for debugging. + * @return {!promise.Promise} A promise that will be resolved + * with the command result. + * @template T + */ + schedule(command: Command, description: string): promise.Promise; + + + /** + * Sets the {@linkplain input.FileDetector file detector} that should be + * used with this instance. + * @param {input.FileDetector} detector The detector to use or {@code null}. + */ + setFileDetector(detector: FileDetector): void; + + + /** + * @return {!promise.Promise.} A promise for this + * client's session. + */ + getSession(): promise.Promise; + + + /** + * @return {!promise.Promise.} A promise + * that will resolve with the this instance's capabilities. + */ + getCapabilities(): 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 {!promise.Promise.} A promise that will be resolved + * when the command has completed. + */ + quit(): promise.Promise; + + /** + * Creates a new action sequence using this driver. The sequence will not be + * scheduled for execution until {@link actions.ActionSequence#perform} is + * called. Example: + * + * driver.actions(). + * mouseDown(element1). + * mouseMove(element2). + * mouseUp(). + * perform(); + * + * @return {!actions.ActionSequence} A new action sequence for this instance. + */ + actions(): ActionSequence; + + + /** + * Creates a new touch sequence using this driver. The sequence will not be + * scheduled for execution until {@link actions.TouchSequence#perform} is + * called. Example: + * + * driver.touchActions(). + * tap(element1). + * doubleTap(element2). + * perform(); + * + * @return {!actions.TouchSequence} A new touch sequence for this instance. + */ + touchActions(): TouchSequence; + + + /** + * Schedules a command to execute JavaScript in the context of the currently + * selected frame or window. The script fragment will be executed as the body + * of an anonymous function. If the script is provided as a function object, + * that function will be converted to a string for injection into the target + * window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code 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 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 {!promise.Promise.} A promise that will resolve to the + * scripts return value. + * @template T + */ + executeScript(script: string | Function, ...var_args: any[]): 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 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 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 {!promise.Promise.} A promise that will resolve to the + * scripts return value. + * @template T + */ + executeAsyncScript(script: string | Function, ...var_args: any[]): promise.Promise; + + /** + * Schedules a command to execute a custom function. + * @param {function(...): (T|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 {!promise.Promise.} A promise that will be resolved' + * with the function's result. + * @template T + */ + call(fn: (...var_args: any[]) => (T | promise.Promise), opt_scope?: any, ...var_args: any[]): promise.Promise; + + /** + * Schedules a command to wait for a condition to hold. The condition may be + * specified by a {@link until.Condition}, as a custom function, or + * as a {@link promise.Promise}. + * + * For a {@link 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 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 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 {!(promise.Promise| + * until.Condition| + * function(!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 {!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: promise.Promise | until.Condition | ((driver: WebDriver) => T) | Function, timeout?: number, opt_message?: string): 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 {!promise.Promise.} A promise that will be resolved + * when the sleep has finished. + */ + sleep(ms: number): promise.Promise; + + /** + * Schedules a command to retrieve they current window handle. + * @return {!promise.Promise.} A promise that will be + * resolved with the current window handle. + */ + getWindowHandle(): promise.Promise; + + /** + * Schedules a command to retrieve the current list of available window handles. + * @return {!promise.Promise.>} A promise that will + * be resolved with an array of window handles. + */ + getAllWindowHandles(): 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 {!promise.Promise.} A promise that will be + * resolved with the current page source. + */ + getPageSource(): promise.Promise; + + /** + * Schedules a command to close the current window. + * @return {!promise.Promise.} A promise that will be resolved + * when this command has completed. + */ + close(): promise.Promise; + + /** + * Schedules a command to navigate to the given URL. + * @param {string} url The fully qualified URL to open. + * @return {!promise.Promise.} A promise that will be resolved + * when the document has finished loading. + */ + get(url: string): promise.Promise; + + /** + * Schedules a command to retrieve the URL of the current page. + * @return {!promise.Promise.} A promise that will be + * resolved with the current URL. + */ + getCurrentUrl(): promise.Promise; + + /** + * Schedules a command to retrieve the current page's title. + * @return {!promise.Promise.} A promise that will be + * resolved with the current page's title. + */ + getTitle(): 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 By} namespace, or as a short-hand + * {@link By.Hash} object. For example, the following two statements + * are equivalent: + * + * var e1 = driver.findElement(By.id('foo')); + * var e2 = driver.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input this + * instance and returns a {@link WebElement}, or a promise that will resolve + * to a WebElement. If the returned promise resolves to an array of + * WebElements, WebDriver will use the first element. For example, to find the + * first visible link on a page, you could write: + * + * var link = driver.findElement(firstVisibleLink); + * + * function firstVisibleLink(driver) { + * var links = driver.findElements(By.tagName('a')); + * return promise.filter(links, function(link) { + * return link.isDisplayed(); + * }); + * } + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!WebElementPromise} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By | Function): WebElementPromise; + + /** + * Schedules a command to test if an element is present on the page. + * + * If given a DOM element, this function will check if it belongs to the + * document the driver is currently focused on. Otherwise, the function will + * test if at least one element can be found with the given search criteria. + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise} A promise that will resolve + * with whether the element is present on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * driver.findElements(locator).then(e => !!e.length); + */ + isElementPresent(locatorOrElement: By | Function): promise.Promise; + + /** + * Schedule a command to search for multiple elements on the page. + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By | Function): promise.Promise; + + /** + * Schedule a command to take a screenshot. The driver makes a best effort to + * return a screenshot of the following, in order of preference: + * + * 1. Entire page + * 2. Current window + * 3. Visible portion of the current frame + * 4. The entire display containing the browser + * + * @return {!promise.Promise} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(): promise.Promise; + + /** + * @return {!Options} The options interface for this + * instance. + */ + manage(): Options; + + /** + * @return {!Navigation} The navigation interface for this + * instance. + */ + navigate(): Navigation; + + /** + * @return {!TargetLocator} The target locator interface for + * this instance. + */ + switchTo(): TargetLocator; + + // endregion +} + +interface IWebElementId { + [ELEMENT: string]: string; +} + +/** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@code WebDriver} instance, or by searching + * under another {@code 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 {!promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): 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 key sequence, 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 input.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', + * Key.CONTROL, 'a', Key.NULL, + * 'now text is'); + * // Alternatively: + * element.sendKeys('text was', + * Key.chord(Key.CONTROL, 'a'), + * 'now text is'); + * + * - The end of the key sequence 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 analogous 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 input.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 + * punctuation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...(number|string|!IThenable<(number|string)>)} var_args The + * sequence of keys to type. Number keys may be referenced numerically or + * by string (1 or '1'). All arguments will be joined into a single + * sequence. + * @return {!promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: Array>): promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

    + * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): 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 {!promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): 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 {!promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): 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 {!promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): 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 {!promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): 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 {!promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): promise.Promise; + + /** + * @return {!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(): promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): 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 By} namespace, or as a short-hand + * {@link 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 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 promise.filter(links, function(link) {
    +   *     return links.isDisplayed();
    +   *   }).then(function(visibleLinks) {
    +   *     return visibleLinks[0];
    +   *   });
    +   * }
    +   * 
    + * + * @param {!(Locator|By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By | Function): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(Locator|By.Hash|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. + */ + isElementPresent(locator: By | Function): promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(Locator|By.Hash|Function)} locator The + * locator strategy to use when searching for the elements. + * @return {!promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By | Function): 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 | promise.IThenable; +} + +/** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@link 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 {Serializable.} + */ +export class WebElement implements Serializable { + /** + * @param {!WebDriver} driver the parent WebDriver instance for this element. + * @param {(!IThenable|string)} id The server-assigned opaque ID for + * the underlying DOM element. + */ + constructor(driver: WebDriver, id: promise.Promise | string); + + /** + * @param {string} id The raw ID. + * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key. + * @return {!Object} The element ID for use with WebDriver's wire protocol. + */ + static buildId(id: string, opt_noLegacy?: boolean): Object; + + /** + * Extracts the encoded WebElement ID from the object. + * + * @param {?} obj The object to extract the ID from. + * @return {string} the extracted ID. + * @throws {TypeError} if the object is not a valid encoded ID. + */ + static extractId(obj: IWebElementId): string; + + /** + * @param {?} obj the object to test. + * @return {boolean} whether the object is a valid encoded WebElement ID. + */ + static isId(obj: IWebElementId): boolean; + + /** + * Compares two WebElements for equality. + * + * @param {!WebElement} a A WebElement. + * @param {!WebElement} b A WebElement. + * @return {!promise.Promise} A promise that will be + * resolved to whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): promise.Promise; + + /** + * @return {!WebDriver} The parent driver for this instance. + */ + getDriver(): WebDriver; + + /** + * @return {!promise.Promise} A promise that resolves to + * the server-assigned opaque ID assigned to this element. + */ + getId(): promise.Promise; + + /** + * @deprecated Use {@link #getId()} instead. + */ + getRawId(): any; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@link #isElementPresent} instead. + * + * The search criteria for an element may be defined using one of the + * factories in the {@link By} namespace, or as a short-hand + * {@link 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 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 promise.filter(links, function(link) { + * return links.isDisplayed(); + * }).then(function(visibleLinks) { + * return visibleLinks[0]; + * }); + * } + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!WebElementPromise} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By | Function): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise} A promise that will be + * resolved with whether an element could be located on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * element.findElements(locator).then(e => !!e.length); + */ + isElementPresent(locator: By | Function): promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By | Function): promise.Promise; + + /** + * Schedules a command to click on this element. + * @return {!promise.Promise.} A promise that will be resolved + * when the click command has completed. + */ + click(): promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * promsieinstance. + * + * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + * + * - The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + * - The {@link 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', + * Key.CONTROL, 'a', Key.NULL, + * 'now text is'); + * // Alternatively: + * element.sendKeys('text was', + * Key.chord(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 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|!promise.Promise)} var_args The sequence + * of keys to type. All arguments will be joined into a single sequence. + * @return {!promise.Promise.} A promise that will be resolved + * when all keys have been typed. + */ + sendKeys(...var_args: Array>): promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!promise.Promise.} A promise that will be + * resolved with the element's tag name. + */ + getTagName(): promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + * + * _Warning:_ the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!promise.Promise} A promise that will be + * resolved with the requested CSS value. + */ + getCssValue(cssStyleProperty: string): 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 {!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): 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 {!promise.Promise.} A promise that will be + * resolved with the element's visible text. + */ + getText(): promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!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(): promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!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(): 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 {!promise.Promise.} A promise that will be + * resolved with whether this element is currently enabled. + */ + isEnabled(): promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!promise.Promise.} A promise that will be + * resolved with whether this element is currently selected. + */ + isSelected(): 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 {!promise.Promise.} A promise that will be resolved + * when the form has been submitted. + */ + submit(): promise.Promise; + + /** + * Schedules a command to clear the `value` of this element. This command has + * no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!promise.Promise} A promise that will be resolved + * when the element has been cleared. + */ + clear(): promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!promise.Promise.} A promise that will be + * resolved with whether this element is currently visible on the page. + */ + isDisplayed(): 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): promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!promise.Promise.} A promise that will be + * resolved with the element's outer HTML. + */ + getOuterHtml(): promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): promise.Promise; + + /** @override */ + serialize(): 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} driver The parent WebDriver instance for this + * element. + * @param {!promise.Promise.} el A promise + * that will resolve to the promised element. + * @constructor + * @extends {WebElement} + * @implements {promise.Thenable.} + * @final + */ +export class WebElementPromise extends WebElement implements 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, el: promise.Promise); + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => promise.Promise, opt_errback?: (error: any) => any): 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): 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|promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): 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
    +   *   }
    +   *
    +   *   promise.rejected(Error('one'))
    +   *       .thenFinally(function() {
    +   *         throw Error('two');  // Hides Error: one
    +   *       });
    +   * 
    + * + * + * @param {function(): (R|promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): promise.Promise; +} + +/** + * Contains information about a WebDriver session. + */ +export class Session { + + // region Constructors + + /** + * @param {string} id The session ID. + * @param {!(Object|Capabilities)} capabilities The session + * capabilities. + * @constructor + */ + constructor(id: string, capabilities: Capabilities | Object); + + // endregion + + // region Methods + + /** + * @return {string} This session's ID. + */ + getId(): string; + + /** + * @return {!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 +} diff --git a/selenium-webdriver/opera.d.ts b/selenium-webdriver/opera.d.ts index 0d3aee1a13..cd02889527 100644 --- a/selenium-webdriver/opera.d.ts +++ b/selenium-webdriver/opera.d.ts @@ -1,177 +1,173 @@ import * as webdriver from './index'; import * as remote from './remote'; -declare namespace opera { +/** + * Creates {@link remote.DriverService} instances that manages an + * [OperaDriver](https://github.com/operasoftware/operachromiumdriver) + * server in a child process. + */ +export class ServiceBuilder { /** - * Creates {@link remote.DriverService} instances that manages an - * [OperaDriver](https://github.com/operasoftware/operachromiumdriver) - * server in a child process. + * @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. */ - 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; - } + constructor(opt_exe?: string); /** - * 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. + * 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. */ - function setDefaultService(service: remote.DriverService): any; + usingPort(port: number): ServiceBuilder; /** - * 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. + * 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. */ - function getDefaultService(): remote.DriverService; + loggingTo(path: string): ServiceBuilder; /** - * Class for managing {@linkplain Driver OperaDriver} specific options. + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. */ - 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; + enableVerboseLogging(): ServiceBuilder; - /** - * 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; + /** + * Silence sthe drivers output. + * @return {!ServiceBuilder} A self reference. + */ + silent(): ServiceBuilder; - /** - * 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; + /** + * 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 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; + /** + * 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 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; - } + /** + * 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; } -export = opera; +/** + * 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. + */ +export 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. + */ +export function getDefaultService(): remote.DriverService; + +/** + * Class for managing {@linkplain Driver OperaDriver} specific options. + */ +export 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: string[]): 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: any[]): 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; +} + +export 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; +} diff --git a/selenium-webdriver/remote.d.ts b/selenium-webdriver/remote.d.ts index d3cadb746a..ae4f156ba7 100644 --- a/selenium-webdriver/remote.d.ts +++ b/selenium-webdriver/remote.d.ts @@ -1,71 +1,67 @@ import * as webdriver from './index'; -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. + */ +export class DriverService { /** - * A record object that defines the configuration options for a DriverService - * instance. - * - * @record + * @param {string} executable Path to the executable to run. + * @param {!ServiceOptions} options Configuration options for the service. */ - interface ServiceOptions { } + constructor(executable: string, options: 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. + * @return {!promise.Promise} A promise that resolves to + * the server's address. + * @throws {Error} If the server has not been started. */ - class DriverService { - /** - * @param {string} executable Path to the executable to run. - * @param {!ServiceOptions} options Configuration options for the service. - */ - constructor(executable: string, options: ServiceOptions); + address(): webdriver.promise.Promise; - /** - * @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; - /** - * 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; - /** - * 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; - /** - * 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; - } + /** + * 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; } - -export = remote; diff --git a/selenium-webdriver/safari.d.ts b/selenium-webdriver/safari.d.ts index 82fd835b20..7a6f1701c4 100644 --- a/selenium-webdriver/safari.d.ts +++ b/selenium-webdriver/safari.d.ts @@ -1,93 +1,89 @@ import * as webdriver from './index'; -declare namespace safari { - class Server { } +export class Server { } - /** - * @return {!Promise} A promise that will resolve with the path - * to Safari on the current system. - */ - function findSafariExecutable(): any; +/** + * @return {!Promise} A promise that will resolve with the path + * to Safari on the current system. + */ +export 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; +/** + * @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. + */ +export 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[]; +/** + * Deletes all session data files if so desired. + * @param {!Object} desiredCapabilities . + * @return {!Array} A list of promises for the deleted files. + */ +export function cleanSession(desiredCapabilities: webdriver.Capabilities): any[]; - /** @return {string} . */ - function getRandomString(): string; +/** @return {string} . */ +export 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); - - } +/** + * @implements {command.Executor} + */ +export class CommandExecutor { } -export = safari; +/** + * Configuration options specific to the {@link Driver SafariDriver}. + */ +export 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(); + * + */ +export 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); + +} diff --git a/selenium-webdriver/test/chrome.ts b/selenium-webdriver/test/chrome.ts index 2fce6bf6ca..de358656bc 100644 --- a/selenium-webdriver/test/chrome.ts +++ b/selenium-webdriver/test/chrome.ts @@ -52,7 +52,7 @@ function TestServiceBuilder() { builder = builder.setUrlBasePath('path'); builder = builder.setStdio('config'); builder = builder.setStdio(['A', 'B']); - builder = builder.withEnvironment({ 'A': 'a', 'B': 'b' }); + builder = builder.withEnvironment({ A: 'a', B: 'b' }); } function TestChromeModule() { diff --git a/selenium-webdriver/test/firefox.ts b/selenium-webdriver/test/firefox.ts index 7ebe0aa856..8b329c8e73 100644 --- a/selenium-webdriver/test/firefox.ts +++ b/selenium-webdriver/test/firefox.ts @@ -8,7 +8,7 @@ function TestBinary() { binary.addArguments('A', 'B', 'C'); var promise: webdriver.promise.Promise = binary.kill(); - binary.launch('profile').then(function (result: any) { }); + binary.launch('profile').then((result: any) => {}); } function TestFirefoxDriver() { @@ -38,7 +38,7 @@ function TestFirefoxProfile() { var bool: boolean = profile.acceptUntrustedCerts(); profile.addExtension('ext'); bool = profile.assumeUntrustedCertIssuer(); - profile.encode().then(function (prof: string) { }); + profile.encode().then((prof: string) => {}); var num: number = profile.getPort(); var anything: any = profile.getPreference('key'); bool = profile.nativeEventsEnabled(); diff --git a/selenium-webdriver/test/index.ts b/selenium-webdriver/test/index.ts index ba2acb91ef..5d32724b15 100644 --- a/selenium-webdriver/test/index.ts +++ b/selenium-webdriver/test/index.ts @@ -28,7 +28,7 @@ function TestBuilder() { builder = builder.setEnableNativeEvents(true); builder = builder.setFirefoxOptions(new firefox.Options()); builder = builder.setLoggingPrefs(new webdriver.logging.Preferences()); - builder = builder.setLoggingPrefs({ 'key': 'value' }); + builder = builder.setLoggingPrefs({ key: 'value' }); builder = builder.setProxy({ proxyType: 'type' }); builder = builder.setScrollBehavior(1); builder = builder.usingServer('http://someserver'); @@ -89,7 +89,7 @@ function TestActionSequence() { sequence = sequence.sendKeys('A', 'B', 'C'); sequence = sequence.sendKeys('A', webdriver.Key.NULL); - sequence.perform().then(function () { }); + sequence.perform().then(() => {}); } function TestTouchSequence() { @@ -111,7 +111,7 @@ function TestTouchSequence() { sequence = sequence.flick({ xspeed: 100, yspeed: 100 }); sequence = sequence.flickElement(element, { x: 100, y: 100 }, 100); - sequence.perform().then(function () { }); + sequence.perform().then(() => {}); } function TestAlert() { @@ -121,10 +121,10 @@ function TestAlert() { 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 () { }); + alert.accept().then(() => {}); + alert.dismiss().then(() => {}); + alert.getText().then((text: string) => {}); + alert.sendKeys('ABC').then(() => {}); } function TestBrowser() { @@ -164,7 +164,7 @@ function TestCapabilities() { 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.setLoggingPrefs({ key: 'value' }); capabilities = capabilities.setProxy({ proxyType: 'Type' }); capabilities = capabilities.setEnableNativeEvents(true); capabilities = capabilities.setScrollBehavior(1); @@ -328,7 +328,7 @@ function TestCommandName() { function TestEventEmitter() { var emitter: webdriver.EventEmitter = new webdriver.EventEmitter(); - var callback = function (a: number, b: number, c: number) { }; + var callback = (a: number, b: number, c: number) => {}; emitter = emitter.addListener('ABC', callback); emitter = emitter.addListener('ABC', callback, this); @@ -453,7 +453,7 @@ function TestBy() { locatorHash = { tagName: 'tag' }; locatorHash = { xpath: 'xpath' }; - webdriver.By.js('script', 1, 2, 3)(driver).then(function (abc: number) { }); + webdriver.By.js('script', 1, 2, 3)(driver).then((abc: number) => {}); } function TestSession() { @@ -470,11 +470,11 @@ function TestSession() { } function TestUnhandledAlertError() { - var someFunc = function (error: webdriver.UnhandledAlertError) { + var someFunc = (error: webdriver.UnhandledAlertError) => { var baseError: Error = error; var str: string = error.getAlertText(); str = error.toString(); - } + }; } function TestWebDriverFileDetector() { @@ -484,7 +484,7 @@ function TestWebDriverFileDetector() { var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); - fileDetector.handleFile(driver, 'path/to/file').then(function (path: string) { }); + fileDetector.handleFile(driver, 'path/to/file').then((path: string) => {}); } function TestWebDriverLogs() { @@ -494,8 +494,8 @@ function TestWebDriverLogs() { 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[]) { }); + logs.get(webdriver.logging.Type.BROWSER).then((entries: webdriver.logging.Entry[]) => {}); + logs.getAvailableLogTypes().then((types: string[]) => {}); } function TestWebDriverNavigation() { @@ -505,10 +505,10 @@ function TestWebDriverNavigation() { 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 () { }); + navigation.back().then(() => {}); + navigation.forward().then(() => {}); + navigation.refresh().then(() => {}); + navigation.to('http://google.com').then(() => {}); } function TestWebDriverOptions() { @@ -529,8 +529,8 @@ function TestWebDriverOptions() { promise = options.deleteAllCookies(); promise = options.deleteCookie('name'); - options.getCookie('name').then(function (cookies: webdriver.IWebDriverOptionsCookie) { }); - options.getCookies().then(function (cookies: webdriver.IWebDriverOptionsCookie[]) { }); + options.getCookie('name').then((cookies: webdriver.IWebDriverOptionsCookie) => {}); + options.getCookies().then((cookies: webdriver.IWebDriverOptionsCookie[]) => {}); var logs: webdriver.Logs = options.logs(); var timeouts: webdriver.Timeouts = options.timeouts(); @@ -600,10 +600,10 @@ function TestWebDriver() { 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); + stringPromise = driver.call(() => 'value'); + stringPromise = driver.call(() => stringPromise); + stringPromise = driver.call(() => { var d: any = this; return 'value'; }, driver); + stringPromise = driver.call((a: number) => 'value', driver, 1); voidPromise = driver.close(); flow = driver.controlFlow(); @@ -611,14 +611,14 @@ function TestWebDriver() { // executeAsyncScript stringPromise = driver.executeAsyncScript('function(){}'); stringPromise = driver.executeAsyncScript('function(){}', 1, 2, 3); - stringPromise = driver.executeAsyncScript(function () { }); - stringPromise = driver.executeAsyncScript(function (a: number) { }, 1); + stringPromise = driver.executeAsyncScript(() => {}); + stringPromise = driver.executeAsyncScript((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); + stringPromise = driver.executeScript(() => {}); + stringPromise = driver.executeScript((a: number) => {}, 1); // findElement var element: webdriver.WebElement; @@ -626,15 +626,15 @@ function TestWebDriver() { 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[]) { }); + driver.findElements(webdriver.By.className('ABC')).then((elements: webdriver.WebElement[]) => {}); + driver.findElements(webdriver.By.js('function(){}')).then((elements: webdriver.WebElement[]) => {}); voidPromise = driver.get('http://www.google.com'); - driver.getAllWindowHandles().then(function (handles: string[]) { }); - driver.getCapabilities().then(function (caps: webdriver.Capabilities) { }); + driver.getAllWindowHandles().then((handles: string[]) => {}); + driver.getCapabilities().then((caps: webdriver.Capabilities) => {}); stringPromise = driver.getCurrentUrl(); - stringPromise = driver.getPageSource() - driver.getSession().then(function (session: webdriver.Session) { });; + stringPromise = driver.getPageSource(); + driver.getSession().then((session: webdriver.Session) => {}); stringPromise = driver.getTitle(); stringPromise = driver.getWindowHandle(); @@ -656,8 +656,8 @@ function TestWebDriver() { var booleanCondition: webdriver.until.Condition; booleanPromise = driver.wait(booleanPromise); booleanPromise = driver.wait(booleanCondition); - booleanPromise = driver.wait(function (driver: webdriver.WebDriver) { return true; }); - let conditionFunction: Function; + booleanPromise = driver.wait((driver: webdriver.WebDriver) => true); + let conditionFunction: Function; // tslint:disable-line:prefer-const booleanPromise = driver.wait(conditionFunction); booleanPromise = driver.wait(booleanPromise, 123); booleanPromise = driver.wait(booleanPromise, 123, 'Message'); @@ -690,16 +690,16 @@ function TestWebElement() { voidPromise = element.click(); element = element.findElement(webdriver.By.id('ABC')); - element.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); + element.findElements(webdriver.By.className('ABC')).then((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) { }); + element.getLocation().then((location: webdriver.ILocation) => {}); stringPromise = element.getOuterHtml(); - element.getSize().then(function (size: webdriver.ISize) { }); + element.getSize().then((size: webdriver.ISize) => {}); stringPromise = element.getTagName(); stringPromise = element.getText(); booleanPromise = element.isDisplayed(); @@ -711,9 +711,9 @@ function TestWebElement() { voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise); voidPromise = element.sendKeys('A', 1, webdriver.Key.BACK_SPACE, stringPromise); voidPromise = element.submit(); - element.getId().then(function (id: string) { }); - element.getRawId().then(function (id: string) { }); - element.serialize().then(function (id: webdriver.IWebElementId) { }); + element.getId().then((id: string) => {}); + element.getRawId().then((id: string) => {}); + element.serialize().then((id: webdriver.IWebElementId) => {}); booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId')); } @@ -731,13 +731,13 @@ function TestWebElementPromise() { 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.then((element: webdriver.WebElement) => {}); + elementPromise.then((element: webdriver.WebElement) => {}, (error: any) => {}); + elementPromise.then((element: webdriver.WebElement) => 'foo', (error: any) => {}).then((result: string) => {}); - elementPromise.thenCatch(function (error: any) { }).then(function (value: any) { }); + elementPromise.thenCatch((error: any) => {}).then((value: any) => {}); - elementPromise.thenFinally(function () { }); + elementPromise.thenFinally(() => {}); } function TestLogging() { @@ -794,52 +794,51 @@ function TestPromiseModule() { var booleanPromise: webdriver.promise.Promise; var voidPromise: webdriver.promise.Promise; - webdriver.promise.all([stringPromise]).then(function (values: string[]) { }); + webdriver.promise.all([stringPromise]).then((values: string[]) => {}); - webdriver.promise.asap('abc', function (value: any) { return true; }); - webdriver.promise.asap('abc', function (value: any) { }, function (err: any) { return 'ABC'; }); + webdriver.promise.asap('abc', (value: any) => true); + webdriver.promise.asap('abc', (value: any) => {}, (err: any) => 'ABC'); - stringPromise = webdriver.promise.checkedNodeCall(function (err: any, value: any) { return 'abc'; }); + stringPromise = webdriver.promise.checkedNodeCall((err: any, value: any) => 'abc'); - webdriver.promise.consume(function () { + webdriver.promise.consume(() => { return 5; - }).then(function (value: number) { }); - webdriver.promise.consume(function () { + }).then((value: number) => {}); + webdriver.promise.consume(() => { 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) { }); + }, this).then((value: number) => {}); + webdriver.promise.consume((a: number, b: number, c: number) => 5, this, 1, 2, 3) + .then((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], (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[]) { + numbersPromise = webdriver.promise.filter([1, 2, 3], (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[]) { + numbersPromise = webdriver.promise.filter(numbersPromise, (element: number, type: any, 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, (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[]) { + numbersPromise = webdriver.promise.map([1, 2, 3], (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[]) { + numbersPromise = webdriver.promise.map([1, 2, 3], (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[]) { + numbersPromise = webdriver.promise.map(numbersPromise, (el: number, type: any, 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, (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' }); + stringPromise = webdriver.promise.createFlow((newFlow: webdriver.promise.ControlFlow) => 'ABC'); var deferred: webdriver.promise.Deferred; deferred = webdriver.promise.defer(); @@ -857,14 +856,14 @@ function TestPromiseModule() { stringPromise = webdriver.promise.fullyResolved('abc'); - var bool: boolean = webdriver.promise.isGenerator(function () { }); + var bool: boolean = webdriver.promise.isGenerator(() => {}); 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; }); + numberPromise = webdriver.promise.when('abc', (value: any) => 123, (err: Error) => 123); } function TestUntilModule() { @@ -872,7 +871,7 @@ function TestUntilModule() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var conditionB: webdriver.until.Condition = new webdriver.until.Condition('message', function (driver: webdriver.WebDriver) { return true; }); + var conditionB: webdriver.until.Condition = new webdriver.until.Condition('message', (driver: webdriver.WebDriver) => true); var conditionBBase: webdriver.until.Condition = conditionB; var conditionWebElement: webdriver.until.Condition; var conditionWebElements: webdriver.until.Condition; @@ -912,9 +911,9 @@ function TestControlFlow() { 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'); + stringPromise = flow.execute(() => 'value'); + stringPromise = flow.execute(() => stringPromise); + stringPromise = flow.execute(() => stringPromise, 'Description'); var schedule: string; schedule = flow.toString(); @@ -928,9 +927,9 @@ function TestControlFlow() { 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'); + voidPromise = flow.wait(() => true); + voidPromise = flow.wait(() => true, 123); + voidPromise = flow.wait(() => stringPromise, 123, 'Timeout Message'); } function TestDeferred() { @@ -952,28 +951,22 @@ function TestDeferred() { function TestPromiseClass() { var controlFlow: webdriver.promise.ControlFlow; var promise: webdriver.promise.Promise; - promise = new webdriver.promise.Promise(function ( - resolve: (value: string) => void, - reject: () => void) { }); - promise = new webdriver.promise.Promise(function ( - resolve: (value: webdriver.promise.Promise) => void, - reject: () => void) { }); - promise = new webdriver.promise.Promise(function ( - resolve: (value: string) => void, - reject: () => void) { }, controlFlow); + promise = new webdriver.promise.Promise((resolve: (value: string) => void, reject: () => void) => {}); + promise = new webdriver.promise.Promise((resolve: (value: webdriver.promise.Promise) => void, reject: () => void) => {}); + promise = new webdriver.promise.Promise((resolve: (value: string) => void, reject: () => 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.then((a: string) => 'cde'); + promise = promise.then((a: string) => 'cde', (e: any) => {}); + promise = promise.then((a: string) => 'cde', (e: any) => 123); - promise = promise.thenCatch(function (error: any) { }); + promise = promise.thenCatch((error: any) => {}); - promise.thenFinally(function () { }); + promise.thenFinally(() => {}); } function TestThenableClass() { @@ -985,13 +978,13 @@ function TestThenableClass() { 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.then((a: string) => 'cde'); + thenable = thenable.then((a: string) => 'cde', (e: any) => {}); + thenable = thenable.then((a: string) => 'cde', (e: any) => 123); - thenable = thenable.thenCatch(function (error: any) { }); + thenable = thenable.thenCatch((error: any) => {}); - thenable.thenFinally(function () { }); + thenable.thenFinally(() => {}); } function TestErrorCode() { @@ -1029,29 +1022,29 @@ async function TestAsyncAwaitable() { } function TestTestingModule() { - testing.before(function () { + testing.before(() => { }); - testing.beforeEach(function () { + testing.beforeEach(() => { }); - testing.describe('My test suite', function () { - testing.it('My test', function () { + testing.describe('My test suite', () => { + testing.it('My test', () => { }); - testing.iit('My exclusive test.', function () { + testing.iit('My exclusive test.', () => { }); }); - testing.xdescribe('My disabled suite', function () { - testing.xit('My disabled test.', function () { + testing.xdescribe('My disabled suite', () => { + testing.xit('My disabled test.', () => { }); }); - testing.after(function () { + testing.after(() => { }); - testing.afterEach(function () { + testing.afterEach(() => { }); } diff --git a/selenium-webdriver/testing.d.ts b/selenium-webdriver/testing.d.ts index e17c8e0f21..34d72e4627 100644 --- a/selenium-webdriver/testing.d.ts +++ b/selenium-webdriver/testing.d.ts @@ -1,63 +1,59 @@ -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; +/** +* Registers a new test suite. +* @param name The suite name. +* @param fn The suite function, or {@code undefined} to define a pending test suite. +*/ +export 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; +/** + * Defines a suppressed test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ +export 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 the current suite finishes. + * @param fn + */ +export 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 after each test in a suite. + * @param fn + */ +export 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 the current suite starts. + * @param fn + */ +export function before(fn: Function): void; - /** - * Register a function to call before each test in a suite. - * @param fn - */ - function beforeEach(fn: Function): void; +/** + * Register a function to call before each test in a suite. + * @param fn + */ +export 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; +/** + * 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. + */ +export 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; +/** + * 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. + */ +export 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; -} - -export = testing; \ No newline at end of file +/** + * 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. + */ +export function xit(name: string, fn: Function): void; diff --git a/selenium-webdriver/tsconfig.json b/selenium-webdriver/tsconfig.json index a16c018a47..50c76c7b28 100644 --- a/selenium-webdriver/tsconfig.json +++ b/selenium-webdriver/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6" ], diff --git a/selenium-webdriver/tslint.json b/selenium-webdriver/tslint.json new file mode 100644 index 0000000000..eb0befd093 --- /dev/null +++ b/selenium-webdriver/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "../tslint.json", + "rules": { + "callable-types": false, + "forbidden-types": false, + "interface-name": false, + "no-empty-interface": false, + "unified-signatures": false + } +} diff --git a/semantic-ui/index.d.ts b/semantic-ui/index.d.ts index 71a4868e3e..bdfa5c2249 100644 --- a/semantic-ui/index.d.ts +++ b/semantic-ui/index.d.ts @@ -1986,7 +1986,9 @@ declare namespace SemanticUI { */ allowTab?: boolean; /** - * Named transition to use when animating menu in and out. Defaults to slide down or slide up depending on dropdown direction. Fade and slide down are available without including ui transitions + * Named transition to use when animating menu in and out. + * Defaults to slide down or slide up depending on dropdown direction. + * Fade and slide down are available without including ui transitions * * @default 'auto' * @see {@link http://semantic-ui.com/modules/transition.html} diff --git a/semantic-ui/tsconfig.json b/semantic-ui/tsconfig.json index f57f321023..510c5ecd05 100644 --- a/semantic-ui/tsconfig.json +++ b/semantic-ui/tsconfig.json @@ -1,20 +1,23 @@ { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "semantic-ui-tests.ts" - ] -} + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "semantic-ui-tests.ts" + ] +} \ No newline at end of file diff --git a/semantic-ui/tslint.json b/semantic-ui/tslint.json index 25440fc88b..68d10d72a6 100644 --- a/semantic-ui/tslint.json +++ b/semantic-ui/tslint.json @@ -1,6 +1,6 @@ { - "extends": "../tslint.json", - "rules": { - "unified-signatures": false - } + "extends": "../tslint.json", + "rules": { + "unified-signatures": false + } } diff --git a/semver-diff/semver-diff-tests.ts b/semver-diff/semver-diff-tests.ts index fca7d8552e..e3ad74c462 100644 --- a/semver-diff/semver-diff-tests.ts +++ b/semver-diff/semver-diff-tests.ts @@ -1,15 +1,15 @@ import semverDiff = require('semver-diff'); -semverDiff('1.1.1', '1.1.2'); //=> 'patch' +semverDiff('1.1.1', '1.1.2'); // => 'patch' -semverDiff('0.0.1', '1.0.0'); //=> 'major' +semverDiff('0.0.1', '1.0.0'); // => 'major' -semverDiff('0.0.1', '0.1.0'); //=> 'minor' +semverDiff('0.0.1', '0.1.0'); // => 'minor' -semverDiff('0.0.1-foo', '0.0.1-foo.bar'); //=> 'prerelease' +semverDiff('0.0.1-foo', '0.0.1-foo.bar'); // => 'prerelease' -semverDiff('0.1.0', '0.1.0+foo'); //=> 'build' +semverDiff('0.1.0', '0.1.0+foo'); // => 'build' -semverDiff('0.0.1', '0.0.1'); //=> null +semverDiff('0.0.1', '0.0.1'); // => null -semverDiff('0.0.2', '0.0.1'); //=> null +semverDiff('0.0.2', '0.0.1'); // => null diff --git a/sequelize/index.d.ts b/sequelize/index.d.ts index 6ff2c3e6df..13f9fbcf2e 100644 --- a/sequelize/index.d.ts +++ b/sequelize/index.d.ts @@ -3319,38 +3319,25 @@ declare namespace sequelize { /** * Options for Model.findOrInitialize method */ - interface FindOrInitializeOptions extends LoggingOptions { - - /** - * A hash of search attributes. - */ - where: string | WhereOptions; + interface FindOrInitializeOptions extends FindOptions { /** * Default values to use if building a new instance */ defaults?: TAttributes; - /** - * Transaction to run query under - */ - transaction?: Transaction; } /** - * Options for Model.findOrInitialize method + * Options for Model.findOrInitialize method */ - interface FindCreateFindOptions { + interface FindCreateFindOptions extends FindOptions { /** - * A hash of search attributes. - */ - where: string | WhereOptions; - - /** - * Default values to use if building a new instance + * Default values to use if building a new instance */ defaults?: TAttributes; + } /** @@ -4781,6 +4768,16 @@ declare namespace sequelize { */ fields?: Array; + /** + * Method the index should use, for example 'gin' index. + */ + using?: string; + + /** + * Operator that should be used by gin index, see Built-in GIN Operator Classes + */ + operator?: string; + } /** @@ -4879,6 +4876,11 @@ declare namespace sequelize { */ underscoredAll?: boolean; + /** + * Indicates if the model's table has a trigger associated with it. Default false. + */ + hasTrigger?: boolean; + /** * If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. * Otherwise, the dao name will be pluralized. Default false. diff --git a/sequelize/sequelize-tests.ts b/sequelize/sequelize-tests.ts index 973f98076c..3ecf1b9427 100644 --- a/sequelize/sequelize-tests.ts +++ b/sequelize/sequelize-tests.ts @@ -977,6 +977,7 @@ let findOrRetVal: Promise<[AnyInstance, boolean]>; findOrRetVal = User.findOrInitialize( { where : { username : 'foo' } } ); findOrRetVal = User.findOrInitialize( { where : { username : 'foo' }, transaction : t } ); findOrRetVal = User.findOrInitialize( { where : { username : 'foo' }, defaults : { foo : 'asd' }, transaction : t } ); +findOrRetVal = User.findOrInitialize( { where : { username : 'foo' }, defaults : { foo : 'asd' }, paranoid : false } ); findOrRetVal = User.findOrCreate( { where : { a : 'b' }, defaults : { json : { a : { b : 'c' }, d : [1, 2, 3] } } } ); findOrRetVal = User.findOrCreate( { where : { a : 'b' }, defaults : { json : 'a', data : 'b' } } ); @@ -989,7 +990,6 @@ findOrRetVal = User.findOrCreate( { where : { objectId : 'asdasdasd' }, defaults findOrRetVal = User.findOrCreate( { where : { id : undefined }, defaults : { name : Math.random().toString() } } ); findOrRetVal = User.findOrCreate( { where : { email : 'unique.email.@d.com', companyId : Math.floor( Math.random() * 5 ) } } ); findOrRetVal = User.findOrCreate( { where : { objectId : 1 }, defaults : { bool : false } } ); -findOrRetVal = User.findOrCreate( { where : 'c', defaults : {} } ); User.upsert( { id : 42, username : 'doe', foo : s.fn( 'upper', 'mixedCase2' ) } ); @@ -1269,7 +1269,7 @@ s.define( 'UserWithUniqueUsername', { username : { type : Sequelize.STRING, unique : { name : 'user_and_email', msg : 'User and email must be unique' } }, email : { type : Sequelize.STRING, unique : 'user_and_email' } } ); -/* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 + s.define( 'UserWithUniqueUsername', { user_id : { type : Sequelize.INTEGER }, email : { type : Sequelize.STRING } @@ -1277,13 +1277,18 @@ s.define( 'UserWithUniqueUsername', { indexes : [ { name : 'user_and_email_index', - msg : 'User and email must be unique', unique : true, method : 'BTREE', fields : ['user_id', { attribute : 'email', collate : 'en_US', order : 'DESC', length : 5 }] - }] + }, + { + fields: ['data'], + using: 'gin', + operator: 'jsonb_path_ops' + } + ] } ); - */ + s.define( 'TaskBuild', { title : { type : Sequelize.STRING, defaultValue : 'a task!' }, foo : { type : Sequelize.INTEGER, defaultValue : 2 }, @@ -1529,6 +1534,27 @@ s.define( 'User', { paranoid : true } ); +s.define( 'TriggerTest', { + id : { + type : Sequelize.INTEGER, + field : 'test_id', + autoIncrement : true, + primaryKey : true, + validate : { + min : 1 + } + }, + title : { + allowNull : false, + type : Sequelize.STRING( 255 ), + field : 'test_title' + } +}, { + timestamps : false, + underscored : true, + hasTrigger : true +} ); + // // Transaction // ~~~~~~~~~~~~~ diff --git a/sequelize/v3/index.d.ts b/sequelize/v3/index.d.ts index 9142dc9a6c..fb73cd94bf 100644 --- a/sequelize/v3/index.d.ts +++ b/sequelize/v3/index.d.ts @@ -4843,6 +4843,11 @@ declare namespace sequelize { */ underscoredAll?: boolean; + /** + * Indicates if the model's table has a trigger associated with it. Default false. + */ + hasTrigger?: boolean; + /** * If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. * Otherwise, the dao name will be pluralized. Default false. diff --git a/sequelize/v3/sequelize-tests.ts b/sequelize/v3/sequelize-tests.ts index 04a55062c8..ef90600e91 100644 --- a/sequelize/v3/sequelize-tests.ts +++ b/sequelize/v3/sequelize-tests.ts @@ -1515,6 +1515,27 @@ s.define( 'User', { paranoid : true } ); +s.define( 'TriggerTest', { + id : { + type : Sequelize.INTEGER, + field : 'test_id', + autoIncrement : true, + primaryKey : true, + validate : { + min : 1 + } + }, + title : { + allowNull : false, + type : Sequelize.STRING( 255 ), + field : 'test_title' + } +}, { + timestamps : false, + underscored : true, + hasTrigger : true +} ); + // // Transaction // ~~~~~~~~~~~~~ diff --git a/service_worker_api/index.d.ts b/service_worker_api/index.d.ts index 715fc4efbe..3f7e07acaa 100644 --- a/service_worker_api/index.d.ts +++ b/service_worker_api/index.d.ts @@ -576,12 +576,90 @@ interface ServiceWorkerRegistration extends EventTarget { * before it is unregistered. */ unregister(): Promise; + + /** + * Returns a Promise that resolves to an array of Notification objects. + * @param [options] An options object that can contain options to filter the notifications returned. + */ + getNotifications(options?: ServiceWorkerGetNotificationOptions): Promise; // need to be replaced with `Notification[]` when possible + + /** + * Displays the notification with the requested title. + * @param [title] The title that must be shown within the notification + * @param [options] An object that allows to configure the notification. + */ + showNotification(title: string, options?: ServiceWorkerNotificationOptions): Promise; } +/** + * An options object to provide options upon a ServiceWorkerRegistration. + * @param [scope] A USVString representing a URL that defines a service worker's registration scope; what range of + * URLs a service worker can control. This is usually a relative URL, and it defaults to '/' when not specified. + */ interface ServiceWorkerRegisterOptions { scope: string; } +/** + * Action to display in a notification. + * @param [action] A DOMString identifying a user action to be displayed on the notification. + * @param [title] A DOMString containing action text to be shown to the user. + * @param [icon] A USVString containg the URL of an icon to display with the action. + */ +interface NotificationAction { // TODO: Maybe need to moved if NotificationApi types are defined + action: string; + title: string; + icon?: string; +} + +/** + * Object that allows to configure a notification. + * @param [actions] An array of actions to display in the notification. + * Appropriate responses are built using event.action within the notificationclick event. + * @param [badge] The URL of an image to represent the notification when there is not enough space to display the + * notification itself such as, for example, the Android Notification Bar. On Android devices, the badge should + * accommodate devices up to 4x resolution, about 96 by 96 px, and the image will be automatically masked. + * @param [body] A string representing an extra content to display within the notification. + * @param [dir] The direction of the notification; it can be auto, ltr, or rtl. + * @param [icon] The URL of an image to be used as an icon by the notification. + * @param [image] A USVSTring containing the URL of an image to be displayed in the notification. + * @param [lang] Specify the lang used within the notification. This string must be a valid BCP 47 language tag. + * @param [renotify] A boolean that indicates whether to supress vibrations and audible alerts when resusing a tag + * value. The default is false. + * @param [requireInteraction] Indicates that on devices with sufficiently large screens, a notification should remain + * active until the user clicks or dismisses it. If this value is absent or false, the desktop version of Chrome + * will auto-minimize notifications after approximately twenty seconds. The default value is false. + * @param [tag] An ID for a given notification that allows you to find, replace, or remove the notification using + * script if necessary. + * @param [vibrate] A vibration pattern to run with the display of the notification. A vibration pattern can be an + * array with as few as one member. The values are times in milliseconds where the even indices (0, 2, 4, etc.) indicate + * how long to vibrate and the odd indices indicate how long to pause. For example [300, 100, 400] would vibrate + * 300ms, pause 100ms, then vibrate 400ms. + * @param [data] Arbitrary data that you want associated with the notification. This can be of any data type. + */ +interface ServiceWorkerNotificationOptions { + actions?: NotificationAction[]; + badge?: string; + body?: string; + dir?: 'auto' | 'ltr' | 'rtl'; + icon?: string; + lang?: string; + renotify?: boolean; + requireInteraction?: boolean; + tag?: string; + vibrate?: number[]; + data?: any; +} + +/** + * An options object that can contain options to filter notifications. + * @param [tag] A DOMString representing a notification tag. If specified, only notifications that have this tag + * will be returned. + */ +interface ServiceWorkerGetNotificationOptions { + tag: string; +} + /** * Provides an object representing the service worker as an overall unit in the * network ecosystem, including facilities to register, unregister and update @@ -629,10 +707,6 @@ interface ServiceWorkerContainer extends EventTarget { * * @param scriptURL The URL of the service worker script. * @param [options] An options object to provide options upon registration. - * Currently available options are: scope: A USVString representing a URL - * that defines a service worker's registration scope; what range of URLs a - * service worker can control. This is usually a relative URL, and it - * defaults to '/' when not specified. */ register(scriptURL: string, options?: ServiceWorkerRegisterOptions): Promise; diff --git a/service_worker_api/service_worker_api-tests.ts b/service_worker_api/service_worker_api-tests.ts index b2e183aa05..27c2b85c20 100644 --- a/service_worker_api/service_worker_api-tests.ts +++ b/service_worker_api/service_worker_api-tests.ts @@ -1,14 +1,14 @@ var OFFLINE_CACHE = "cache_test"; var OFFLINE_URL = "localhost"; -self.addEventListener('fetch', function(event: FetchEvent) { +self.addEventListener('fetch', (event: FetchEvent) => { if (event.request.method === 'GET' && event.request.headers.get('accept').indexOf('text/html') !== -1) { console.log('Handling fetch event for', event.request.url); event.respondWith( - self.fetch(event.request).catch(function(e) { + self.fetch(event.request).catch(e => { console.error('Fetch failed; returning offline page instead.', e); - return self.caches.open(OFFLINE_CACHE).then(function(cache: Cache) { + return self.caches.open(OFFLINE_CACHE).then((cache: Cache) => { return cache.match(OFFLINE_URL); }); }) @@ -16,25 +16,25 @@ self.addEventListener('fetch', function(event: FetchEvent) { } }); -self.caches.open('v1').then(function(cache: Cache) { - cache.matchAll('/images/').then(function(response: Response[]) { - response.forEach(function(element, index, array) { +self.caches.open('v1').then((cache: Cache) => { + cache.matchAll('/images/').then((response: Response[]) => { + response.forEach((element, index, array) => { cache.delete(element.url); }); }); }); -self.addEventListener('install', function(event: InstallEvent) { +self.addEventListener('install', (event: InstallEvent) => { event.waitUntil( - self.caches.open('v1').then(function(cache: Cache) { + self.caches.open('v1').then((cache: Cache) => { return cache.add('/sw-test/index.html'); }) ); }); -self.addEventListener('install', function(event: InstallEvent) { +self.addEventListener('install', (event: InstallEvent) => { event.waitUntil( - self.caches.open('v1').then(function(cache) { + self.caches.open('v1').then(cache => { return cache.addAll([ '/sw-test/', '/sw-test/index.html', @@ -51,50 +51,50 @@ self.addEventListener('install', function(event: InstallEvent) { ); }); -self.addEventListener('fetch', function(event: FetchEvent) { - var cachedResponse = self.caches.match(event.request).then(function(response: Response) { +self.addEventListener('fetch', (event: FetchEvent) => { + var cachedResponse = self.caches.match(event.request).then(response => { if (response) { return response; } - }).catch(function() { - return self.fetch(event.request).then(function(response: Response) { - return self.caches.open('v1').then(function(cache) { + }).catch(() => { + return self.fetch(event.request).then(response => { + return self.caches.open('v1').then(cache => { cache.put(event.request, response.clone()); return response; }); }); - }).catch(function() { + }).catch(() => { return self.caches.match('/sw-test/gallery/myLittleVader.jpg'); }); event.respondWith(cachedResponse); }); -self.caches.open('v1').then(function(cache) { - cache.match('/images/image.png').then(function(response: Response) { +self.caches.open('v1').then(cache => { + cache.match('/images/image.png').then(response => { cache.delete(response.url); }); }); -self.caches.open('v1').then(function(cache: Cache) { - cache.keys().then(function(response) { - response.forEach(function(element, index, array) { +self.caches.open('v1').then(cache => { + cache.keys().then(response => { + response.forEach((element, index, array) => { cache.delete(element); }); }); }); -self.caches.has('v1').then(function() { - self.caches.delete('v1').then(function() { +self.caches.has('v1').then(() => { + self.caches.delete('v1').then(() => { console.log('done'); }); }); -self.addEventListener('activate', function(event: ExtendableEvent) { +self.addEventListener('activate', (event: ExtendableEvent) => { var cacheWhitelist = ['v2']; event.waitUntil( - self.caches.keys().then(function(keyList) { + self.caches.keys().then(keyList => { for (var item of keyList) { if (cacheWhitelist.indexOf(item) === -1) { return self.caches.delete(item); @@ -105,9 +105,9 @@ self.addEventListener('activate', function(event: ExtendableEvent) { }); function sendMessage(message: any) { - return new Promise(function(resolve, reject) { + return new Promise((resolve, reject) => { var messageChannel = new MessageChannel(); - messageChannel.port1.onmessage = function(event) { + messageChannel.port1.onmessage = event => { if (event.data.error) { reject(event.data.error); } else { @@ -118,28 +118,28 @@ function sendMessage(message: any) { }); } -self.addEventListener('message', function(evt: ExtendableMessageEvent) { +self.addEventListener('message', (evt: ExtendableMessageEvent) => { evt.ports[0].postMessage(evt.source.id); }); -sendMessage('test').then(function(clientId: string) { +sendMessage('test').then((clientId: string) => { console.log(clientId); }); -self.clients.matchAll({type: "test"}).then(function(clients) { +self.clients.matchAll({type: "test"}).then(clients => { for (var cli of clients) { - if(cli.url === 'index.html') { + if (cli.url === 'index.html') { self.clients.openWindow(cli.url); // or do something else involving the matching client } } }); -self.addEventListener('activate', function(e: ExtendableEvent) { +self.addEventListener('activate', (e: ExtendableEvent) => { e.waitUntil(self.clients.claim()); }); -navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(function(registration) { +navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(registration => { // At this point, registration has taken place. // The service worker will not handle requests until this page and any // other instances of this page (in other tabs, etc.) have been @@ -154,31 +154,31 @@ navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(functi } if (serviceWorker) { console.log(serviceWorker.state); - serviceWorker.addEventListener('statechange', function(e: any) { + serviceWorker.addEventListener('statechange', (e: any) => { console.log(e.target.state); }); } -}).catch(function(error) { +}).catch(error => { // Something went wrong during registration. The service-worker.js file // might be unavailable or contain a syntax error. }); -navigator.serviceWorker.getRegistration('/app').then(function(registration: ServiceWorkerRegistration) { +navigator.serviceWorker.getRegistration('/app').then((registration: ServiceWorkerRegistration) => { console.log(registration); }); -navigator.serviceWorker.getRegistrations().then(function(registrations: ServiceWorkerRegistration[]) { +navigator.serviceWorker.getRegistrations().then((registrations: ServiceWorkerRegistration[]) => { console.log(registrations); }); self.registration.unregister(); -self.addEventListener('install', function(event: ExtendableEvent) { +self.addEventListener('install', (event: ExtendableEvent) => { event.waitUntil(self.skipWaiting()); }); -self.addEventListener('notificationclick', function(event: NotificationEvent) { +self.addEventListener('notificationclick', (event: NotificationEvent) => { console.log('On notification click: ', event.notification.tag); event.notification.close(); @@ -186,8 +186,21 @@ self.addEventListener('notificationclick', function(event: NotificationEvent) { // focuses if it is event.waitUntil(self.clients.matchAll({ type: "window" - }).then(function(clientList) { + }).then(clientList => { if (self.clients.openWindow) return self.clients.openWindow('/'); })); }); + +navigator.serviceWorker.ready.then(function(registration) { + registration.showNotification('Notification Sample', { + body: 'This is a sample notification!', + icon: '/sw-test/star-wars-logo.jpg', + tag: 'notification-sample' + }); +}); + +self.registration.getNotifications({tag: 'notification-sample'}) + .then(function(notifications) { + console.log(notifications); + }); diff --git a/service_worker_api/tslint.json b/service_worker_api/tslint.json index f9e30021f4..377cc837d4 100644 --- a/service_worker_api/tslint.json +++ b/service_worker_api/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/sha1/sha1-tests.ts b/sha1/sha1-tests.ts index f2c6547f2b..22467632c8 100644 --- a/sha1/sha1-tests.ts +++ b/sha1/sha1-tests.ts @@ -1,5 +1,3 @@ -/// - import fs = require("fs"); import sha1 = require("sha1"); /** @@ -31,6 +29,6 @@ console.log(sha1('message')); // should print 6f9b9af3cd6e8b8a73c2cdced37fe9f592 const testTwo = sha1('message', {asString: true}); const testThree = sha1('message', {asBytes: true}); -fs.readFile('sha1.d.ts', function(err: Error, buf: Buffer) { +fs.readFile('sha1.d.ts', (err: Error, buf: Buffer) => { console.log(sha1(buf)); }); diff --git a/sharepoint/index.d.ts b/sharepoint/index.d.ts index 2bc22e9234..1908d46b0c 100644 --- a/sharepoint/index.d.ts +++ b/sharepoint/index.d.ts @@ -1,7 +1,7 @@ // Type definitions for SharePoint: 2010.1 / 2013.1 -// Project: https://github.com/gandjustas/sptypescript -// Definitions by: Stanislav Vyshchepan , Andrey Markeev -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Project: https:// github.com/gandjustas/sptypescript +// Definitions by: Stanislav Vyshchepan , Andrey Markeev +// Definitions: https:// github.com/DefinitelyTyped/DefinitelyTyped /// @@ -34,17 +34,17 @@ declare namespace SP { } export enum ListLevelPermissionMask { - viewListItems, //: 1, - insertListItems, //: 2, - editListItems, //: 4, - deleteListItems, //: 8, - approveItems, //: 16, - openItems, //: 32, - viewVersions, //: 64, - deleteVersions, //: 128, - breakCheckout, //: 256, - managePersonalViews, //: 512, - manageLists //: 2048 + viewListItems, // : 1, + insertListItems, // : 2, + editListItems, // : 4, + deleteListItems, // : 8, + approveItems, // : 16, + openItems, // : 32, + viewVersions, // : 64, + deleteVersions, // : 128, + breakCheckout, // : 256, + managePersonalViews, // : 512, + manageLists // : 2048 } export class HtmlBuilder { @@ -154,32 +154,32 @@ declare class JSRequest { } declare class _spPageContextInfo { - static alertsEnabled: boolean; //true - static allowSilverlightPrompt: string; //"True" - static clientServerTimeDelta: number; //-182 - static crossDomainPhotosEnabled: boolean; //true - static currentCultureName: string; //"ru-RU" - static currentLanguage: number; //1049 - static currentUICultureName: string; //"ru-RU" - static layoutsUrl: string; //"_layouts/15" - static pageListId: string; //"{06ee6d96-f27f-4160-b6bb-c18f187b18a7}" + static alertsEnabled: boolean; // true + static allowSilverlightPrompt: string; // "True" + static clientServerTimeDelta: number; // -182 + static crossDomainPhotosEnabled: boolean; // true + static currentCultureName: string; // "ru-RU" + static currentLanguage: number; // 1049 + static currentUICultureName: string; // "ru-RU" + static layoutsUrl: string; // "_layouts/15" + static pageListId: string; // "{06ee6d96-f27f-4160-b6bb-c18f187b18a7}" static pageItemId: number; - static pagePersonalizationScope: string; //1 - static serverRequestPath: string; //"/SPTypeScript/Lists/ConditionalFormattingTasksList/AllItems.aspx" - static siteAbsoluteUrl: string; // "https://gandjustas-7b20d3715e8ed4.sharepoint.com" - static siteClientTag: string; //"0$$15.0.4454.1021" + static pagePersonalizationScope: string; // 1 + static serverRequestPath: string; // "/SPTypeScript/Lists/ConditionalFormattingTasksList/AllItems.aspx" + static siteAbsoluteUrl: string; // "https:// gandjustas-7b20d3715e8ed4.sharepoint.com" + static siteClientTag: string; // "0$$15.0.4454.1021" static siteServerRelativeUrl: string; // "/" - static systemUserKey: string; //"i:0h.f|membership|10033fff84e7cb2b@live.com" - static tenantAppVersion: string; //"0" - static userId: number; //12 - static webAbsoluteUrl: string; //"https://gandjustas-7b20d3715e8ed4.sharepoint.com/SPTypeScript" - static webLanguage: number; //1049 - static webLogoUrl: string; //"/_layouts/15/images/siteIcon.png?rev=23" + static systemUserKey: string; // "i:0h.f|membership|10033fff84e7cb2b@live.com" + static tenantAppVersion: string; // "0" + static userId: number; // 12 + static webAbsoluteUrl: string; // "https:// gandjustas-7b20d3715e8ed4.sharepoint.com/SPTypeScript" + static webLanguage: number; // 1049 + static webLogoUrl: string; // "/_layouts/15/images/siteIcon.png?rev=23" static webPermMasks: { High: number; Low: number; }; - static webServerRelativeUrl: string; //"/SPTypeScript" - static webTemplate: string; //"17" - static webTitle: string; //"SPTypeScript" - static webUIVersion: number; //15 + static webServerRelativeUrl: string; // "/SPTypeScript" + static webTemplate: string; // "17" + static webTitle: string; // "SPTypeScript" + static webUIVersion: number; // 15 } declare function STSHtmlEncode(value: string): string; @@ -268,7 +268,7 @@ interface ContextInfo extends SPClientTemplates.RenderContext { LastSelectedItemIID: number; LastRowIndexSelected: number; RowFocusTimerID: number; - ListData: any; //SPClientTemplates.ListData_InView | SPClientTemplates.ListData_InForm + ListData: any; // SPClientTemplates.ListData_InView | SPClientTemplates.ListData_InForm ListSchema: SPClientTemplates.ListSchema; ModerationStatus: number; PortalUrl: string; @@ -356,7 +356,7 @@ declare namespace SP { body?: string | Uint8Array; binaryStringRequestBody?: boolean; - /** Currently need fix to get ginary response. Details: http://techmikael.blogspot.ru/2013/07/how-to-copy-files-between-sites-using.html */ + /** Currently need fix to get ginary response. Details: http:// techmikael.blogspot.ru/2013/07/how-to-copy-files-between-sites-using.html */ binaryStringResponseBody?: boolean; timeout?: number; success?: (response: ResponseInfo) => void; @@ -810,7 +810,7 @@ declare namespace SPClientTemplates { export interface FieldSchema_InForm_Lookup extends FieldSchema_InForm { /** Specifies if the field allows multiple values */ AllowMultipleValues: boolean; - /** Returns base url for a list display form, e.g. "http://portal/web/_layouts/15/listform.aspx?PageType=4" + /** Returns base url for a list display form, e.g. "http:// portal/web/_layouts/15/listform.aspx?PageType=4" You must add "ListId" (Guid of the list) and "ID" (integer Id of the item) parameters in order to use this Url */ BaseDisplayFormUrl: string; /** Indicates if the field is a dependent lookup */ @@ -1464,13 +1464,13 @@ declare namespace SPClientForms { } export enum FormManagerEvents { - Event_OnControlValueChanged, //: 1, - Event_OnControlInitializedCallback, //: 2, - Event_OnControlFocusSetCallback, //: 3, - Event_GetControlValueCallback, //: 4, - Event_OnControlValidationError, //: 5, - Event_RegisterControlValidator, //: 6, - Event_GetHasValueChangedCallback //: 7 + Event_OnControlValueChanged, // : 1, + Event_OnControlInitializedCallback, // : 2, + Event_OnControlFocusSetCallback, // : 3, + Event_GetControlValueCallback, // : 4, + Event_OnControlValidationError, // : 5, + Event_RegisterControlValidator, // : 6, + Event_GetHasValueChangedCallback // : 7 } export class ClientForm { @@ -1734,11 +1734,11 @@ declare namespace SP { export class ClientObjectPropertyConditionalScope extends SP.ConditionalScopeBase { constructor(clientObject: SP.ClientObject, propertyName: string, comparisonOperator: string, valueToCompare: any, allowAllActions?: boolean); } - //export class ClientResult { + // export class ClientResult { // get_value(): any; // setValue(value: any): void; // constructor(); - //} + // } export class ClientResult { get_value(): T; setValue(value: T): void; @@ -5235,7 +5235,7 @@ declare namespace Microsoft.SharePoint.Client.Search { } export class QueryPersonalizationData extends SP.ClientObject { - //It's really empty; + // It's really empty; } export class QuerySuggestionResults extends SP.ClientValueObject { @@ -5561,7 +5561,7 @@ declare namespace Microsoft.SharePoint.Client.Search { } export class SearchConfigurationPortabilityPropertyNames { - static importWarnings: string; //= 'ImportWarnings' + static importWarnings: string; // = 'ImportWarnings' } } @@ -5890,12 +5890,12 @@ declare namespace SP { } // For some reasons this enum doesn't exist - //export enum SocialFollowResult { + // export enum SocialFollowResult { // ok = 0, // alreadyFollowing = 1, // limitReached = 2, // internalError = 3 - //} + // } /** Provides information about the feed. This type provides information about whether the feed on the server contains additional threads that were not returned. */ @@ -6619,7 +6619,7 @@ declare namespace SP { set_owner(value: string): void; get_terms(): TermCollection; createTerm(name: string, lcid: number, newTermId: SP.Guid): Term; - /*getTerms(pagingLimit: number): TermCollection;*/ //Moved to descendants to void TypeScript errors + /*getTerms(pagingLimit: number): TermCollection;*/ // Moved to descendants to void TypeScript errors reuseTerm(sourceTerm: Term, reuseBranch: boolean): Term; reuseTermWithPinning(sourceTerm: Term): Term; deleteCustomProperty(name: string): void; @@ -7683,7 +7683,7 @@ declare namespace SP { /** The Follow method adds the specified document or site to the list of followed content. @param url URL that identifies the item to follow. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= @param data Optional parameter that holds application-defined data for the item. */ follow(url: string, data?: FollowedItemData): FollowResult; @@ -7694,23 +7694,23 @@ declare namespace SP { /** Removes the specified document or site from list of followed content. @param url URL that identifies the item to stop following. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= */ + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= */ stopFollowing(url: string): void; /** Determines if the specified document or site is being followed. @param url URL that identifies the item that is supposed to be followed. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= */ + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= */ isFollowed(url: string): SP.BooleanResult; /** Retrieves the followed status of the specified document or site. Returns a value of type FollowedStatus, wrapped into a SP.IntResult object. @param url URL that identifies the followed item. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= */ + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= */ getFollowedStatus(url: string): SP.IntResult; /** Returns the followed item identified by a given URL or returns null if the item does not exist. @param url URL that identifies the followed item. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= */ + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= */ getItem(url: string): FollowedItem; /** Returns an array of zero or more followed items described by the type and subtype parameters. @param options Describes the type of item to return. @@ -7719,7 +7719,7 @@ declare namespace SP { /** Updates the properties for followed item with specified URL. @param url URL that identifies the followed item. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= @param data Application-defined data stored with the followed item. */ updateData(url: string, data: FollowedItemData): void; /** Returns the refreshed item that is being pointed to in the Social list. @@ -8936,9 +8936,9 @@ declare namespace SP { declare namespace SP { export namespace CompliancePolicy { export enum SPContainerType { - site, //: 0, - web, //: 1, - list //: 2 + site, // : 0, + web, // : 1, + list // : 2 } export class SPContainerId extends ClientObject { @@ -9203,10 +9203,10 @@ declare namespace SP { export namespace Discovery { export enum ExportStatus { - notStarted, //: 0, - started, //: 1, - complete, //: 2, - failed //: 3 + notStarted, // : 0, + started, // : 1, + complete, // : 2, + failed // : 3 } export class Case extends ClientObject { @@ -9261,11 +9261,11 @@ declare class SPClientAutoFill { Loading: number; }; - static KeyProperty: string; //= 'AutoFillKey'; - static DisplayTextProperty: string; //= 'AutoFillDisplayText'; - static SubDisplayTextProperty: string; //= 'AutoFillSubDisplayText'; - static TitleTextProperty: string; //= 'AutoFillTitleText'; - static MenuOptionTypeProperty: string; //= 'AutoFillMenuOptionType'; + static KeyProperty: string; // = 'AutoFillKey'; + static DisplayTextProperty: string; // = 'AutoFillDisplayText'; + static SubDisplayTextProperty: string; // = 'AutoFillSubDisplayText'; + static TitleTextProperty: string; // = 'AutoFillTitleText'; + static MenuOptionTypeProperty: string; // = 'AutoFillMenuOptionType'; static GetAutoFillObjFromInput(elmText: HTMLInputElement): SPClientAutoFill; static GetAutoFillObjFromContainer(elmChild: HTMLElement): SPClientAutoFill; @@ -9338,50 +9338,50 @@ declare class SPClientPeoplePicker { TopLevelElementId: string; // '', - EditorElementId: string; //'', - AutoFillElementId: string; //'', - ResolvedListElementId: string; //'', - InitialHelpTextElementId: string; //'', - WaitImageId: string; //'', - HiddenInputId: string; //'', - AllowEmpty: boolean; //true, - ForceClaims: boolean; //false, - AutoFillEnabled: boolean; //true, - AllowMultipleUsers: boolean; //false, + EditorElementId: string; // '', + AutoFillElementId: string; // '', + ResolvedListElementId: string; // '', + InitialHelpTextElementId: string; // '', + WaitImageId: string; // '', + HiddenInputId: string; // '', + AllowEmpty: boolean; // true, + ForceClaims: boolean; // false, + AutoFillEnabled: boolean; // true, + AllowMultipleUsers: boolean; // false, OnValueChangedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; OnUserResolvedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; OnControlValidateClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; - UrlZone: SP.UrlZone; //null, - AllUrlZones: boolean; //false, - SharePointGroupID: number; //0, - AllowEmailAddresses: boolean; //false, + UrlZone: SP.UrlZone; // null, + AllUrlZones: boolean; // false, + SharePointGroupID: number; // 0, + AllowEmailAddresses: boolean; // false, PPMRU: SPClientPeoplePickerMRU; - UseLocalSuggestionCache: boolean; //true, - CurrentQueryStr: string; //'', + UseLocalSuggestionCache: boolean; // true, + CurrentQueryStr: string; // '', LatestSearchQueryStr: string; // '', InitialSuggestions: ISPClientPeoplePickerEntity[]; CurrentLocalSuggestions: ISPClientPeoplePickerEntity[]; CurrentLocalSuggestionsDict: ISPClientPeoplePickerEntity; - VisibleSuggestions: number; //5, - PrincipalAccountType: string; //'', + VisibleSuggestions: number; // 5, + PrincipalAccountType: string; // '', PrincipalAccountTypeEnum: SP.Utilities.PrincipalType; - EnabledClaimProviders: string; //'', - SearchPrincipalSource: SP.Utilities.PrincipalSource; //null, - ResolvePrincipalSource: SP.Utilities.PrincipalSource; //null, - MaximumEntitySuggestions: number; //30, - EditorWidthSet: boolean; //false, - QueryScriptInit: boolean; //false, - AutoFillControl: SPClientAutoFill; //null, - TotalUserCount: number; //0, - UnresolvedUserCount: number; //0, + EnabledClaimProviders: string; // '', + SearchPrincipalSource: SP.Utilities.PrincipalSource; // null, + ResolvePrincipalSource: SP.Utilities.PrincipalSource; // null, + MaximumEntitySuggestions: number; // 30, + EditorWidthSet: boolean; // false, + QueryScriptInit: boolean; // false, + AutoFillControl: SPClientAutoFill; // null, + TotalUserCount: number; // 0, + UnresolvedUserCount: number; // 0, UserQueryDict: { [index: string]: SP.StringResult }; ProcessedUserList: { [index: string]: SPClientPeoplePickerProcessedUser }; - HasInputError: boolean; //false, - HasServerError: boolean; //false, - ShowUserPresence: boolean; //true, - TerminatingCharacter: string; //';', - UnresolvedUserElmIdToReplace: string; //'', - WebApplicationID: SP.Guid; //'{00000000-0000-0000-0000-000000000000}', + HasInputError: boolean; // false, + HasServerError: boolean; // false, + ShowUserPresence: boolean; // true, + TerminatingCharacter: string; // ';', + UnresolvedUserElmIdToReplace: string; // '', + WebApplicationID: SP.Guid; // '{00000000-0000-0000-0000-000000000000}', GetAllUserInfo(): ISPClientPeoplePickerEntity[]; SetInitialValue(entities: ISPClientPeoplePickerEntity[], initialErrorMsg?: string): void @@ -9482,9 +9482,9 @@ interface ISPClientPeoplePickerSchema { } declare class SPClientPeoplePickerMRU { - static PPMRUVersion: number; //= 1; - static MaxPPMRUItems: number; //= 200; - static PPMRUDomLocalStoreKey: string; //= "ClientPeoplePickerMRU"; + static PPMRUVersion: number; // = 1; + static MaxPPMRUItems: number; // = 200; + static PPMRUDomLocalStoreKey: string; // = "ClientPeoplePickerMRU"; static GetSPClientPeoplePickerMRU(): SPClientPeoplePickerMRU; GetItems(strKey: string): { Key: string, [name: string]: any }; @@ -9513,18 +9513,18 @@ interface ISPClientPeoplePickerEntity { } declare class SPClientPeoplePickerProcessedUser { - UserContainerElementId: string; //'', - DisplayElementId: string; //'', - PresenceElementId: string; //'', - DeleteUserElementId: string; //'', - SID: string; //'', - DisplayName: string; //'', - SIPAddress: string; //'', - UserInfo: ISPClientPeoplePickerEntity; //null, - ResolvedUser: boolean; //true, - Suggestions: ISPClientAutoFillData[]; //null, - ErrorDescription: string; //'', - ResolveText: string; //'', + UserContainerElementId: string; // '', + DisplayElementId: string; // '', + PresenceElementId: string; // '', + DeleteUserElementId: string; // '', + SID: string; // '', + DisplayName: string; // '', + SIPAddress: string; // '', + UserInfo: ISPClientPeoplePickerEntity; // null, + ResolvedUser: boolean; // true, + Suggestions: ISPClientAutoFillData[]; // null, + ErrorDescription: string; // '', + ResolveText: string; // '', UpdateResolvedUser(newUserInfo: ISPClientPeoplePickerEntity, strNewElementId: string): void; UpdateSuggestions(entity: ISPClientPeoplePickerEntity): void; BuildUserHTML(): string; @@ -9713,126 +9713,126 @@ declare namespace SP { export namespace JsGrid { export enum TextDirection { - Default, //0, - RightToLeft, //1, - LeftToRight //2 + Default, // 0, + RightToLeft, // 1, + LeftToRight // 2 } export enum PaneId { - MainGrid, //0, - PivotedGrid, //1, - Gantt //2 + MainGrid, // 0, + PivotedGrid, // 1, + Gantt // 2 } export enum PaneLayout { - GridOnly, //0, - GridAndGantt, //1, - GridAndPivotedGrid //2 + GridOnly, // 0, + GridAndGantt, // 1, + GridAndPivotedGrid // 2 } export enum EditMode { - ReadOnly, //0, - ReadWrite, //1, - ReadOnlyDefer, //2, - ReadWriteDefer, //3, - Defer //4 + ReadOnly, // 0, + ReadWrite, // 1, + ReadOnlyDefer, // 2, + ReadWriteDefer, // 3, + Defer // 4 } export enum GanttDrawBarFlags { - LeftLink, //0x01, - RightLink //0x02 + LeftLink, // 0x01, + RightLink // 0x02 } export enum GanttBarDateType { - Start, //0, - End //1 + Start, // 0, + End // 1 } export enum ValidationState { - Valid, //0, - Pending, //1, - Invalid //2 + Valid, // 0, + Pending, // 1, + Invalid // 2 } export enum HierarchyMode { - None, //0, - Standard, //1, - Grouping //2 + None, // 0, + Standard, // 1, + Grouping // 2 } export enum EditActorWriteType { - Both, //1, - LocalizedOnly, //2, - DataOnly, //3, - Either //4 + Both, // 1, + LocalizedOnly, // 2, + DataOnly, // 3, + Either // 4 } export enum EditActorReadType { - Both, //1, - LocalizedOnly, //2, - DataOnly //3 + Both, // 1, + LocalizedOnly, // 2, + DataOnly // 3 } export enum EditActorUpdateType { - Committed, //0, - Uncommitted, //1 + Committed, // 0, + Uncommitted, // 1 } export enum SortMode { - Ascending, //1, - Descending, //-1, - None //0 + Ascending, // 1, + Descending, // -1, + None // 0 } export namespace RowHeaderStyleId { - export var Transfer: string; //'Transfer', - export var Conflict: string; //'Conflict' + export var Transfer: string; // 'Transfer', + export var Conflict: string; // 'Conflict' } export namespace RowHeaderAutoStyleId { - export var Dirty: string; //'Dirty', - export var Error: string; //'Error', - export var NewRow: string; //'NewRow' + export var Dirty: string; // 'Dirty', + export var Error: string; // 'Error', + export var NewRow: string; // 'NewRow' } export enum RowHeaderStatePriorities { - Dirty, //10, - Transfer, //30, - CellError, //40, - Conflict, //50, - RowError, //60, - NewRow //90 + Dirty, // 10, + Transfer, // 30, + CellError, // 40, + Conflict, // 50, + RowError, // 60, + NewRow // 90 } export enum UpdateSerializeMode { - Cancel, //0, - Default, //1, - PropDataOnly, //2, - PropLocalizedOnly, //3, - PropBoth //4 + Cancel, // 0, + Default, // 1, + PropDataOnly, // 2, + PropLocalizedOnly, // 3, + PropBoth // 4 } export enum UpdateTrackingMode { - PropData, //2, - PropLocalized, //3, - PropBoth //4 + PropData, // 2, + PropLocalized, // 3, + PropBoth // 4 } export namespace UserAction { - export var UserEdit: string; //'User Edit':string; - export var DeleteRecord: string; //'Delete Record':string; - export var InsertRecord: string; //'Insert Record':string; - export var Indent: string; //'Indent':string; - export var Outdent: string; //'Outdent':string; - export var Fill: string; //'Fill':string; - export var Paste: string; //'Paste':string; - export var CutPaste: string; //'Cut/Paste' + export var UserEdit: string; // 'User Edit':string; + export var DeleteRecord: string; // 'Delete Record':string; + export var InsertRecord: string; // 'Insert Record':string; + export var Indent: string; // 'Indent':string; + export var Outdent: string; // 'Outdent':string; + export var Fill: string; // 'Fill':string; + export var Paste: string; // 'Paste':string; + export var CutPaste: string; // 'Cut/Paste' } export enum ReadOnlyActiveState { - ReadOnlyActive, //0, - ReadOnlyDisabled, //1 + ReadOnlyActive, // 0, + ReadOnlyDisabled, // 1 } // tslint:disable-next-line: interface-name @@ -10403,15 +10403,15 @@ declare namespace SP { gridFieldMap: { [name: string]: GridField }; columns: ColumnInfoCollection; - messageOverrides: any; //TODO - operationalConstantsFieldKeyMap: any; //TODO + messageOverrides: any; // TODO + operationalConstantsFieldKeyMap: any; // TODO ganttParams: GanttParameters; pivotedGridParams: PivotedGridParameters; rowViewParams: RowViewParameters; } export class PivotedGridParameters { - //this.dateRange = null; + // this.dateRange = null; // this.ganttBarStyles = null; // this.ganttZoomLevel = 3; // this.fnRenderGanttRow = null; @@ -10883,7 +10883,7 @@ declare namespace SP { bHyperlink: boolean; DataToLocalized(dataValue: any): string; GetAddress(dataValue: any): string; - /** Returns string like this: '"http://site.com, Site title"' */ + /** Returns string like this: '"http:// site.com, Site title"' */ GetCopyValue(record: IRecord, dataValue: any, locValue: string): string; toString(): string; } @@ -10950,7 +10950,7 @@ declare namespace SP { export interface IEditControlCellContext extends IEditActorCellContext { cellWidth: number; cellHeight: number; - cellStyle: any; //TODO: Determine correct type + cellStyle: any; // TODO: Determine correct type cellRect: any; NotifyExpandControl(): void; NotifyEditComplete(): void; diff --git a/sharepoint/sharepoint-tests.ts b/sharepoint/sharepoint-tests.ts index 9d75197d89..4c028d977c 100644 --- a/sharepoint/sharepoint-tests.ts +++ b/sharepoint/sharepoint-tests.ts @@ -3,8 +3,8 @@ import * as angular from 'angular'; import * as ng from 'angular'; -//code from http://sptypescript.codeplex.com/ -//BasicTasksJSOM.ts +// code from http://sptypescript.codeplex.com/ +// BasicTasksJSOM.ts // Website tasks function retrieveWebsite(resultpanel: HTMLElement) { var clientContext = SP.ClientContext.get_current(); @@ -613,7 +613,7 @@ namespace CSR { } - //typescripttempltes.ts + // typescripttempltes.ts declare var Strings: any; export function getFieldValue(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): any { if (ctx.ControlMode === SPClientTemplates.ClientControlMode.EditForm @@ -674,7 +674,7 @@ namespace CSR { export function getControl(schema: SPClientTemplates.FieldSchema_InForm): HTMLInputElement { var id = schema.Name + '_' + schema.Id + '_$' + schema.FieldType + 'Field'; - //TODO: Handle different input types + // TODO: Handle different input types return $get(id) as HTMLInputElement; } @@ -782,7 +782,7 @@ namespace CSR { return this.onPreRender((ctx: SPClientTemplates.RenderContext) => { var ctxInView = ctx as SPClientTemplates.RenderContext_InView; - //ListSchema schma exists in Form and in View render context + // ListSchema schma exists in Form and in View render context var fields = ctxInView.ListSchema.Field; if (fields) { for (var innerField of fields) { @@ -798,7 +798,7 @@ namespace CSR { return this.onPostRender((ctx: SPClientTemplates.RenderContext) => { var ctxInView = ctx as SPClientTemplates.RenderContext_InView; - //ListSchema schma exists in Form and in View render context + // ListSchema schma exists in Form and in View render context var fields = ctxInView.ListSchema.Field; if (fields) { for (var innerField of fields) { @@ -821,7 +821,7 @@ namespace CSR { if (ctx.ControlMode === SPClientTemplates.ClientControlMode.View) { var ctxInView = ctx as SPClientTemplates.RenderContext_InView; if (ctxInView.inGridMode) { - //TODO: Disable editing in grid mode + // TODO: Disable editing in grid mode } @@ -869,7 +869,7 @@ namespace CSR { var ctxInView = ctx as SPClientTemplates.RenderContext_InView; if (ctxInView.inGridMode) { - //TODO: Hide item in grid mode + // TODO: Hide item in grid mode } else { ctxInView.ListSchema.Field.splice(ctxInView.ListSchema.Field.indexOf(schema), 1); } @@ -1014,7 +1014,7 @@ namespace CSR { } else { var ctx = SP.ClientContext.get_current(); var web = ctx.get_web(); - //TODO: Handle lookup to another web + // TODO: Handle lookup to another web var list = web.get_lists().getById(listId); var item = list.getItemById(parseInt(value, 10)); var field = list.get_fields().getByInternalNameOrTitle(expressionParts.shift()); @@ -1059,7 +1059,7 @@ namespace CSR { pendingLoads++; var ctx = SP.ClientContext.get_current(); - //TODO: Handle lookup to another web + // TODO: Handle lookup to another web var web = ctx.get_web(); var listId = _schema.LookupListId; var list = !listname ? web.get_lists().getById(listId) : web.get_lists().getByTitle(listname); @@ -1070,7 +1070,7 @@ namespace CSR { return dependencyValues[expr] ? dependencyValues[expr] : ''; }); - //TODO: Handle ShowField attribure + // TODO: Handle ShowField attribure if (predicate.substr(0, 5) === ''); @@ -1336,14 +1336,14 @@ namespace CSR { query.set_queryText('contentclass:STS_ListItem ListID:{' + _schema.LookupListId + '} ' + value); var selectProps = query.get_selectProperties(); selectProps.clear(); - //TODO: Handle ShowField attribute + // TODO: Handle ShowField attribute selectProps.add('Title'); selectProps.add('ListItemId'); var executor = new Search.SearchExecutor(ctx); var result = executor.executeQuery(query); ctx.executeQueryAsync( () => { - //TODO: Discover proper way to load collection + // TODO: Discover proper way to load collection var tableCollection = new Search.ResultTableCollection(); tableCollection.initPropertiesFromJson(result.get_value()); @@ -1711,7 +1711,7 @@ if (typeof SP === 'object' && SP && typeof SP.SOD === 'object' && SP.SOD) { } -//mquery.ts +// mquery.ts @@ -1822,7 +1822,7 @@ m$.ready(() => { }); -//whoisapppart.ts +// whoisapppart.ts namespace _ { @@ -1842,7 +1842,7 @@ namespace _ { } }); - //Load the people picker + // Load the people picker function loadPeoplePicker(peoplePickerElementId: string) { var schema: ISPClientPeoplePickerSchema = { PrincipalAccountType: "User", @@ -1881,7 +1881,7 @@ namespace _ { var properties = personProperties.get_userProfileProperties(); var messageText = ""; for (var key in properties) { - if(properties.hasOwnProperty(key)) + if (properties.hasOwnProperty(key)) continue; messageText += "
    [" + key + "]: \"" + properties[key] + "\""; } @@ -1916,12 +1916,12 @@ namespace _ { function prepareVisual() { if (isIframe) { - //Create a Link element for the defaultcss.ashx resource + // Create a Link element for the defaultcss.ashx resource var linkElement = document.createElement('link'); linkElement.setAttribute('rel', 'stylesheet'); linkElement.setAttribute('href', spHostUrl + '/_layouts/15/defaultcss.ashx'); - //Add the linkElement as a child to the head section of the html + // Add the linkElement as a child to the head section of the html document.head.appendChild(linkElement); } else { @@ -1953,7 +1953,7 @@ namespace _ { } } -//taxonomy +// taxonomy namespace MySP { // Class @@ -2261,7 +2261,7 @@ namespace _ { }; -//publishing.ts +// publishing.ts // Variables used in various callbacks JSRequest.EnsureSetup(); @@ -2332,7 +2332,7 @@ function createPage(evt) { }); } -//likes +// likes namespace SampleReputation { interface MyList extends SPClientTemplates.RenderContext_InView { @@ -2428,7 +2428,7 @@ namespace SampleReputation { -//code from https://github.com/gandjustas/SharePointAngularTS +// code from https://github.com/gandjustas/SharePointAngularTS namespace App { "use strict"; var app = angular.module("app", []); diff --git a/sharepoint/tslint.json b/sharepoint/tslint.json index 192203ab54..e4f5db4fa0 100644 --- a/sharepoint/tslint.json +++ b/sharepoint/tslint.json @@ -1,3 +1,6 @@ { - "extends": "../tslint.json" -} \ No newline at end of file + "extends": "../tslint.json", + "rules": { + "max-line-length": false + } +} diff --git a/sharp/index.d.ts b/sharp/index.d.ts index ef2026a782..0776b80b81 100644 --- a/sharp/index.d.ts +++ b/sharp/index.d.ts @@ -19,7 +19,9 @@ declare namespace sharp { const gravity: sharp.GravityEnum; const strategy: sharp.StrategyEnum; /** - * Gets, or when options are provided sets, the limits of libvips' operation cache. Existing entries in the cache will be trimmed after any change in limits. This method always returns cache statistics, useful for determining how much working memory is required for a particular task. + * Gets, or when options are provided sets, the limits of libvips' operation cache. + * Existing entries in the cache will be trimmed after any change in limits. + * This method always returns cache statistics, useful for determining how much working memory is required for a particular task. * @param {boolean|sharp.CacheOptions} options Object with the cache options, or Boolean where true uses default cache settings and false removes all caching. * @returns {Object} */ @@ -221,13 +223,23 @@ declare namespace sharp { gamma(gamma?: number): SharpInstance; /** * Alternative spelling of greyscale. - * Convert to 8-bit greyscale; 256 shades of grey. This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use gamma() with greyscale() for the best results. By default the output image will be web-friendly sRGB and contain three (identical) color channels. This may be overridden by other sharp operations such as toColourspace('b-w'), which will produce an output image containing one color channel. An alpha channel may be present, and will be unchanged by the operation. + * Convert to 8-bit greyscale; 256 shades of grey. + * This is a linear operation. + * If the input image is in a non-linear colour space such as sRGB, use gamma() with greyscale() for the best results. + * By default the output image will be web-friendly sRGB and contain three (identical) color channels. + * This may be overridden by other sharp operations such as toColourspace('b-w'), which will produce an output image containing one color channel. + * An alpha channel may be present, and will be unchanged by the operation. * @param {boolean} grayscale true to enable and false to disable (defaults to true) * @returns {SharpInstance} A sharp instance that can be used to chain operations */ grayscale(grayscale?: boolean): SharpInstance; /** - * Convert to 8-bit greyscale; 256 shades of grey. This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use gamma() with greyscale() for the best results. By default the output image will be web-friendly sRGB and contain three (identical) color channels. This may be overridden by other sharp operations such as toColourspace('b-w'), which will produce an output image containing one color channel. An alpha channel may be present, and will be unchanged by the operation. + * Convert to 8-bit greyscale; 256 shades of grey. + * This is a linear operation. + * If the input image is in a non-linear colour space such as sRGB, use gamma() with greyscale() for the best results. + * By default the output image will be web-friendly sRGB and contain three (identical) color channels. + * This may be overridden by other sharp operations such as toColourspace('b-w'), which will produce an output image containing one color channel. + * An alpha channel may be present, and will be unchanged by the operation. * @param {boolean} greyscale true to enable and false to disable (defaults to true) * @returns {SharpInstance} A sharp instance that can be used to chain operations */ @@ -313,7 +325,11 @@ declare namespace sharp { toFile(fileOut: string): Promise; /** * Write output to a Buffer. JPEG, PNG, WebP, and RAW output are supported. By default, the format will match the input image, except GIF and SVG input which become PNG output. - * @param {Function} callback Callback function called on completion with three arguments (err, buffer, info). err is an error message, if any. buffer is the output image data. info contains the output image format, size (bytes), width, height and channels. A Promises/A+ promise is returned when callback is not provided. + * @param {Function} callback Callback function called on completion with three arguments (err, buffer, info). + * err is an error message, if any. + * buffer is the output image data. + * info contains the output image format, size (bytes), width, height and channels. + * A Promises/A+ promise is returned when callback is not provided. * @returns {SharpInstance} A sharp instance that can be used to chain operations */ toBuffer(callback: (err: Error, buffer: Buffer, info: OutputInfo) => void): SharpInstance; @@ -364,13 +380,16 @@ declare namespace sharp { */ toFormat(format: string | AvailableFormatInfo, options?: OutputOptions | JpegOptions | PngOptions): SharpInstance; /** - * Include all metadata (EXIF, XMP, IPTC) from the input image in the output image. The default behaviour, when withMetadata is not used, is to strip all metadata and convert to the device-independent sRGB colour space. This will also convert to and add a web-friendly sRGB ICC profile. + * Include all metadata (EXIF, XMP, IPTC) from the input image in the output image. + * The default behaviour, when withMetadata is not used, is to strip all metadata and convert to the device-independent sRGB colour space. + * This will also convert to and add a web-friendly sRGB ICC profile. * @param {Metadata} * @throws {Error} Invalid parameters. */ withMetadata(metadata?: Metadata): SharpInstance; /** - * Use tile-based deep zoom (image pyramid) output. Set the format and options for tile images via the toFormat, jpeg, png or webp functions. Use a .zip or .szi file extension with toFile to write to a compressed archive file format. + * Use tile-based deep zoom (image pyramid) output. Set the format and options for tile images via the toFormat, jpeg, png or webp functions. + * Use a .zip or .szi file extension with toFile to write to a compressed archive file format. * @param {TileOptions} options options */ tile(options: TileOptions): SharpInstance; diff --git a/sharp/sharp-tests.ts b/sharp/sharp-tests.ts index 00c318feb9..2ca348620a 100644 --- a/sharp/sharp-tests.ts +++ b/sharp/sharp-tests.ts @@ -9,14 +9,14 @@ const writableStream: NodeJS.WritableStream = createWriteStream(input); sharp(input) .extractChannel('green') - .toFile('input_green.jpg', function(err, info) { + .toFile('input_green.jpg', (err, info) => { // info.channels === 1 // input_green.jpg contains the green channel of the input image }); sharp('3-channel-rgb-input.png') .bandbool(sharp.bool.and) - .toFile('1-channel-output.png', function(err, info) { + .toFile('1-channel-output.png', (err, info) => { // The output will be a single channel image where each pixel `P = R & G & B`. // If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]` // then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`. @@ -34,7 +34,7 @@ sharp('input.png') quality: 90 }) .toBuffer() - .then(function(outputBuffer: Buffer) { + .then((outputBuffer: Buffer) => { // outputBuffer contains upside down, 300px wide, alpha channel flattened // onto orange background, composited with overlay.png with SE gravity, // sharpened, with metadata, 90% quality WebP image data. Phew! @@ -42,14 +42,14 @@ sharp('input.png') sharp('input.jpg') .resize(300, 200) - .toFile('output.jpg', function(err: Error) { + .toFile('output.jpg', (err: Error) => { // output.jpg is a 300 pixels wide and 200 pixels high image // containing a scaled and cropped version of input.jpg }); var transformer = sharp() .resize(300) - .on('info', function(info: sharp.OutputInfo) { + .on('info', (info: sharp.OutputInfo) => { console.log('Image height is ' + info.height); }); readableStream.pipe(transformer).pipe(writableStream); @@ -57,7 +57,7 @@ readableStream.pipe(transformer).pipe(writableStream); console.log(sharp.format); console.log(sharp.versions); -sharp.queue.on('change', function(queueLength: number) { +sharp.queue.on('change', (queueLength: number) => { console.log('Queue contains ' + queueLength + ' task(s)'); }); @@ -71,7 +71,7 @@ readableStream.pipe(pipeline); const image: sharp.SharpInstance = sharp(input); image .metadata() - .then(function(metadata: sharp.Metadata) { + .then((metadata: sharp.Metadata) => { if (metadata.width) { return image .resize(Math.round(metadata.width / 2)) @@ -79,14 +79,14 @@ image .toBuffer(); } }) - .then(function(data: Buffer) { + .then((data: Buffer) => { // data contains a WebP image half the width and height of the original JPEG }); pipeline = sharp() .rotate() .resize(undefined, 200) - .toBuffer(function(err: Error, outputBuffer: Buffer, info: sharp.OutputInfo) { + .toBuffer((err: Error, outputBuffer: Buffer, info: sharp.OutputInfo) => { // outputBuffer contains 200px high JPEG image data, // auto-rotated using EXIF Orientation tag // info.width and info.height contain the dimensions of the resized image @@ -95,7 +95,7 @@ readableStream.pipe(pipeline); sharp(input) .extract({ left: 0, top: 0, width: 100, height: 100 }) - .toFile("output", function(err: Error) { + .toFile("output", (err: Error) => { // Extract a region of the input image, saving in the same format. }); @@ -103,7 +103,7 @@ sharp(input) .extract({ left: 0, top: 0, width: 100, height: 100 }) .resize(200, 200) .extract({ left: 0, top: 0, width: 100, height: 100 }) - .toFile("output", function(err: Error) { + .toFile("output", (err: Error) => { // Extract a region, resize, then extract from the resized image }); @@ -121,7 +121,7 @@ sharp(input) kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1] }) .raw() - .toBuffer(function(err: Error, data: Buffer, info: sharp.OutputInfo) { + .toBuffer((err: Error, data: Buffer, info: sharp.OutputInfo) => { // data contains the raw pixel data representing the convolution // of the input image with the horizontal Sobel operator }); @@ -131,7 +131,7 @@ sharp('input.tiff') .tile({ size: 512 }) - .toFile('output.dz', function(err: Error, info: sharp.OutputInfo) { + .toFile('output.dz', (err: Error, info: sharp.OutputInfo) => { // output.dzi is the Deep Zoom XML definition // output_files contains 512x512 tiles grouped by zoom level }); @@ -144,7 +144,7 @@ sharp(input) .background('white') .embed() .toFile('output.tiff') - .then(function() { + .then(() => { // output.tiff is a 200 pixels wide and 300 pixels high image // containing a lanczos2/nohalo scaled version, embedded on a white canvas, // of the image data in inputBuffer @@ -153,7 +153,7 @@ sharp(input) transformer = sharp() .resize(200, 200) .crop(sharp.strategy.entropy) - .on('error', function(err: Error) { + .on('error', (err: Error) => { console.log(err); }); // Read image data from readableStream @@ -165,7 +165,7 @@ sharp('input.gif') .background({ r: 0, g: 0, b: 0, alpha: 0 }) .embed() .toFormat(sharp.format.webp) - .toBuffer(function(err: Error, outputBuffer: Buffer) { + .toBuffer((err: Error, outputBuffer: Buffer) => { if (err) { throw err; } @@ -178,7 +178,7 @@ sharp(input) .max() .toFormat('jpeg') .toBuffer() - .then(function(outputBuffer: Buffer) { + .then((outputBuffer: Buffer) => { // outputBuffer contains JPEG image data no wider than 200 pixels and no higher // than 200 pixels regardless of the inputBuffer image dimensions }); diff --git a/sheetify/sheetify-tests.ts b/sheetify/sheetify-tests.ts index 7287ba1499..931e05b579 100644 --- a/sheetify/sheetify-tests.ts +++ b/sheetify/sheetify-tests.ts @@ -1,8 +1,8 @@ import * as sheetify from 'sheetify'; -function done1 (err: Error, css: string, prefix: string) {}; -function done2 (err: Error, css: string) {}; -function done3 (err: Error) {}; +function done1(err: Error, css: string, prefix: string) {}; +function done2(err: Error, css: string) {}; +function done3(err: Error) {}; const test1 = sheetify('foobar'); const test2 = sheetify('foobar', {global: true}); @@ -15,6 +15,6 @@ const test8 = sheetify` .test { border: 1px soild black; } -` +`; const prefix = sheetify.getPrefix('boop'); \ No newline at end of file diff --git a/shelljs/index.d.ts b/shelljs/index.d.ts index 5e812947fd..a8f2196dab 100644 --- a/shelljs/index.d.ts +++ b/shelljs/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ShellJS v0.6.0 +// Type definitions for ShellJS v0.7.6 // Project: http://shelljs.org // Definitions by: Niklas Mollenhauer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -466,7 +466,7 @@ export interface ExecCallback { (code: number, stdout: string, stderr: string): any; } -export interface ExecOptions { +export interface ExecOptions extends child.ExecOptions { silent?: boolean; async?: boolean; } diff --git a/shelljs/shelljs-tests.ts b/shelljs/shelljs-tests.ts index a78b8e44e1..6c155e5aee 100644 --- a/shelljs/shelljs-tests.ts +++ b/shelljs/shelljs-tests.ts @@ -97,7 +97,7 @@ var pid = asyncVersion3.pid; shell.exec("node --version", { silent: true }, function (code, stdout, stderr) { var version = stdout; }); -shell.exec("node --version", { silent: true, async: true }, function (code, stdout, stderr) { +shell.exec("node --version", { silent: true, async: true, cwd: '/usr/local/bin' }, function (code, stdout, stderr) { var version = stdout; }); shell.exec("node --version", function (code, stdout, stderr) { diff --git a/shipit/index.d.ts b/shipit/index.d.ts index 8c614f1627..187b8c1f7d 100644 --- a/shipit/index.d.ts +++ b/shipit/index.d.ts @@ -7,57 +7,54 @@ import * as fs from "fs"; import * as child_process from "child_process"; +import * as shipit from "./index"; // Used for `typeof shipit` -declare namespace shipit { - type LocalOrRemoteCommand = (command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void) => PromiseLike; - type EmptyCallback = () => void; - type TaskExecution = (name: string, depsOrFn: string[] | EmptyCallback, fn: () => void) => any; +type LocalOrRemoteCommand = (command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void) => PromiseLike; +type EmptyCallback = () => void; +type TaskExecution = (name: string, depsOrFn: string[] | EmptyCallback, fn: () => void) => any; - interface Options { - environment: string; - stderr: fs.WriteStream; - stdout: fs.WriteStream; - } - - interface ShipitLocal { - child: child_process.ChildProcess; - stderr: fs.WriteStream; - stdout: fs.WriteStream; - } - - interface Tasks { - [name: string]: Task; - } - - interface Task { - blocking: boolean; - dep: string[]; - fn: () => void; - name: string; - } - - export function blTask(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): any; - export function emit(name: string): any; - export function initConfig(config: {}): typeof shipit; - export function local(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; - export function log(log: any): void; - export function log(...log: any[]): void; - export function on(name: string, callback: (e: any) => void): any; - export function remote(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; - export function remoteCopy(src: string, dest: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; - export function start(tasks: string | string[]): typeof shipit; - export function start(...tasks: string[]): typeof shipit; - export function task(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): typeof shipit; - - export var config: {}; - export var domain: any; - export var doneCallback: any; - export var environment: string; - export var seq: any[]; - export var tasks: Tasks; - export var isRunning: boolean; +interface Options { + environment: string; + stderr: fs.WriteStream; + stdout: fs.WriteStream; } -//tslint:disable-next-line:export-just-namespace -export = shipit; +interface ShipitLocal { + child: child_process.ChildProcess; + stderr: fs.WriteStream; + stdout: fs.WriteStream; +} + +interface Tasks { + [name: string]: Task; +} + +interface Task { + blocking: boolean; + dep: string[]; + fn: () => void; + name: string; +} + +export function blTask(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): any; +export function emit(name: string): any; +export function initConfig(config: {}): typeof shipit; +export function local(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; +export function log(log: any): void; +export function log(...log: any[]): void; +export function on(name: string, callback: (e: any) => void): any; +export function remote(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; +export function remoteCopy(src: string, dest: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; +export function start(tasks: string | string[]): typeof shipit; +export function start(...tasks: string[]): typeof shipit; +export function task(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): typeof shipit; + +export var config: {}; +export var domain: any; +export var doneCallback: any; +export var environment: string; +export var seq: any[]; +export var tasks: Tasks; +export var isRunning: boolean; + export as namespace shipit; diff --git a/siema/tslint.json b/siema/tslint.json index f9e30021f4..377cc837d4 100644 --- a/siema/tslint.json +++ b/siema/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/simple-oauth2/simple-oauth2-tests.ts b/simple-oauth2/simple-oauth2-tests.ts index 290ac6fc31..7a47078a71 100644 --- a/simple-oauth2/simple-oauth2-tests.ts +++ b/simple-oauth2/simple-oauth2-tests.ts @@ -13,13 +13,13 @@ const credentials = { }; // Initialize the OAuth2 Library -//const oauth2 = require('simple-oauth2').create(credentials); +// const oauth2 = require('simple-oauth2').create(credentials); import oauth2lib = require("simple-oauth2"); const oauth2 = oauth2lib.create(credentials); // #Authorization Code flow -(function () { +(() => { // Authorization oauth2 URI const authorizationUri = oauth2.authorizationCode.authorizeURL({ @@ -29,7 +29,7 @@ const oauth2 = oauth2lib.create(credentials); }); // Redirect example using Express (see http://expressjs.com/api.html#res.redirect) - //res.redirect(authorizationUri); + // res.redirect(authorizationUri); // Get the access token object (the authorization code is given from the previous step). const tokenConfig = { @@ -60,7 +60,7 @@ const oauth2 = oauth2lib.create(credentials); // #Client Credentials Flow -(function () { +(() => { const tokenConfig = {}; // Callbacks @@ -88,12 +88,12 @@ const oauth2 = oauth2lib.create(credentials); // #Access Token object -(function () { +(() => { // Sample of a JSON access token (you got it through previous steps) const tokenObject = { - 'access_token': '', - 'refresh_token': '', - 'expires_in': '7200' + access_token: '', + refresh_token: '', + expires_in: '7200' }; // Create the access token wrapper @@ -104,7 +104,7 @@ const oauth2 = oauth2lib.create(credentials); // Callbacks token.refresh((error, result) => { token = result; - }) + }); // Promises token.refresh() diff --git a/simple-peer/tslint.json b/simple-peer/tslint.json index ec365f164b..377cc837d4 100644 --- a/simple-peer/tslint.json +++ b/simple-peer/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/sip.js/index.d.ts b/sip.js/index.d.ts index be01cd3682..d4e6bcebf1 100644 --- a/sip.js/index.d.ts +++ b/sip.js/index.d.ts @@ -182,7 +182,10 @@ declare namespace sipjs { on(name: 'addStream' | 'userMedia', callback: (stream: any) => void): void; on(name: 'userMediaFailed', callback: (error: string) => void): void; on(name: 'iceCandidate', callback: (candidate: any) => void): void; - on(name: 'iceGathering' | 'iceGatheringComplete' | 'iceConnection' | 'iceConnectionChecking' | 'iceConnectionConnected' | 'iceConnectionCompleted' | 'iceConnectionFailed' | 'iceConnectionDisconnected' | 'iceConnectionClosed' | string, callback: () => void): void; + on( + name: 'iceGathering' | 'iceGatheringComplete' | 'iceConnection' | 'iceConnectionChecking' | 'iceConnectionConnected' | 'iceConnectionCompleted' | 'iceConnectionFailed' | + 'iceConnectionDisconnected' | 'iceConnectionClosed' | string, + callback: () => void): void; on(name: 'dataChannel' | 'getDescription' | 'setDescription', callback: (sdpWrapper: { type: string, sdp: string }) => void): void; } } diff --git a/sip.js/sip.js-tests.ts b/sip.js/sip.js-tests.ts index 524caf1827..b817b8e2c8 100644 --- a/sip.js/sip.js-tests.ts +++ b/sip.js/sip.js-tests.ts @@ -55,7 +55,7 @@ ua.stop(); ua.register(); ua = ua.register({ extraHeaders: [""] }); -ua.unregister() +ua.unregister(); ua.unregister({ extraHeaders: [""], all: true }); const isConnected: boolean = ua.isConnected(); @@ -78,7 +78,7 @@ const inviteOptions: sipjs.InviteOptions = { rel100: "", inviteWithoutSdp: true, RTCConstraints: {} -} +}; session = ua.invite("", inviteOptions); diff --git a/slug/slug-tests.ts b/slug/slug-tests.ts index 101155e3ce..5ba9aa7f29 100644 --- a/slug/slug-tests.ts +++ b/slug/slug-tests.ts @@ -1,28 +1,28 @@ -import slug = require('slug') -var print = console.log.bind(console, '>') +import slug = require('slug'); +var print = console.log.bind(console, '>'); -print(slug('i ♥ unicode')) +print(slug('i ♥ unicode')); // > i-love-unicode -print(slug('unicode ♥ is ☢')) // yes! +print(slug('unicode ♥ is ☢')); // yes! // > unicode-love-is-radioactive -print(slug('i ♥ unicode', '_')) // If you prefer something else then `-` as seperator +print(slug('i ♥ unicode', '_')); // If you prefer something else then `-` as seperator // > i_love_unicode -slug.charmap['♥'] = 'freaking love' // change default charmap or use option {charmap:{…}} as 2. argument -print(slug('I ♥ UNICODE')) +slug.charmap['♥'] = 'freaking love'; // change default charmap or use option {charmap:{…}} as 2. argument +print(slug('I ♥ UNICODE')); // > I-freaking-love-UNICODE -print(slug('☏-Number', {lower: true})) // If you prefer lower case +print(slug('☏-Number', {lower: true})); // If you prefer lower case // > telephone-number -print(slug('i <3 unicode')) +print(slug('i <3 unicode')); // > i-love-unicode // options is either object or replacement (sets options.replacement) slug('string', { } || 'replacement'); -slug.defaults.mode ='pretty'; +slug.defaults.mode = 'pretty'; slug.defaults.modes['rfc3986'] = { replacement: '-', // replace spaces with replacement symbols: true, // replace unicode symbols or not diff --git a/soap/index.d.ts b/soap/index.d.ts index 8cb9c43424..151e914f63 100644 --- a/soap/index.d.ts +++ b/soap/index.d.ts @@ -10,6 +10,10 @@ import * as events from 'events'; interface Security { } +export interface SoapMethod { + (args: any, callback: (err: any, result: any) => void, options?: any, extraHeaders?: any): void; +} + export class WSSecurity implements Security { constructor(username: string, password: string, options?: any); } @@ -19,12 +23,22 @@ export class ClientSSLSecurity implements Security { constructor(key: Buffer | string, cert: Buffer | string, defaults?: any); } -interface Client extends events.EventEmitter { - setSecurity(s: Security): void; - [method: string]: (args: any, fn: (err: any, result: any) => void, options?: any, extraHeaders?: any) => void; - addSoapHeader(headJSON: any): void; - setEndpoint(endpoint: string): void; +export interface Client extends events.EventEmitter { + addBodyAttribute(bodyAttribute: any, name?: string, namespace?: string, xmlns?: string): void; + addHttpHeader(name: string, value: any): void; + addSoapHeader(soapHeader: any, name?: string, namespace?: string, xmlns?: string): number; + changeSoapHeader(index: number, soapHeader: any, name?: string, namespace?: string, xmlns?: string): void; + clearBodyAttributes(): void; + clearHttpHeaders(): void; + clearSoapHeaders(): void; describe(): any; + getBodyAttributes(): any[]; + getHttpHeaders(): any[]; + getSoapHeaders(): any[]; + setEndpoint(endpoint: string): void; + setSOAPAction(action: string): void; + setSecurity(s: Security): void; + [method: string]: SoapMethod | Function; } export interface Server extends events.EventEmitter { diff --git a/soap/soap-tests.ts b/soap/soap-tests.ts index 48b2e2317e..9771b26efc 100644 --- a/soap/soap-tests.ts +++ b/soap/soap-tests.ts @@ -1,4 +1,3 @@ - import * as soap from 'soap'; import * as events from 'events'; import * as fs from "fs"; @@ -14,18 +13,28 @@ soap.createClient(url, wsdlOptions, function(err: any, client: soap.Client) { client.setSecurity(new soap.ClientSSLSecurity('/path/to/key', '/path/to/cert', '/path/to/ca', defaults)); client.setSecurity(new soap.ClientSSLSecurity('/path/to/key', '/path/to/cert', defaults)); client.setSecurity(new soap.ClientSSLSecurity('/path/to/key', '/path/to/cert', '/path/to/ca')); - client.addSoapHeader({}); client.setEndpoint('http://localhost'); - client['create']({ name: 'value' }, function(err, result) { + client.describe(); + client.addBodyAttribute({}); + client.addHttpHeader('test', true); + client.addSoapHeader({}); + client.changeSoapHeader(0, {}); + client.clearBodyAttributes(); + client.clearHttpHeaders(); + client.clearSoapHeaders(); + client.getBodyAttributes(); + client.getHttpHeaders(); + client.getSoapHeaders(); + client.setSOAPAction('action'); + (client['create'] as soap.SoapMethod)({ name: 'value' }, function(err: any, result: any) { // result is an object }); - client['create']({ name: 'value' }, function(err, result) { + (client['create'] as soap.SoapMethod)({ name: 'value' }, function(err: any, result: any) { // result is an object }, {}); client.on('request', function(obj: any) { //obj is an object }); - client.describe(); }); var myService = { diff --git a/socket.io/index.d.ts b/socket.io/index.d.ts index bf46ca1160..2333dc8fe2 100644 --- a/socket.io/index.d.ts +++ b/socket.io/index.d.ts @@ -180,7 +180,7 @@ declare namespace SocketIO { /** * Closes the server connection */ - close():void; + close( fn ?: () => void ):void; /** * The event fired when we get a new connection diff --git a/socket.io/socket.io-tests.ts b/socket.io/socket.io-tests.ts index 442e677751..ea3d97e21f 100644 --- a/socket.io/socket.io-tests.ts +++ b/socket.io/socket.io-tests.ts @@ -143,3 +143,14 @@ function testUsingItJustAsACrossBrowserWebSocket() { socket.on('disconnect', function () { }); }); } + +function testClosingServerWithCallback() { + var io = socketIO.listen(80); + io.close(function() { + }); +} + +function testClosingServerWithoutCallback() { + var io = socketIO.listen(80); + io.close(); +} diff --git a/spatialite/spatialite-tests.ts b/spatialite/spatialite-tests.ts index eef51b3c18..0edf111cc1 100644 --- a/spatialite/spatialite-tests.ts +++ b/spatialite/spatialite-tests.ts @@ -44,8 +44,8 @@ function insertRows() { function readAllRows() { console.log("readAllRows lorem"); - db.all("SELECT rowid AS id, info FROM lorem", function(err, rows) { - rows.forEach(function (row) { + db.all("SELECT rowid AS id, info FROM lorem", (err, rows) => { + rows.forEach(row => { console.log(row.id + ": " + row.info); }); readSomeRows(); @@ -54,7 +54,7 @@ function readAllRows() { function readSomeRows() { console.log("readAllRows lorem"); - db.each("SELECT rowid AS id, info FROM lorem WHERE rowid < ? ", 5, function(err, row) { + db.each("SELECT rowid AS id, info FROM lorem WHERE rowid < ? ", 5, (err, row) => { console.log(row.id + ": " + row.info); }, closeDb); } @@ -70,7 +70,7 @@ function runChainExample() { runChainExample(); -db.serialize(function() { +db.serialize(() => { db.run("CREATE TABLE lorem (info TEXT)"); var stmt = db.prepare("INSERT INTO lorem VALUES (?)"); @@ -79,15 +79,15 @@ db.serialize(function() { } stmt.finalize(); - db.each("SELECT rowid AS id, info FROM lorem", function(err, row) { + db.each("SELECT rowid AS id, info FROM lorem", (err, row) => { console.log(row.id + ": " + row.info); }); }); -db.serialize(function() { +db.serialize(() => { // These two queries will run sequentially. db.run("CREATE TABLE foo (num)"); - db.run("INSERT INTO foo VALUES (?)", 1, function(err) { + db.run("INSERT INTO foo VALUES (?)", 1, err => { // These queries will run in parallel and the second query will probably // fail because the table might not exist yet. db.run("CREATE TABLE bar (num)"); @@ -107,7 +107,7 @@ db.run("UPDATE tbl SET name = $name WHERE id = $id", { $name: "bar" }); db.run("UPDATE tbl SET name = $name WHERE id = $id", { $id: 2, $name: "bar" }, - function(err) { } + err => { } ); db.run("UPDATE tbl SET name = ?5 WHERE id = ?", { diff --git a/spatialite/tsconfig.json b/spatialite/tsconfig.json index 6ad0b96035..ddcef0c7ac 100644 --- a/spatialite/tsconfig.json +++ b/spatialite/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "spatialite-tests.ts" ] -} +} \ No newline at end of file diff --git a/sqlite3/sqlite3-tests.ts b/sqlite3/sqlite3-tests.ts index 5e13fd7840..75a8c2e72c 100644 --- a/sqlite3/sqlite3-tests.ts +++ b/sqlite3/sqlite3-tests.ts @@ -27,8 +27,8 @@ function insertRows() { function readAllRows() { console.log("readAllRows lorem"); - db.all("SELECT rowid AS id, info FROM lorem", function(err, rows) { - rows.forEach(function (row) { + db.all("SELECT rowid AS id, info FROM lorem", (err, rows) => { + rows.forEach(row => { console.log(row.id + ": " + row.info); }); readSomeRows(); @@ -37,7 +37,7 @@ function readAllRows() { function readSomeRows() { console.log("readAllRows lorem"); - db.each("SELECT rowid AS id, info FROM lorem WHERE rowid < ? ", 5, function(err, row) { + db.each("SELECT rowid AS id, info FROM lorem WHERE rowid < ? ", 5, (err, row) => { console.log(row.id + ": " + row.info); }, closeDb); } @@ -53,7 +53,7 @@ function runChainExample() { runChainExample(); -db.serialize(function() { +db.serialize(() => { db.run("CREATE TABLE lorem (info TEXT)"); var stmt = db.prepare("INSERT INTO lorem VALUES (?)"); @@ -62,15 +62,15 @@ db.serialize(function() { } stmt.finalize(); - db.each("SELECT rowid AS id, info FROM lorem", function(err, row) { + db.each("SELECT rowid AS id, info FROM lorem", (err, row) => { console.log(row.id + ": " + row.info); }); }); -db.serialize(function() { +db.serialize(() => { // These two queries will run sequentially. db.run("CREATE TABLE foo (num)"); - db.run("INSERT INTO foo VALUES (?)", 1, function(err) { + db.run("INSERT INTO foo VALUES (?)", 1, err => { // These queries will run in parallel and the second query will probably // fail because the table might not exist yet. db.run("CREATE TABLE bar (num)"); @@ -90,7 +90,7 @@ db.run("UPDATE tbl SET name = $name WHERE id = $id", { $name: "bar" }); db.run("UPDATE tbl SET name = $name WHERE id = $id", { $id: 2, $name: "bar" }, - function(err) { } + err => { } ); db.run("UPDATE tbl SET name = ?5 WHERE id = ?", { diff --git a/sshpk/index.d.ts b/sshpk/index.d.ts index 05d26053b6..0bc2274120 100644 --- a/sshpk/index.d.ts +++ b/sshpk/index.d.ts @@ -365,7 +365,8 @@ declare namespace SshPK { export function parseCertificate(data: string|Buffer, format: string, options?: any): Certificate; export function createSelfSignedCertificate(subjectOrSubjects: string, key: Key, options?: any): Certificate; - export function createCertificate(subjectOrSubjects: string, key: Key, issuer: string, + export function createCertificate( + subjectOrSubjects: string, key: Key, issuer: string, issuerKey: PrivateKey, options?: any): Certificate; export function identityFromDN(dn: string): Identity; diff --git a/steed/index.d.ts b/steed/index.d.ts index ba4b199999..4865c8efa8 100644 --- a/steed/index.d.ts +++ b/steed/index.d.ts @@ -3,22 +3,21 @@ // Definitions by: Paul Isache // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare namespace steed { interface Dictionary { [key: string]: T; } - interface ErrorCallback { (err?: T): void; } + type ErrorCallback = (err?: T) => void; - interface SteedResultCallback { (err: E, result: T): void; } - interface SteedResultArrayCallback { (err: E, results: T[]): void; } - interface SteedResultObjectCallback { (err: E, results: Dictionary): void; } + type SteedResultCallback = (err: E, result: T) => void; + type SteedResultArrayCallback = (err: E, results: T[]) => void; + type SteedResultObjectCallback = (err: E, results: Dictionary) => void; - interface SteedWorker { (task: T, callback: ErrorCallback): void; } - interface SteedIterator { (item: T, callback: ErrorCallback): void; } - interface SteedResultIterator { (item: T, callback: SteedResultCallback): void; } - interface SteedFunction { (callback: (err?: E, result?: T) => void): void; } + type SteedWorker = (task: T, callback: ErrorCallback) => void; + type SteedIterator = (item: T, callback: ErrorCallback) => void; + type SteedResultIterator = (item: T, callback: SteedResultCallback) => void; + type SteedFunction = (callback: (err?: E, result?: T) => void) => void; interface SteedQueue { - push(task: T | T[], callback?: ErrorCallback | SteedResultCallback): void; + push(task: T | T[], callback?: SteedResultCallback): void; unshift(task: T | T[], callback?: ErrorCallback): void; pause(): void; resume(): void; diff --git a/steed/steed-tests.ts b/steed/steed-tests.ts index 685654cc52..dd89e4480b 100644 --- a/steed/steed-tests.ts +++ b/steed/steed-tests.ts @@ -1,6 +1,6 @@ /// -import steed = require('steed') +import steed = require('steed'); declare var path: { exists: (path: string, callback?: (error: Error, exists: boolean) => any) => void; @@ -10,133 +10,133 @@ function funcStringCbErrBoolean(v: string, cb: (error: Error, res: boolean) => v function callback() { } steed.parallel([ - function () { }, - function () { } + () => {}, + () => {} ], callback); steed.series([ - function () { }, - function () { } + () => {}, + () => {} ]); var data: any[] = []; function steedProcess(item: any, callback: (error: Error, result: any) => void) { } -steed.map(data, steedProcess, function (error, results) { +steed.map(data, steedProcess, (error, results) => { console.log(results); }); var openFiles = ['file1', 'file2']; -var saveFile = function (file: string, cb: (error: Error) => void) { } -steed.each(openFiles, saveFile, function (error: Error) { }); -steed.eachSeries(openFiles, saveFile, function (error: Error) { }); +var saveFile = (file: string, cb: (error: Error) => void) => {}; +steed.each(openFiles, saveFile, (error: Error) => {}); +steed.eachSeries(openFiles, saveFile, (error: Error) => {}); // Control Flow // steed.series([ - function (callback) { + callback => { callback(undefined, 'one'); }, - function (callback) { + callback => { callback(undefined, 'two'); }, ], - function (error, results) { }); + (error, results) => {}); steed.series([ - function (callback) { + callback => { callback(undefined, 'one'); }, - function (callback) { + callback => { callback(undefined, 'two'); }, ], - function (error, results) { }); + (error, results) => {}); steed.series({ - one: function (callback) { - setTimeout(function () { + one(callback) { + setTimeout(() => { callback(undefined, 1); }, 200); }, - two: function (callback) { - setTimeout(function () { + two(callback) { + setTimeout(() => { callback(undefined, 2); }, 100); }, }, - function (error, results) { }); + (error, results) => {}); steed.series({ - one: function (callback) { - setTimeout(function () { + one(callback) { + setTimeout(() => { callback(undefined, 1); }, 200); }, - two: function (callback) { - setTimeout(function () { + two(callback) { + setTimeout(() => { callback(undefined, 2); }, 100); }, }, - function (error, results) { }); + (error, results) => {}); steed.parallel([ - function (callback) { - setTimeout(function () { + callback => { + setTimeout(() => { callback(undefined, 'one'); }, 200); }, - function (callback) { - setTimeout(function () { + callback => { + setTimeout(() => { callback(undefined, 'two'); }, 100); }, ], - function (error, results) { }); + (error, results) => {}); steed.parallel([ - function (callback) { - setTimeout(function () { + callback => { + setTimeout(() => { callback(undefined, 'one'); }, 200); }, - function (callback) { - setTimeout(function () { + callback => { + setTimeout(() => { callback(undefined, 'two'); }, 100); }, ], - function (error, results) { }); + (error, results) => {}); steed.parallel({ - one: function (callback) { - setTimeout(function () { + one(callback) { + setTimeout(() => { callback(undefined, 1); }, 200); }, - two: function (callback) { - setTimeout(function () { + two(callback) { + setTimeout(() => { callback(undefined, 2); }, 100); }, }, - function (error, results) { }); + (error, results) => {}); steed.parallel({ - one: function (callback) { - setTimeout(function () { + one(callback) { + setTimeout(() => { callback(undefined, 1); }, 200); }, - two: function (callback) { - setTimeout(function () { + two(callback) { + setTimeout(() => { callback(undefined, 2); }, 100); }, }, - function (error, results) { }); + (error, results) => {}); function whileFn(callback: any) { count++; @@ -147,100 +147,100 @@ function whileTest() { return count < 5; } var count = 0; steed.waterfall([ - function (callback: any) { + (callback: any) => { callback(null, 'one', 'two'); }, - function (arg1: any, arg2: any, callback: any) { + (arg1: any, arg2: any, callback: any) => { callback(null, 'three'); }, - function (arg1: any, callback: any) { + (arg1: any, callback: any) => { callback(null, 'done'); } -], function (error, result) { }); +], (error, result) => {}); -var q = steed.queue(function (task: any, callback: () => void) { +var q = steed.queue((task: any, callback: () => void) => { console.log('hello ' + task.name); callback(); }, 2); -q.drain = function () { +q.drain = () => { console.log('all items have been processed'); -} +}; q.push({ name: 'foo' }); -q.push({ name: 'bar' }, function (err) { +q.push({ name: 'bar' }, err => { console.log('finished processing bar'); }); -q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (error: Error) { +q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], (error: Error) => { console.log('finished processing bar'); }); q.unshift({ name: 'foo' }); -q.unshift({ name: 'bar' }, function (err) { +q.unshift({ name: 'bar' }, err => { console.log('finished processing bar'); }); -q.unshift([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (error: Error) { +q.unshift([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], (error: Error) => { console.log('finished processing bar'); }); var qLength: number = q.length(); var qIsIdle: boolean = q.idle(); -q.saturated = function () { +q.saturated = () => { console.log('queue is saturated.'); -} +}; -q.empty = function () { +q.empty = () => { console.log('queue is empty.'); -} +}; -q.drain = function () { +q.drain = () => { console.log('queue was drained.'); -} +}; q.pause(); q.resume(); q.kill(); // tests for strongly typed tasks -var q2 = steed.queue(function (task: string, callback: () => void) { +var q2 = steed.queue((task: string, callback: () => void) => { console.log('Task: ' + task); callback(); }, 1); q2.push('task1'); -q2.push('task2', function (error) { +q2.push('task2', error => { console.log('Finished tasks'); }); -q2.push(['task3', 'task4', 'task5'], function (error: Error) { +q2.push(['task3', 'task4', 'task5'], (error: Error) => { console.log('Finished tasks'); }); q2.unshift('task1'); -q2.unshift('task2', function (error) { +q2.unshift('task2', error => { console.log('Finished tasks'); }); -q2.unshift(['task3', 'task4', 'task5'], function (error: Error) { +q2.unshift(['task3', 'task4', 'task5'], (error: Error) => { console.log('Finished tasks'); }); steed.parallel([ - function (callback: (error: Error, val: string) => void) { }, - function (callback) { } + (callback: (error: Error, val: string) => void) => { }, + callback => {} ], - function (error: Error, results: Array) { + (error: Error, results: string[]) => { steed.series([ - function (callback) { }, + callback => { }, function email_link(callback) { } ]); }); @@ -248,11 +248,11 @@ steed.parallel([ // each steed.each({ - "a": 1, - "b": 2 -}, function (val: number, next: steed.ErrorCallback): void { + a: 1, + b: 2 +}, (val: number, next: steed.ErrorCallback): void => { - setTimeout(function (): void { + setTimeout((): void => { console.log(`steed.each: ${val}`); @@ -260,18 +260,18 @@ steed.each({ }, 500); -}, function (err?: Error): void { +}, (err?: Error): void => { console.log("steed.each: done."); }); steed.eachSeries({ - "a": 1, - "b": 2 -}, function (val: number, next: steed.ErrorCallback): void { + a: 1, + b: 2 +}, (val: number, next: steed.ErrorCallback): void => { - setTimeout(function (): void { + setTimeout((): void => { console.log(`steed.eachSeries: ${val}`); @@ -279,7 +279,7 @@ steed.eachSeries({ }, 500); -}, function (err?: Error): void { +}, (err?: Error): void => { console.log("steed.eachSeries: done."); @@ -288,12 +288,12 @@ steed.eachSeries({ // map steed.map({ - "a": 1, - "b": 2, - "c": 3 -}, function (val: number, next: steed.SteedResultCallback): void { + a: 1, + b: 2, + c: 3 +}, (val: number, next: steed.SteedResultCallback): void => { - setTimeout(function (): void { + setTimeout((): void => { console.log(`steed.map: ${val}`); @@ -301,19 +301,19 @@ steed.map({ }, 500); -}, function (error: Error, results: string[]): void { +}, (error: Error, results: string[]): void => { console.log("steed.map: done with results", results); }); steed.mapSeries({ - "a": 1, - "b": 2, - "c": 3 -}, function (val: number, next: steed.SteedResultCallback): void { + a: 1, + b: 2, + c: 3 +}, (val: number, next: steed.SteedResultCallback): void => { - setTimeout(function (): void { + setTimeout((): void => { console.log(`steed.mapSeries: ${val}`); @@ -321,8 +321,8 @@ steed.mapSeries({ }, 500); -}, function (error: Error, results: string[]): void { +}, (error: Error, results: string[]): void => { console.log("steed.mapSeries: done with results", results); -}); \ No newline at end of file +}); diff --git a/steed/tsconfig.json b/steed/tsconfig.json index ec8377c527..54a669803d 100644 --- a/steed/tsconfig.json +++ b/steed/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "steed-tests.ts" ] -} +} \ No newline at end of file diff --git a/steed/tslint.json b/steed/tslint.json new file mode 100644 index 0000000000..f05741c59b --- /dev/null +++ b/steed/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/strip-ansi/strip-ansi-tests.ts b/strip-ansi/strip-ansi-tests.ts index 6d38a0ed49..12e60b5e82 100644 --- a/strip-ansi/strip-ansi-tests.ts +++ b/strip-ansi/strip-ansi-tests.ts @@ -1,4 +1,4 @@ import stripAnsi = require('strip-ansi'); stripAnsi('\u001b[4mcake\u001b[0m'); -//=> 'cake' \ No newline at end of file +// => 'cake' \ No newline at end of file diff --git a/strip-bom/strip-bom-tests.ts b/strip-bom/strip-bom-tests.ts index dc63d80303..79aaa3daae 100644 --- a/strip-bom/strip-bom-tests.ts +++ b/strip-bom/strip-bom-tests.ts @@ -1,4 +1,4 @@ import stripBom = require('strip-bom'); stripBom('\uFEFFunicorn'); -//=> 'unicorn' \ No newline at end of file +// => 'unicorn' \ No newline at end of file diff --git a/stripe/index.d.ts b/stripe/index.d.ts index 24803eeadf..3e5d902060 100644 --- a/stripe/index.d.ts +++ b/stripe/index.d.ts @@ -1,6 +1,10 @@ // Type definitions for stripe 2.x // Project: https://stripe.com/ -// Definitions by: Andy Hawkins , Eric J. Smith , Amrit Kahlon , Adam Cmiel , Justin Leider +// Definitions by: Andy Hawkins +// Eric J. Smith +// Amrit Kahlon +// Adam Cmiel +// Justin Leider // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare const Stripe: StripeStatic; diff --git a/stripe/tslint.json b/stripe/tslint.json index f9e30021f4..377cc837d4 100644 --- a/stripe/tslint.json +++ b/stripe/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/strong-cluster-control/index.d.ts b/strong-cluster-control/index.d.ts index e0bb92b82f..5037aed03b 100644 --- a/strong-cluster-control/index.d.ts +++ b/strong-cluster-control/index.d.ts @@ -43,7 +43,7 @@ declare namespace StrongClusterControl { * @description Start the controller * @param [options] - An options object, no default, and options object is not required. * @param [options.size] - Number of workers that should be running, the default is to not control the number of workers - * @param [options.env=null] - Environment properties object passed to cluster.fork() if the controller has to start a worker to resize the cluster, default is null. + * @param [options.env=null] - Environment properties object passed to cluster.fork() if the controller has to start a worker to resize the cluster, default is null. * @param [options.shutdownTimeout=5000] - Number of milliseconds to wait after shutdown before terminating a worker, the default is 5 seconds * @param [options.terminateTimeout=5000] - Number of milliseconds to wait after terminate before killing a worker, the default is 5 seconds * @param [options.throttoleDelay] - Number of milliseconds to delay restarting workers after they are exiting abnormally. Abnormal is defined as as not suicide. diff --git a/strong-cluster-control/tsconfig.json b/strong-cluster-control/tsconfig.json index 3623adaea2..6d625c44b6 100644 --- a/strong-cluster-control/tsconfig.json +++ b/strong-cluster-control/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "strong-cluster-control-tests.ts" ] -} +} \ No newline at end of file diff --git a/supertest-as-promised/index.d.ts b/supertest-as-promised/index.d.ts index db0bf18e81..385f25867b 100644 --- a/supertest-as-promised/index.d.ts +++ b/supertest-as-promised/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for SuperTest as Promised v2.0.2 +// Type definitions for SuperTest as Promised 2.0 // Project: https://github.com/WhoopInc/supertest-as-promised // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/supertest-as-promised/supertest-as-promised-tests.ts b/supertest-as-promised/supertest-as-promised-tests.ts index d6eb5771c9..c20f9a92b6 100644 --- a/supertest-as-promised/supertest-as-promised-tests.ts +++ b/supertest-as-promised/supertest-as-promised-tests.ts @@ -10,13 +10,13 @@ var app = express(); request(app) .get("/user") .expect(200) - .then(function (res) { + .then(res => { return request(app) .post("/kittens") .send({ userId: res}) .expect(201); }) - .then(function (res) { + .then(res => { // ... }); @@ -25,12 +25,12 @@ request(app) request(app) .get("/kittens") .expect(200) - .then(function (res) { + .then(res => { // ... }); -describe("GET /kittens", function () { - it("should work", function () { +describe("GET /kittens", () => { + it("should work", () => { return request(app).get("/kittens").expect(200); }); }); @@ -41,18 +41,18 @@ var agent = request.agent(app); agent .get("/ugly-kitteh") .expect(404) - .then(function () { + .then(() => { // ... - }) + }); // Promisey goodness request(app) .get("/kittens") .expect(201) - .then(function (res) { /* ... */ }) + .then(res => { /* ... */ }) // I'm a real promise now! - .catch(function (err) { /* ... */ }) + .catch(err => { /* ... */ }); request(app) .get("/kittens") @@ -60,4 +60,4 @@ request(app) .toPromise() // I'm a real promise now! .delay(10) - .then(function (res) { /* ... */ }) + .then(res => { /* ... */ }); diff --git a/supertest-as-promised/tslint.json b/supertest-as-promised/tslint.json new file mode 100644 index 0000000000..105f5736e6 --- /dev/null +++ b/supertest-as-promised/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "no-empty-interface": false + } +} diff --git a/swagger-express-mw/swagger-express-mw-tests.ts b/swagger-express-mw/swagger-express-mw-tests.ts index 78fc26889c..a066071758 100644 --- a/swagger-express-mw/swagger-express-mw-tests.ts +++ b/swagger-express-mw/swagger-express-mw-tests.ts @@ -1,8 +1,8 @@ import * as SwaggerExpress from "swagger-express-mw"; import * as express from "express"; -let app = express(); -let config: SwaggerExpress.Config = { +const app = express(); +const config: SwaggerExpress.Config = { appRoot: __dirname }; @@ -17,12 +17,12 @@ SwaggerExpress.create(config, (err, middleware) => { }); -let swaggerSecurityHandlerCb = (err: Error) => { - //do nothing +const swaggerSecurityHandlerCb = (err: Error) => { + // do nothing }; -let configComplex: SwaggerExpress.Config = { +const configComplex: SwaggerExpress.Config = { appRoot: __dirname, configDir: "some/directory", controllersDirs: ["some/directory"], @@ -32,7 +32,7 @@ let configComplex: SwaggerExpress.Config = { swaggerSecurityHandlers: { // did not manage to research the typings of first 3 arguments someHandlerName: ({}, {}, {}, swaggerSecurityHandlerCb) => { - //do nothing + // do nothing } }, validateResponse: true diff --git a/swagger-hapi/swagger-hapi-tests.ts b/swagger-hapi/swagger-hapi-tests.ts index 50d3954975..3d894aafba 100644 --- a/swagger-hapi/swagger-hapi-tests.ts +++ b/swagger-hapi/swagger-hapi-tests.ts @@ -9,7 +9,7 @@ var config = { appRoot: __dirname // required config } as SwaggerHapi.Config; -SwaggerHapi.create(config, function(err, swaggerHapi) { +SwaggerHapi.create(config, (err, swaggerHapi) => { if (err) { throw err; } var port = process.env.PORT || 10010; @@ -19,22 +19,22 @@ SwaggerHapi.create(config, function(err, swaggerHapi) { // }; if (swaggerHapi.config.swagger !== undefined) { - let appRootFromMw = swaggerHapi.config.swagger.appRoot; + const appRootFromMw = swaggerHapi.config.swagger.appRoot; } - app.register(swaggerHapi.plugin, function(err) { + app.register(swaggerHapi.plugin, err => { if (err) { return console.error("Failed to load plugin:", err); } // stat app etc.. }); }); -let swaggerSecurityHandlerCb = (err: Error) => { - //do nothing +const swaggerSecurityHandlerCb = (err: Error) => { + // do nothing }; -let configComplex: SwaggerHapi.Config = { +const configComplex: SwaggerHapi.Config = { appRoot: __dirname, configDir: "some/directory", controllersDirs: ["some/directory"], @@ -44,7 +44,7 @@ let configComplex: SwaggerHapi.Config = { swaggerSecurityHandlers: { // did not manage to research the typings of first 3 arguments someHandlerName: ({}, {}, {}, swaggerSecurityHandlerCb) => { - //do nothing + // do nothing } }, validateResponse: true diff --git a/swagger-node-runner/swagger-node-runner-tests.ts b/swagger-node-runner/swagger-node-runner-tests.ts index 49538d3825..cff8e9d570 100644 --- a/swagger-node-runner/swagger-node-runner-tests.ts +++ b/swagger-node-runner/swagger-node-runner-tests.ts @@ -5,17 +5,17 @@ import * as Hapi from "hapi"; import * as restify from "restify"; import * as sails from "sails.io.js"; -let config: SwaggerNodeRunner.Config = { +const config: SwaggerNodeRunner.Config = { appRoot: __dirname }; // Express middleware -let expressApp = express(); +const expressApp = express(); SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; // or handle error } - let expressMiddleware = runner.expressMiddleware(); + const expressMiddleware = runner.expressMiddleware(); expressMiddleware.register(expressApp); const port = process.env.PORT || 10010; @@ -23,14 +23,14 @@ SwaggerNodeRunner.create(config, (err, runner) => { }); -//Connect middleware -let connectApp = connect(); +// Connect middleware +const connectApp = connect(); SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; } - let conncetMiddleware = runner.connectMiddleware(); + const connectMiddleware = runner.connectMiddleware(); - conncetMiddleware.register(connectApp); + connectMiddleware.register(connectApp); var port = process.env.PORT || 10010; connectApp.listen(port); }); @@ -40,16 +40,16 @@ SwaggerNodeRunner.create(config, (err, runner) => { SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; } - let sailsMw = runner.sailsMiddleware(); - if(typeof sailsMw.chain !== 'function' || !sailsMw.runner) { + const sailsMw = runner.sailsMiddleware(); + if (typeof sailsMw.chain !== 'function' || !sailsMw.runner) { // do nothing } }); -//Hapi Middleware +// Hapi Middleware var hapiapp = new Hapi.Server(); -SwaggerNodeRunner.create(config, function(err, runner) { +SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; } var port = process.env.PORT || 10010; @@ -57,15 +57,15 @@ SwaggerNodeRunner.create(config, function(err, runner) { // hapiapp.address = function() { // return { port }; // }; - let hapiMiddleware = runner.hapiMiddleware(); + const hapiMiddleware = runner.hapiMiddleware(); if (hapiMiddleware.config.swagger !== undefined) { - let appRootFromMw = hapiMiddleware.config.swagger.appRoot; + const appRootFromMw = hapiMiddleware.config.swagger.appRoot; } - let pluginAttributes = hapiMiddleware.plugin.register.attributes.name + hapiMiddleware.plugin.register.attributes.version; + const pluginAttributes = hapiMiddleware.plugin.register.attributes.name + hapiMiddleware.plugin.register.attributes.version; - hapiapp.register(hapiMiddleware.plugin, function(err) { + hapiapp.register(hapiMiddleware.plugin, err => { if (err) { return console.error("Failed to load plugin:", err); } // stat app etc.. }); @@ -73,25 +73,25 @@ SwaggerNodeRunner.create(config, function(err, runner) { // Restify Middelware -let app = restify.createServer(); -SwaggerNodeRunner.create(config, function(err, runner) { +const app = restify.createServer(); +SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; } - let restifyMiddelware = runner.restifyMiddleware() + const restifyMiddelware = runner.restifyMiddleware(); restifyMiddelware.register(app); - let port = process.env.PORT || 10010; + const port = process.env.PORT || 10010; app.listen(port); }); -let swaggerSecurityHandlerCb = (err: Error) => { - //do nothing +const swaggerSecurityHandlerCb = (err: Error) => { + // do nothing }; -let configComplex: SwaggerNodeRunner.Config = { +const configComplex: SwaggerNodeRunner.Config = { appRoot: __dirname, configDir: "some/directory", controllersDirs: ["some/directory"], @@ -101,7 +101,7 @@ let configComplex: SwaggerNodeRunner.Config = { swaggerSecurityHandlers: { // did not manage to research the typings of first 3 arguments someHandlerName: ({}, {}, {}, swaggerSecurityHandlerCb) => { - //do nothing + // do nothing } }, validateResponse: true diff --git a/swagger-parser/tslint.json b/swagger-parser/tslint.json index ec365f164b..377cc837d4 100644 --- a/swagger-parser/tslint.json +++ b/swagger-parser/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/swagger-restify-mw/swagger-restify-mw-tests.ts b/swagger-restify-mw/swagger-restify-mw-tests.ts index c8bd436c7c..73568b2153 100644 --- a/swagger-restify-mw/swagger-restify-mw-tests.ts +++ b/swagger-restify-mw/swagger-restify-mw-tests.ts @@ -1,28 +1,28 @@ import * as SwaggerRestify from "swagger-restify-mw"; import * as restify from "restify"; -let app = restify.createServer(); +const app = restify.createServer(); -let config = { +const config = { appRoot: __dirname // required config } as SwaggerRestify.Config; -SwaggerRestify.create(config, function(err, swaggerRestify) { +SwaggerRestify.create(config, (err, swaggerRestify) => { if (err) { throw err; } swaggerRestify.register(app); - let port = process.env.PORT || 10010; + const port = process.env.PORT || 10010; app.listen(port); }); -let swaggerSecurityHandlerCb = (err: Error) => { - //do nothing +const swaggerSecurityHandlerCb = (err: Error) => { + // do nothing }; -let configComplex: SwaggerRestify.Config = { +const configComplex: SwaggerRestify.Config = { appRoot: __dirname, configDir: "some/directory", controllersDirs: ["some/directory"], @@ -32,7 +32,7 @@ let configComplex: SwaggerRestify.Config = { swaggerSecurityHandlers: { // did not manage to research the typings of first 3 arguments someHandlerName: ({}, {}, {}, swaggerSecurityHandlerCb) => { - //do nothing + // do nothing } }, validateResponse: true diff --git a/swagger-sails-hook/swagger-sails-hook-tests.ts b/swagger-sails-hook/swagger-sails-hook-tests.ts index ee023047c3..c1b73a08b7 100644 --- a/swagger-sails-hook/swagger-sails-hook-tests.ts +++ b/swagger-sails-hook/swagger-sails-hook-tests.ts @@ -11,8 +11,8 @@ const mockSailsApp = { }; // create and register hook -let swaggerHookRef = swaggerSailsHook(mockSailsApp); -if(typeof swaggerHookRef.routes.after['/*'] === 'function') { +const swaggerHookRef = swaggerSailsHook(mockSailsApp); +if (typeof swaggerHookRef.routes.after['/*'] === 'function') { // right type } diff --git a/swagger-schema-official/swagger-schema-official-tests.ts b/swagger-schema-official/swagger-schema-official-tests.ts index 79eedfa076..42e35483ea 100644 --- a/swagger-schema-official/swagger-schema-official-tests.ts +++ b/swagger-schema-official/swagger-schema-official-tests.ts @@ -1,5 +1,7 @@ import * as swagger from "swagger-schema-official"; +// tslint:disable:max-line-length + const apiExample: swagger.Spec = { "swagger": "2.0", "info": { diff --git a/swagger-schema-official/tslint.json b/swagger-schema-official/tslint.json index ec365f164b..6721a6962c 100644 --- a/swagger-schema-official/tslint.json +++ b/swagger-schema-official/tslint.json @@ -1,3 +1,6 @@ { - "extends": "../tslint.json" + "extends": "../tslint.json", + "rules": { + "object-literal-key-quotes": false + } } diff --git a/swiper/swiper-tests.ts b/swiper/swiper-tests.ts index 3fc9b3c185..6decd155e0 100644 --- a/swiper/swiper-tests.ts +++ b/swiper/swiper-tests.ts @@ -239,22 +239,22 @@ function dynamicSlides() { paginationClickable: true, spaceBetween: 30, }); - document.querySelector('.prepend-2-slides').addEventListener('click', function (e) { + document.querySelector('.prepend-2-slides').addEventListener('click', e => { e.preventDefault(); swiper.prependSlide([ '
    Slide ' + (--prependNumber) + '
    ', '
    Slide ' + (--prependNumber) + '
    ' ]); }); - document.querySelector('.prepend-slide').addEventListener('click', function (e) { + document.querySelector('.prepend-slide').addEventListener('click', e => { e.preventDefault(); swiper.prependSlide('
    Slide ' + (--prependNumber) + '
    '); }); - document.querySelector('.append-slide').addEventListener('click', function (e) { + document.querySelector('.append-slide').addEventListener('click', e => { e.preventDefault(); swiper.appendSlide('
    Slide ' + (++appendNumber) + '
    '); }); - document.querySelector('.append-2-slides').addEventListener('click', function (e) { + document.querySelector('.append-2-slides').addEventListener('click', e => { e.preventDefault(); swiper.appendSlide([ '
    Slide ' + (++appendNumber) + '
    ', @@ -269,14 +269,14 @@ function thumbsGalleryLoop() { prevButton: '.swiper-button-prev', spaceBetween: 10, loop: true, - loopedSlides: 5, //looped slides should be the same + loopedSlides: 5, // looped slides should be the same }); var galleryThumbs = new Swiper('.gallery-thumbs', { spaceBetween: 10, slidesPerView: 4, touchRatio: 0.2, loop: true, - loopedSlides: 5, //looped slides should be the same + loopedSlides: 5, // looped slides should be the same slideToClickedSlide: true }); galleryTop.params.control = galleryThumbs; @@ -365,7 +365,7 @@ function customPagination() { var swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', paginationClickable: true, - paginationBulletRender: function (swiper, index, className) { + paginationBulletRender(swiper, index, className) { return '' + (index + 1) + ''; } }); @@ -388,41 +388,41 @@ function customPlugin() { /* ======== Debugger plugin, simple demo plugin to console.log some of callbacks ======== */ - Swiper.prototype.plugins.debugger = function (swiper: any, params: any) { + Swiper.prototype.plugins.debugger = (swiper: any, params: any) => { if (!params) return; // Need to return object with properties that names are the same as callbacks return { - onInit: function (swiper: any) { + onInit(swiper: any) { console.log('onInit'); }, - onClick: function (swiper: any, e: any) { + onClick(swiper: any, e: any) { console.log('onClick'); }, - onTap: function (swiper: any, e: any) { + onTap(swiper: any, e: any) { console.log('onTap'); }, - onDoubleTap: function (swiper: any, e: any) { + onDoubleTap(swiper: any, e: any) { console.log('onDoubleTap'); }, - onSliderMove: function (swiper: any, e: any) { + onSliderMove(swiper: any, e: any) { console.log('onSliderMove'); }, - onSlideChangeStart: function (swiper: any) { + onSlideChangeStart(swiper: any) { console.log('onSlideChangeStart'); }, - onSlideChangeEnd: function (swiper: any) { + onSlideChangeEnd(swiper: any) { console.log('onSlideChangeEnd'); }, - onTransitionStart: function (swiper: any) { + onTransitionStart(swiper: any) { console.log('onTransitionStart'); }, - onTransitionEnd: function (swiper: any) { + onTransitionEnd(swiper: any) { console.log('onTransitionEnd'); }, - onReachBeginning: function (swiper: any) { + onReachBeginning(swiper: any) { console.log('onReachBeginning'); }, - onReachEnd: function (swiper: any) { + onReachEnd(swiper: any) { console.log('onReachEnd'); } }; @@ -440,30 +440,30 @@ function scrollContainer() { } // 32-slideable-menu.html function slideableMenu() { - var toggleMenu = function () { - if (swiper.previousIndex == 0) - swiper.slidePrev() + var toggleMenu = () => { + if (swiper.previousIndex === 0) + swiper.slidePrev(); } , menuButton = document.getElementsByClassName('menu-button')[0] , swiper = new Swiper('.swiper-container', { slidesPerView: 'auto' , initialSlide: 1 , resistanceRatio: .00000000000001 - , onSlideChangeStart: function (slider) { - if (slider.activeIndex == 0) { - menuButton.classList.add('cross') - menuButton.removeEventListener('click', toggleMenu, false) + , onSlideChangeStart: (slider) => { + if (slider.activeIndex === 0) { + menuButton.classList.add('cross'); + menuButton.removeEventListener('click', toggleMenu, false); } else - menuButton.classList.remove('cross') + menuButton.classList.remove('cross'); } - , onSlideChangeEnd: function (slider) { - if (slider.activeIndex == 0) - menuButton.removeEventListener('click', toggleMenu, false) + , onSlideChangeEnd: (slider) => { + if (slider.activeIndex === 0) + menuButton.removeEventListener('click', toggleMenu, false); else - menuButton.addEventListener('click', toggleMenu, false) + menuButton.addEventListener('click', toggleMenu, false); } , slideToClickedSlide: true - }) + }); } // 33-responsive-breakpoints.html function responsiveBreakpoints() { @@ -499,7 +499,7 @@ function autoheight() { paginationClickable: true, nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', - autoHeight: true, //enable auto height + autoHeight: true, // enable auto height }); } // 35-effect-flip.html diff --git a/swiper/tslint.json b/swiper/tslint.json index fd1872c1cb..0b14fdec0d 100644 --- a/swiper/tslint.json +++ b/swiper/tslint.json @@ -1,6 +1,6 @@ { "extends": "../tslint.json", "rules": { - "no-single-declare-module": false + "no-single-declare-module": false } -} \ No newline at end of file +} diff --git a/swiper/v2/swiper-tests.ts b/swiper/v2/swiper-tests.ts index 12abcc8944..ad1180a352 100644 --- a/swiper/v2/swiper-tests.ts +++ b/swiper/v2/swiper-tests.ts @@ -14,12 +14,12 @@ function defaultDemo() { paginationClickable: true }); - $('.arrow-left').on('click', function (e) { + $('.arrow-left').on('click', e => { e.preventDefault(); mySwiper.swipePrev(); }); - $('.arrow-right').on('click', function (e) { + $('.arrow-right').on('click', e => { e.preventDefault(); mySwiper.swipeNext(); }); @@ -40,7 +40,7 @@ function dynamicSlides() { pagination: '.pagination', paginationClickable: true }); - + function randomColor() { var colors = ('blue red green orange pink').split(' '); return colors[Math.floor(Math.random() * colors.length)]; @@ -48,41 +48,41 @@ function dynamicSlides() { var count = 4; - $('.sdl-append').click(function (e) { + $('.sdl-append').click(e => { e.preventDefault(); - mySwiper.appendSlide('
    Slide ' + (++count) + '
    ', 'swiper-slide ' + randomColor() + '-slide') + mySwiper.appendSlide('
    Slide ' + (++count) + '
    ', 'swiper-slide ' + randomColor() + '-slide'); }); - $('.sdl-prepend').click(function (e) { + $('.sdl-prepend').click(e => { e.preventDefault(); - mySwiper.prependSlide('
    Slide ' + (++count) + '
    ', 'swiper-slide ' + randomColor() + '-slide') + mySwiper.prependSlide('
    Slide ' + (++count) + '
    ', 'swiper-slide ' + randomColor() + '-slide'); }); - $('.sdl-swap').click(function (e) { + $('.sdl-swap').click(e => { e.preventDefault(); mySwiper .getFirstSlide() .insertAfter(1); }); - $('.sdl-insert').click(function (e) { + $('.sdl-insert').click(e => { e.preventDefault(); mySwiper .createSlide('
    Slide ' + (++count) + '
    ', 'swiper-slide ' + randomColor() + '-slide') .insertAfter(0); }); - $('.sdl-remove1').click(function (e) { + $('.sdl-remove1').click(e => { e.preventDefault(); mySwiper.removeSlide(0); }); - $('.sdl-removel').click(function (e) { + $('.sdl-removel').click(e => { e.preventDefault(); mySwiper.removeLastSlide(); }); - $('.sdl-remove2').click(function (e) { + $('.sdl-remove2').click(e => { e.preventDefault(); mySwiper.removeSlide(1); }); @@ -108,7 +108,7 @@ function freeMode() { }); } -// 06-carousel-mode.html +// 06-carousel-mode.html function carouselMode() { var mySwiper = new Swiper('.swiper-container', { pagination: '.pagination', @@ -174,14 +174,14 @@ function tabs() { speed: 500 }); - $(".tabs a").on('touchstart mousedown', function (e) { + $(".tabs a").on('touchstart mousedown', e => { e.preventDefault(); $(".tabs .active").removeClass('active'); $(this).addClass('active'); tabsSwiper.swipeTo($(this).index()); }); - $(".tabs a").click(function (e) { + $(".tabs a").click(e => { e.preventDefault(); }); } @@ -190,20 +190,20 @@ function tabs() { function tabsFeedback() { var tabsSwiper = new Swiper('.swiper-container', { speed: 500, - onSlideChangeStart: function () { + onSlideChangeStart: () => { $(".tabs .active").removeClass('active'); $(".tabs a").eq(tabsSwiper.activeIndex).addClass('active'); } }); - $(".tabs a").on('touchstart mousedown', function (e) { + $(".tabs a").on('touchstart mousedown', e => { e.preventDefault(); $(".tabs .active").removeClass('active'); $(this).addClass('active'); tabsSwiper.swipeTo($(this).index()); }); - $(".tabs a").click(function (e) { + $(".tabs a").click(e => { e.preventDefault(); }); } @@ -256,7 +256,7 @@ function visibilityApi() { }); } -// 17 - responsive.html +// 17 - responsive.html function responsive() { var mySwiper = new Swiper('.swiper-container', { pagination: '.pagination', diff --git a/swiper/v2/tsconfig.json b/swiper/v2/tsconfig.json index 963c1c24f6..6ef8f1f2c8 100644 --- a/swiper/v2/tsconfig.json +++ b/swiper/v2/tsconfig.json @@ -1,7 +1,10 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6", + "dom" + ], "noImplicitAny": true, "noImplicitThis": false, "strictNullChecks": false, diff --git a/swiper/v2/tslint.json b/swiper/v2/tslint.json index 506ccb3b24..8ab1b996c9 100644 --- a/swiper/v2/tslint.json +++ b/swiper/v2/tslint.json @@ -4,4 +4,4 @@ "no-single-declare-module": false, "dt-header": false } -} \ No newline at end of file +} diff --git a/systemjs/index.d.ts b/systemjs/index.d.ts index 44bee39900..876e4fdb4d 100644 --- a/systemjs/index.d.ts +++ b/systemjs/index.d.ts @@ -319,6 +319,17 @@ declare namespace SystemJSLoader { */ set(moduleName: string, module: any): void; + /** + * Resolves module name to normalized URL. + */ + resolve(moduleName: string, parentName?: string): Promise; + + /** + * Resolves module name to normalized URL. + * Synchronous alternative to `SystemJS.resolve`. + */ + resolveSync(moduleName: string, parentName?: string): string; + /** * In CommonJS environments, SystemJS will substitute the global require as needed by the module format being * loaded to ensure the correct detection paths in loaded code. diff --git a/table/table-tests.ts b/table/table-tests.ts index 4dc6541bb5..f3f4662b69 100644 --- a/table/table-tests.ts +++ b/table/table-tests.ts @@ -8,8 +8,6 @@ const data = [ ['john', 'doe'] ]; -const config: table.TableUserConfig = { - border: border -}; +const config: table.TableUserConfig = { border }; table.table(data, config); diff --git a/tcomb/index.d.ts b/tcomb/index.d.ts index 4b00616e26..abfa163b98 100644 --- a/tcomb/index.d.ts +++ b/tcomb/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for tcomb v1.0.3 +// Type definitions for tcomb 1.0 // Project: http://gcanti.github.io/tcomb/guide/index.html // Definitions by: Hans Windhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -26,14 +26,14 @@ declare namespace TComb { Func: Func_Static; func: { (domain: TCombBase[], codomain: TCombBase, name?: string): Func_Static; - (domain: TCombBase, codomain: TCombBase, name?: string) : Func_Static; - } + (domain: TCombBase, codomain: TCombBase, name?: string): Func_Static; + }; Err: Err_Static; Re: Re_Static; Dat: Dat_Static; Type: Type_Static; - irreducible: (name: string, is: TypePredicate) => TCombBase; - struct: (props: Object, name?: string) => Struct_Static; + irreducible(name: string, is: TypePredicate): TCombBase; + struct(props: Object, name?: string): Struct_Static; Union: Union_Static; Maybe: Maybe_Static; @@ -43,15 +43,15 @@ declare namespace TComb { maybe(type: TCombBase, name?: string): Maybe_Static; Tuple: Tuple_Static; - tuple:(types: TCombBase[], name?: string)=> Tuple_Static; + tuple(types: TCombBase[], name?: string): Tuple_Static; Subtype: Subtype_Static; List: List_Static; - list:(type: TCombBase, name?: string)=> List_Static; + list(type: TCombBase, name?: string): List_Static; Dict: Dict_Static; - dict:(domain: TCombBase, codomain: TCombBase, name?: string)=> Dict_Static; + dict(domain: TCombBase, codomain: TCombBase, name?: string): Dict_Static; subtype(type: TCombBase, predicate: TypePredicate, name?: string): Subtype_Static; @@ -260,7 +260,7 @@ declare namespace TComb { * @param name - Useful for debugging purposes. */ - export module enums { + export namespace enums { /** * @param keys - Array of enums. * @param name - Useful for debugging purposes. diff --git a/tcomb/tcomb-tests.ts b/tcomb/tcomb-tests.ts index d34d6feec8..02982faae7 100644 --- a/tcomb/tcomb-tests.ts +++ b/tcomb/tcomb-tests.ts @@ -6,9 +6,11 @@ // tests adapted from/for tcomb's test folder +// tslint:disable:no-construct + 'use strict'; import assert = require('assert'); -var t = require('../index'); +import t = require("tcomb"); var Any = t.Any; var Nil = t.Nil; @@ -38,11 +40,11 @@ var format = t.format; // setup // -var ok = function (x:any) { assert.strictEqual(true, x); }; -var ko = function (x:any) { assert.strictEqual(false, x); }; +var ok = (x: any) => { assert.strictEqual(true, x); }; +var ko = (x: any) => { assert.strictEqual(false, x); }; var eq = assert.deepEqual; -var throwsWithMessage = function (f:any, message:any) { - assert.throws(f, function (err:any) { +var throwsWithMessage = (f: any, message: any) => { + assert.throws(f, (err: any) => { ok(err instanceof Error); eq(err.message, message); return true; @@ -50,30 +52,30 @@ var throwsWithMessage = function (f:any, message:any) { }; var doesNotThrow = assert.doesNotThrow; -var noop = function () {}; +var noop = () => {}; var Point = struct({ x: Num, y: Num }); -describe('update', function () { +describe('update', () => { var update = t.update; var Tuple = tuple([Str, Num]); var List = list(Num); var Dict = dict(Str, Num); - it('should handle $set command', function () { + it('should handle $set command', () => { var instance = 1; var actual = update(instance, {$set: 2}); eq(actual, 2); var instance2 = [1, 2, 3]; - actual = update(instance2, {1: {'$set': 4}}); + actual = update(instance2, {1: {$set: 4}}); eq(instance2, [1, 2, 3]); eq(actual, [1, 4, 3]); }); - it('$set and null value, fix #65', function () { + it('$set and null value, fix #65', () => { var NullStruct = struct({a: Num, b: maybe(Num)}); var instance = new NullStruct({a: 1}); var updated = update(instance, {b: {$set: 2}}); @@ -81,76 +83,74 @@ describe('update', function () { eq(updated, {a: 1, b: 2}); }); - it('should handle $apply command', function () { - var $apply = function (n:any) { return n + 1; }; + it('should handle $apply command', () => { + var $apply = (n: any) => n + 1; var instance = 1; - var actual = update(instance, {$apply: $apply}); + var actual = update(instance, {$apply}); eq(actual, 2); var instance2 = [1, 2, 3]; - actual = update(instance2, {1: {'$apply': $apply}}); + actual = update(instance2, {1: {$apply}}); eq(instance2, [1, 2, 3]); eq(actual, [1, 3, 3]); }); - it('should handle $unshift command', function () { - var actual = update([1, 2, 3], {'$unshift': [4]}); + it('should handle $unshift command', () => { + var actual = update([1, 2, 3], {$unshift: [4]}); eq(actual, [4, 1, 2, 3]); - actual = update([1, 2, 3], {'$unshift': [4, 5]}); + actual = update([1, 2, 3], {$unshift: [4, 5]}); eq(actual, [4, 5, 1, 2, 3]); - actual = update([1, 2, 3], {'$unshift': [[4, 5]]}); + actual = update([1, 2, 3], {$unshift: [[4, 5]]}); eq(actual, [[4, 5], 1, 2, 3]); }); - it('should handle $push command', function () { - var actual = update([1, 2, 3], {'$push': [4]}); + it('should handle $push command', () => { + var actual = update([1, 2, 3], {$push: [4]}); eq(actual, [1, 2, 3, 4]); - actual = update([1, 2, 3], {'$push': [4, 5]}); + actual = update([1, 2, 3], {$push: [4, 5]}); eq(actual, [1, 2, 3, 4, 5]); - actual = update([1, 2, 3], {'$push': [[4, 5]]}); + actual = update([1, 2, 3], {$push: [[4, 5]]}); eq(actual, [1, 2, 3, [4, 5]]); }); - it('should handle $splice command', function () { + it('should handle $splice command', () => { var instance = [1, 2, {a: [12, 17, 15]}]; var actual = update(instance, {2: {a: {$splice: [[1, 1, 13, 14]]}}}); eq(instance, [1, 2, {a: [12, 17, 15]}]); eq(actual, [1, 2, {a: [12, 13, 14, 15]}]); }); - it('should handle $remove command', function () { + it('should handle $remove command', () => { var instance = {a: 1, b: 2}; - var actual = update(instance, {'$remove': ['a']}); + var actual = update(instance, {$remove: ['a']}); eq(instance, {a: 1, b: 2}); eq(actual, {b: 2}); }); - it('should handle $swap command', function () { + it('should handle $swap command', () => { var instance = [1, 2, 3, 4]; - var actual = update(instance, {'$swap': {from: 1, to: 2}}); + var actual = update(instance, {$swap: {from: 1, to: 2}}); eq(instance, [1, 2, 3, 4]); eq(actual, [1, 3, 2, 4]); }); - describe('structs', function () { + describe('structs', () => { var instance = new Point({x: 0, y: 1}); - it('should handle $set command', function () { + it('should handle $set command', () => { var updated = update(instance, {x: {$set: 1}}); eq(instance, {x: 0, y: 1}); eq(updated, {x: 1, y: 1}); }); - it('should handle $apply command', function () { - var updated = update(instance, {x: {$apply: function (x:any) { - return x + 2; - }}}); + it('should handle $apply command', () => { + var updated = update(instance, {x: {$apply: (x: any) => x + 2}}); eq(instance, {x: 0, y: 1}); eq(updated, {x: 2, y: 1}); }); - it('should handle $merge command', function () { - var updated = update(instance, {'$merge': {x: 2, y: 2}}); + it('should handle $merge command', () => { + var updated = update(instance, {$merge: {x: 2, y: 2}}); eq(instance, {x: 0, y: 1}); eq(updated, {x: 2, y: 2}); var Nested = struct({ @@ -162,78 +162,78 @@ describe('update', function () { }) }); instance = new Nested({a: 1, b: {c: 2, d: 3, e: 4}}); - updated = update(instance, {b: {'$merge': {c: 5, e: 6}}}); + updated = update(instance, {b: {$merge: {c: 5, e: 6}}}); eq(instance, {a: 1, b: {c: 2, d: 3, e: 4}}); eq(updated, {a: 1, b: {c: 5, d: 3, e: 6}}); }); }); - describe('tuples', function () { + describe('tuples', () => { var instance = Tuple(['a', 1]); - it('should handle $set command', function () { + it('should handle $set command', () => { var updated = update(instance, {0: {$set: 'b'}}); eq(updated, ['b', 1]); }); }); - describe('lists', function () { + describe('lists', () => { var instance = List([1, 2, 3, 4]); - it('should handle $set command', function () { + it('should handle $set command', () => { var updated = update(instance, {2: {$set: 5}}); eq(updated, [1, 2, 5, 4]); }); - it('should handle $splice command', function () { + it('should handle $splice command', () => { var updated = update(instance, {$splice: [[1, 2, 5, 6]]}); eq(updated, [1, 5, 6, 4]); }); - it('should handle $concat command', function () { + it('should handle $concat command', () => { var updated = update(instance, {$push: [5]}); eq(updated, [1, 2, 3, 4, 5]); updated = update(instance, {$push: [5, 6]}); eq(updated, [1, 2, 3, 4, 5, 6]); }); - it('should handle $prepend command', function () { + it('should handle $prepend command', () => { var updated = update(instance, {$unshift: [5]}); eq(updated, [5, 1, 2, 3, 4]); updated = update(instance, {$unshift: [5, 6]}); eq(updated, [5, 6, 1, 2, 3, 4]); }); - it('should handle $swap command', function () { + it('should handle $swap command', () => { var updated = update(instance, {$swap: {from: 1, to: 2}}); eq(updated, [1, 3, 2, 4]); }); }); - describe('dicts', function () { + describe('dicts', () => { var instance = Dict({a: 1, b: 2}); - it('should handle $set command', function () { + it('should handle $set command', () => { var updated = update(instance, {a: {$set: 2}}); eq(updated, {a: 2, b: 2}); }); - it('should handle $remove command', function () { + it('should handle $remove command', () => { var updated = update(instance, {$remove: ['a']}); eq(updated, {b: 2}); }); }); - describe('memory saving', function () { + describe('memory saving', () => { - it('should reuse members that are not updated', function () { + it('should reuse members that are not updated', () => { var Struct = struct({ a: Num, b: Str, @@ -244,7 +244,7 @@ describe('update', function () { a: 1, b: 'one', c: [1000, 1000000] - },{ + }, { a: 2, b: 'two', c: [2000, 2000000] @@ -262,9 +262,9 @@ describe('update', function () { }); }); - describe('all together now', function () { + describe('all together now', () => { - it('should handle mixed commands', function () { + it('should handle mixed commands', () => { var Struct = struct({ a: Num, b: Tuple, @@ -291,7 +291,7 @@ describe('update', function () { }); }); - it('should handle nested structures', function () { + it('should handle nested structures', () => { var Struct = struct({ a: struct({ b: tuple([ @@ -323,42 +323,42 @@ describe('update', function () { // assert // -describe('assert', function () { +describe('assert', () => { var assert = t.assert; - it('should nor throw when guard is true', function () { + it('should nor throw when guard is true', () => { assert(true); }); - it('should throw a default message', function () { - throwsWithMessage(function () { + it('should throw a default message', () => { + throwsWithMessage(() => { assert(1 === 2 + 1); }, 'assert failed'); }); - it('should throw the specified message', function () { - throwsWithMessage(function () { + it('should throw the specified message', () => { + throwsWithMessage(() => { assert(1 === 2 + 1, 'my message'); }, 'my message'); }); - it('should format the specified message', function () { - throwsWithMessage(function () { + it('should format the specified message', () => { + throwsWithMessage(() => { assert(1 === 2 + 1, '%s !== %s', 1, 2); }, '1 !== 2'); }); - it('should handle custom fail behaviour', function () { + it('should handle custom fail behaviour', () => { var fail = t.fail; - t.fail = function (message) { + t.fail = message => { try { throw new Error(message); } catch (e) { eq(e.message, 'report error'); } }; - doesNotThrow(function () { + doesNotThrow(() => { assert(1 === 2 + 1, 'report error'); }); t.fail = fail; @@ -370,48 +370,48 @@ describe('assert', function () { // utils // -describe('format(str, [...])', function () { +describe('format(str, [...])', () => { - it('should format strings', function () { + it('should format strings', () => { eq(format('%s', 'a'), 'a'); eq(format('%s', 2), '2'); eq(format('%s === %s', 1, 1), '1 === 1'); }); - it('should format JSON', function () { + it('should format JSON', () => { eq(format('%j', {a: 1}), '{"a":1}'); }); - it('should handle undefined formatters', function () { + it('should handle undefined formatters', () => { eq(format('%o', 'a'), '%o a'); }); - it('should handle escaping %', function () { + it('should handle escaping %', () => { eq(format('%%s'), '%s'); }); - it('should not consume an argument with a single %', function () { + it('should not consume an argument with a single %', () => { eq(format('%s%', '100'), '100%'); }); - it('should handle less arguments than placeholders', function () { + it('should handle less arguments than placeholders', () => { eq(format('%s %s', 'a'), 'a %s'); }); - it('should handle more arguments than placeholders', function () { + it('should handle more arguments than placeholders', () => { eq(format('%s', 'a', 'b', 'c'), 'a b c'); }); - it('should be extensible', function () { - (format).formatters.l = function (x:any) { return x.length; }; + it('should be extensible', () => { + ( format).formatters.l = (x: any) => x.length; eq(format('%l', ['a', 'b', 'c']), '3'); }); }); -describe('mixin(x, y, [overwrite])', function () { +describe('mixin(x, y, [overwrite])', () => { - it('should mix two objects', function () { + it('should mix two objects', () => { var o1 = {a: 1}; var o2 = {b: 2}; var o3 = mixin(o1, o2); @@ -420,15 +420,15 @@ describe('mixin(x, y, [overwrite])', function () { eq(o3.b, 2); }); - it('should throw if a property already exists', function () { - throwsWithMessage(function () { + it('should throw if a property already exists', () => { + throwsWithMessage(() => { var o1 = {a: 1}; var o2 = {a: 2, b: 2}; mixin(o1, o2); }, 'Cannot overwrite property a'); }); - it('should not throw if a property already exists but overwrite = true', function () { + it('should not throw if a property already exists but overwrite = true', () => { var o1 = {a: 1}; var o2 = {a: 2, b: 2}; var o3 = mixin(o1, o2, true); @@ -436,38 +436,38 @@ describe('mixin(x, y, [overwrite])', function () { eq(o3.b, 2); }); - it('should not mix prototype properties', function () { + it('should not mix prototype properties', () => { function F() {} F.prototype.method = noop; - var source = new (F)(); + var source = new ( F)(); var target = {}; mixin(target, source); - eq((target).method, undefined); + eq(( target).method, undefined); }); }); -describe('getFunctionName(f, [defaultName])', function () { +describe('getFunctionName(f, [defaultName])', () => { var getFunctionName = t.getFunctionName; - it('should return the name of a named function', function () { + it('should return the name of a named function', () => { eq(getFunctionName(function myfunc(){}), 'myfunc'); }); - it('should return the value of `displayName` if specified', function () { + it('should return the value of `displayName` if specified', () => { var f = function myfunc(){}; - (f).displayName = 'mydisplayname'; + ( f).displayName = 'mydisplayname'; eq(getFunctionName(f), 'mydisplayname'); }); - it('should fallback on function arity if nothing is specified', function () { - eq(getFunctionName(function (a:any, b:any, c:any) { return a + b + c; }), ''); + it('should fallback on function arity if nothing is specified', () => { + eq(getFunctionName((a: any, b: any, c: any) => a + b + c), ''); }); }); -describe('getTypeName(type)', function () { +describe('getTypeName(type)', () => { var UnnamedStruct = struct({}); var NamedStruct = struct({}, 'NamedStruct'); @@ -480,7 +480,7 @@ describe('getTypeName(type)', function () { var UnnamedTuple = tuple([Str, Num]); var NamedTuple = tuple([Str, Num], 'NamedTuple'); var UnnamedSubtype = subtype(Str, function notEmpty(x) { return x !== ''; }); - var NamedSubtype = subtype(Str, function (x) { return x !== ''; }, 'NamedSubtype'); + var NamedSubtype = subtype(Str, x => x !== '', 'NamedSubtype'); var UnnamedList = list(Str); var NamedList = list(Str, 'NamedList'); var UnnamedDict = dict(Str, Str); @@ -488,7 +488,7 @@ describe('getTypeName(type)', function () { var UnnamedFunc = func(Str, Str); var NamedFunc = func(Str, Str, 'NamedFunc'); - it('should return the name of a named type', function () { + it('should return the name of a named type', () => { eq(getTypeName(NamedStruct), 'NamedStruct'); eq(getTypeName(NamedUnion), 'NamedUnion'); eq(getTypeName(NamedMaybe), 'NamedMaybe'); @@ -500,7 +500,7 @@ describe('getTypeName(type)', function () { eq(getTypeName(NamedFunc), 'NamedFunc'); }); - it('should return a meaningful name of a unnamed type', function () { + it('should return a meaningful name of a unnamed type', () => { eq(getTypeName(UnnamedStruct), '{}'); eq(getTypeName(UnnamedUnion), 'Str | Num'); eq(getTypeName(UnnamedMaybe), '?Str'); @@ -518,29 +518,27 @@ describe('getTypeName(type)', function () { // Any // -describe('Any', function () { +describe('Any', () => { var T = Any; - describe('constructor', function () { + describe('constructor', () => { - it('should behave like identity', function () { + it('should behave like identity', () => { eq(Any('a'), 'a'); }); - it('should throw if used with new', function () { - throwsWithMessage(function () { - /* jshint ignore:start */ - var x = new (T)(); - /* jshint ignore:end */ + it('should throw if used with new', () => { + throwsWithMessage(() => { + var x = new ( T)(); }, 'Operator `new` is forbidden for type `Any`'); }); }); - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should always return true', function () { + it('should always return true', () => { ok(T.is(null)); ok(T.is(undefined)); ok(T.is(0)); @@ -562,7 +560,7 @@ describe('Any', function () { // irreducible types // -describe('irreducible types constructors', function () { +describe('irreducible types constructors', () => { [ {T: Nil, x: null}, @@ -575,19 +573,17 @@ describe('irreducible types constructors', function () { {T: Err, x: new Error()}, {T: Re, x: /a/}, {T: Dat, x: new Date()} - ].forEach(function (o) { + ].forEach(o => { var { T, x } = o; - it('should accept only valid values', function () { - eq((T)(x), x); + it('should accept only valid values', () => { + eq(( T)(x), x); }); - it('should throw if used with new', function () { - throwsWithMessage(function () { - /* jshint ignore:start */ - var x = new (T) (); - /* jshint ignore:end */ + it('should throw if used with new', () => { + throwsWithMessage(() => { + var x = new ( T) (); }, 'Operator `new` is forbidden for type `' + getTypeName(T) + '`'); }); @@ -595,16 +591,16 @@ describe('irreducible types constructors', function () { }); -describe('Nil', function () { +describe('Nil', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is null or undefined', function () { + it('should return true when x is null or undefined', () => { ok(Nil.is(null)); ok(Nil.is(undefined)); }); - it('should return false when x is neither null nor undefined', function () { + it('should return false when x is neither null nor undefined', () => { ko(Nil.is(0)); ko(Nil.is(true)); ko(Nil.is('')); @@ -621,16 +617,16 @@ describe('Nil', function () { }); -describe('Bool', function () { +describe('Bool', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is true or false', function () { + it('should return true when x is true or false', () => { ok(Bool.is(true)); ok(Bool.is(false)); }); - it('should return false when x is neither true nor false', function () { + it('should return false when x is neither true nor false', () => { ko(Bool.is(null)); ko(Bool.is(undefined)); ko(Bool.is(0)); @@ -648,19 +644,17 @@ describe('Bool', function () { }); -describe('Num', function () { +describe('Num', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is a number', function () { + it('should return true when x is a number', () => { ok(Num.is(0)); ok(Num.is(1)); - /* jshint ignore:start */ ko(Num.is(new Number(1))); - /* jshint ignore:end */ }); - it('should return false when x is not a number', function () { + it('should return false when x is not a number', () => { ko(Num.is(NaN)); ko(Num.is(Infinity)); ko(Num.is(-Infinity)); @@ -681,19 +675,17 @@ describe('Num', function () { }); -describe('Str', function () { +describe('Str', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is a string', function () { + it('should return true when x is a string', () => { ok(Str.is('')); ok(Str.is('a')); - /* jshint ignore:start */ ko(Str.is(new String('a'))); - /* jshint ignore:end */ }); - it('should return false when x is not a string', function () { + it('should return false when x is not a string', () => { ko(Str.is(NaN)); ko(Str.is(Infinity)); ko(Str.is(-Infinity)); @@ -714,15 +706,15 @@ describe('Str', function () { }); -describe('Arr', function () { +describe('Arr', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is an array', function () { + it('should return true when x is an array', () => { ok(Arr.is([])); }); - it('should return false when x is not an array', function () { + it('should return false when x is not an array', () => { ko(Arr.is(NaN)); ko(Arr.is(Infinity)); ko(Arr.is(-Infinity)); @@ -743,17 +735,17 @@ describe('Arr', function () { }); -describe('Obj', function () { +describe('Obj', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is an object', function () { + it('should return true when x is an object', () => { function A() {} ok(Obj.is({})); - ok(Obj.is(new (A)())); + ok(Obj.is(new ( A)())); }); - it('should return false when x is not an object', function () { + it('should return false when x is not an object', () => { ko(Obj.is(null)); ko(Obj.is(undefined)); ko(Obj.is(0)); @@ -766,28 +758,24 @@ describe('Obj', function () { }); -describe('Func', function () { +describe('Func', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is a function', function () { + it('should return true when x is a function', () => { ok(Func.is(noop)); - /* jshint ignore:start */ ok(Func.is(new Function())); - /* jshint ignore:end */ }); - it('should return false when x is not a function', function () { + it('should return false when x is not a function', () => { ko(Func.is(null)); ko(Func.is(undefined)); ko(Func.is(0)); ko(Func.is('')); ko(Func.is([])); - /* jshint ignore:start */ ko(Func.is(new String('1'))); ko(Func.is(new Number(1))); ko(Func.is(new Boolean())); - /* jshint ignore:end */ ko(Func.is(/a/)); ko(Func.is(new RegExp('a'))); ko(Func.is(new Error())); @@ -798,25 +786,23 @@ describe('Func', function () { }); -describe('Err', function () { +describe('Err', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is an error', function () { + it('should return true when x is an error', () => { ok(Err.is(new Error())); }); - it('should return false when x is not an error', function () { + it('should return false when x is not an error', () => { ko(Err.is(null)); ko(Err.is(undefined)); ko(Err.is(0)); ko(Err.is('')); ko(Err.is([])); - /* jshint ignore:start */ ko(Err.is(new String('1'))); ko(Err.is(new Number(1))); ko(Err.is(new Boolean())); - /* jshint ignore:end */ ko(Err.is(/a/)); ko(Err.is(new RegExp('a'))); ko(Err.is(new Date())); @@ -826,26 +812,24 @@ describe('Err', function () { }); -describe('Re', function () { +describe('Re', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is a regexp', function () { + it('should return true when x is a regexp', () => { ok(Re.is(/a/)); ok(Re.is(new RegExp('a'))); }); - it('should return false when x is not a regexp', function () { + it('should return false when x is not a regexp', () => { ko(Re.is(null)); ko(Re.is(undefined)); ko(Re.is(0)); ko(Re.is('')); ko(Re.is([])); - /* jshint ignore:start */ ko(Re.is(new String('1'))); ko(Re.is(new Number(1))); ko(Re.is(new Boolean())); - /* jshint ignore:end */ ko(Re.is(new Error())); ko(Re.is(new Date())); }); @@ -854,25 +838,23 @@ describe('Re', function () { }); -describe('Dat', function () { +describe('Dat', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is a Dat', function () { + it('should return true when x is a Dat', () => { ok(Dat.is(new Date())); }); - it('should return false when x is not a Dat', function () { + it('should return false when x is not a Dat', () => { ko(Dat.is(null)); ko(Dat.is(undefined)); ko(Dat.is(0)); ko(Dat.is('')); ko(Dat.is([])); - /* jshint ignore:start */ ko(Dat.is(new String('1'))); ko(Dat.is(new Number(1))); ko(Dat.is(new Boolean())); - /* jshint ignore:end */ ko(Dat.is(new Error())); ko(Dat.is(/a/)); ko(Dat.is(new RegExp('a'))); @@ -886,30 +868,30 @@ describe('Dat', function () { // struct // -describe('struct', function () { +describe('struct', () => { - describe('combinator', function () { + describe('combinator', () => { - it('should throw if used with wrong arguments', function () { + it('should throw if used with wrong arguments', () => { - throwsWithMessage(function () { - (struct)(); + throwsWithMessage(() => { + ( struct)(); }, 'Invalid argument `props` = `undefined` supplied to `struct` combinator'); - throwsWithMessage(function () { + throwsWithMessage(() => { struct({a: null}); }, 'Invalid argument `props` = `[object Object]` supplied to `struct` combinator'); - throwsWithMessage(function () { - (struct)({}, 1); + throwsWithMessage(() => { + ( struct)({}, 1); }, 'Invalid argument `name` = `1` supplied to `struct` combinator'); }); }); - describe('constructor', function () { + describe('constructor', () => { - it('should be idempotent', function () { + it('should be idempotent', () => { var T = Point; var p1 = T({x: 0, y: 0}); var p2 = T(p1); @@ -918,29 +900,29 @@ describe('struct', function () { eq(p2 === p1, true); }); - it('should accept only valid values', function () { - throwsWithMessage(function () { + it('should accept only valid values', () => { + throwsWithMessage(() => { Point(1); }, 'Invalid argument `value` = `1` supplied to struct type `{x: Num, y: Num}`'); }); }); - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is an instance of the struct', function () { + it('should return true when x is an instance of the struct', () => { var p = new Point({ x: 1, y: 2 }); ok(Point.is(p)); }); }); - describe('#update()', function () { + describe('#update()', () => { var Type = struct({name: Str}); var instance = new Type({name: 'Giulio'}); - it('should return a new instance', function () { + it('should return a new instance', () => { var newInstance = Type.update(instance, {name: {$set: 'Canti'}}); ok(Type.is(newInstance)); eq( ( instance).name, 'Giulio'); @@ -949,31 +931,31 @@ describe('struct', function () { }); - describe('#extend(props, [name])', function () { + describe('#extend(props, [name])', () => { - it('should extend an existing struct', function () { + it('should extend an existing struct', () => { var Point = struct({ x: Num, y: Num }, 'Point'); var Point3D = Point.extend({z: Num}, 'Point3D'); eq(getTypeName(Point3D), 'Point3D'); - eq((Point3D).meta.props.x, Num); - eq((Point3D).meta.props.y, Num); - eq((Point3D).meta.props.z, Num); + eq(( Point3D).meta.props.x, Num); + eq(( Point3D).meta.props.y, Num); + eq(( Point3D).meta.props.z, Num); }); - it('should handle an array as argument', function () { + it('should handle an array as argument', () => { var Type = struct({a: Str}, 'Type'); var Mixin = [{b: Num, c: Bool}]; var NewType = Type.extend(Mixin, 'NewType'); eq(getTypeName(NewType), 'NewType'); - eq((NewType).meta.props.a, Str); - eq((NewType).meta.props.b, Num); - eq((NewType).meta.props.c, Bool); + eq(( NewType).meta.props.a, Str); + eq(( NewType).meta.props.b, Num); + eq(( NewType).meta.props.c, Bool); }); - it('should handle a struct (or list of structs) as argument', function () { + it('should handle a struct (or list of structs) as argument', () => { var A = struct({a: Str}, 'A'); var B = struct({b: Str}, 'B'); var C = struct({c: Str}, 'C'); @@ -987,18 +969,20 @@ describe('struct', function () { }); }); - it('should support prototypal inheritance', function () { + it('should support prototypal inheritance', () => { + interface Rectangle { w: number; h: number; area(): number; }; var Rectangle = struct({ w: Num, h: Num }, 'Rectangle'); - Rectangle.prototype.area = function () { + Rectangle.prototype.area = function(this: Rectangle) { return this.w * this.h; }; + interface Cube extends Rectangle { l: number; } var Cube = Rectangle.extend({ l: Num }); - Cube.prototype.volume = function () { + Cube.prototype.volume = function(this: Cube) { return this.area() * this.l; }; @@ -1008,8 +992,8 @@ describe('struct', function () { assert('function' === typeof Cube.prototype.volume); assert(Cube.prototype.constructor === Cube); - var c = new Cube({w:2, h:2, l:2}); - eq((c).volume(), 8); + var c = new Cube({w: 2, h: 2, l: 2}); + eq(( c).volume(), 8); }); }); @@ -1020,46 +1004,44 @@ describe('struct', function () { // enums // -describe('enums', function () { +describe('enums', () => { - describe('combinator', function () { + describe('combinator', () => { - it('should throw if used with wrong arguments', function () { + it('should throw if used with wrong arguments', () => { - throwsWithMessage(function () { - (enums)(); + throwsWithMessage(() => { + ( enums)(); }, 'Invalid argument `map` = `undefined` supplied to `enums` combinator'); - throwsWithMessage(function () { - (enums)({}, 1); + throwsWithMessage(() => { + ( enums)({}, 1); }, 'Invalid argument `name` = `1` supplied to `enums` combinator'); }); }); - describe('constructor', function () { + describe('constructor', () => { var T = enums({a: 0}, 'T'); - it('should throw if used with new', function () { - throwsWithMessage(function () { - /* jshint ignore:start */ - var x = new (T)('a'); - /* jshint ignore:end */ + it('should throw if used with new', () => { + throwsWithMessage(() => { + var x = new ( T)('a'); }, 'Operator `new` is forbidden for type `T`'); }); - it('should accept only valid values', function () { - eq((T)('a'), 'a'); - throwsWithMessage(function () { - (T)('b'); + it('should accept only valid values', () => { + eq(( T)('a'), 'a'); + throwsWithMessage(() => { + ( T)('b'); }, 'Invalid argument `value` = `b` supplied to enums type `T`, expected one of ["a"]'); }); }); - describe('#is(x)', function () { + describe('#is(x)', () => { var Direction = enums({ North: 0, @@ -1070,32 +1052,32 @@ describe('enums', function () { 2.5: 'South-East' }); - it('should return true when x is an instance of the enum', function () { + it('should return true when x is an instance of the enum', () => { ok(Direction.is('North')); ok(Direction.is(1)); ok(Direction.is('1')); ok(Direction.is(2.5)); }); - it('should return false when x is not an instance of the enum', function () { + it('should return false when x is not an instance of the enum', () => { ko(Direction.is('North-East')); ko(Direction.is(2)); }); }); - describe('#of(keys)', function () { + describe('#of(keys)', () => { - it('should return an enum', function () { - var Size = (enums).of(['large', 'small', 1, 10.9]); ///!!! + it('should return an enum', () => { + var Size = ( enums).of(['large', 'small', 1, 10.9]); ///!!! ok(Size.meta.map.large === 'large'); ok(Size.meta.map.small === 'small'); ok(Size.meta.map['1'] === 1); ok(Size.meta.map[10.9] === 10.9); }); - it('should handle a string', function () { - var Size = (enums).of('large small 10'); + it('should handle a string', () => { + var Size = ( enums).of('large small 10'); ok(Size.meta.map.large === 'large'); ok(Size.meta.map.small === 'small'); ok(Size.meta.map['10'] === '10'); @@ -1110,7 +1092,7 @@ describe('enums', function () { // union // -describe('union', function () { +describe('union', () => { var Circle = struct({ center: Point, @@ -1124,81 +1106,79 @@ describe('union', function () { var Shape = union([Circle, Rectangle], 'Shape'); - Shape.dispatch = function (values) { + Shape.dispatch = values => { assert(Obj.is(values)); return values.hasOwnProperty('center') ? Circle : Rectangle; }; - describe('combinator', function () { + describe('combinator', () => { - it('should throw if used with wrong arguments', function () { + it('should throw if used with wrong arguments', () => { - throwsWithMessage(function () { - (union)(); + throwsWithMessage(() => { + ( union)(); }, 'Invalid argument `types` = `undefined` supplied to `union` combinator'); - throwsWithMessage(function () { + throwsWithMessage(() => { union([]); }, 'Invalid argument `types` = `` supplied to `union` combinator, provide at least two types'); - throwsWithMessage(function () { + throwsWithMessage(() => { union([Circle]); }, 'Invalid argument `types` = `Circle` supplied to `union` combinator, provide at least two types'); - throwsWithMessage(function () { - (union)([Circle, Point], 1); + throwsWithMessage(() => { + ( union)([Circle, Point], 1); }, 'Invalid argument `name` = `1` supplied to `union` combinator'); }); }); - describe('constructor', function () { + describe('constructor', () => { - it('should throw when dispatch() is not implemented', function () { - throwsWithMessage(function () { + it('should throw when dispatch() is not implemented', () => { + throwsWithMessage(() => { var T = union([Str, Num], 'T'); T.dispatch = null; T(1); }, 'Unimplemented `dispatch()` function for union type `T`'); }); - it('should have a default dispatch() implementation', function () { + it('should have a default dispatch() implementation', () => { var T = union([Str, Num], 'T'); eq(T(1), 1); }); - it('should throw when dispatch() does not return a type', function () { - throwsWithMessage(function () { + it('should throw when dispatch() does not return a type', () => { + throwsWithMessage(() => { var T = union([Str, Num], 'T'); T(true); }, 'The `dispatch()` function of union type `T` returns no type constructor'); }); - it('should build instances when dispatch() is implemented', function () { + it('should build instances when dispatch() is implemented', () => { var circle = Shape({center: {x: 0, y: 0}, radius: 10}); ok(Circle.is(circle)); }); - it('should throw if used with new and union types are not instantiables with new', function () { - throwsWithMessage(function () { + it('should throw if used with new and union types are not instantiables with new', () => { + throwsWithMessage(() => { var T = union([Str, Num], 'T'); - T.dispatch = function () { return Str; }; - /* jshint ignore:start */ + T.dispatch = () => Str; var x = new T('a'); - /* jshint ignore:end */ }, 'Operator `new` is forbidden for type `T`'); }); - it('should not throw if used with new and union types are instantiables with new', function () { - doesNotThrow(function () { + it('should not throw if used with new and union types are instantiables with new', () => { + doesNotThrow(() => { Shape({center: {x: 0, y: 0}, radius: 10}); }); }); - it('should be idempotent', function () { + it('should be idempotent', () => { var p1 = Shape({center: {x: 0, y: 0}, radius: 10}); var p2 = Shape(p1); eq(Object.isFrozen(p1), true); @@ -1208,9 +1188,9 @@ describe('union', function () { }); - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is an instance of the union', function () { + it('should return true when x is an instance of the union', () => { var p = new Circle({center: { x: 0, y: 0 }, radius: 10}); ok(Shape.is(p)); }); @@ -1223,56 +1203,54 @@ describe('union', function () { // maybe // -describe('maybe', function () { +describe('maybe', () => { - describe('combinator', function () { + describe('combinator', () => { - it('should throw if used with wrong arguments', function () { + it('should throw if used with wrong arguments', () => { - throwsWithMessage(function () { - (maybe)(); + throwsWithMessage(() => { + ( maybe)(); }, 'Invalid argument `type` = `undefined` supplied to `maybe` combinator'); - throwsWithMessage(function () { - (maybe)(Point, 1); + throwsWithMessage(() => { + ( maybe)(Point, 1); }, 'Invalid argument `name` = `1` supplied to `maybe` combinator'); }); - it('should be idempotent', function () { + it('should be idempotent', () => { var MaybeStr = maybe(Str); ok(maybe(MaybeStr) === MaybeStr); }); - it('should be noop with Any', function () { + it('should be noop with Any', () => { ok(maybe(Any) === Any); }); - it('should be noop with Nil', function () { - ok((maybe)(Nil) === Nil); + it('should be noop with Nil', () => { + ok(( maybe)(Nil) === Nil); }); }); - describe('constructor', function () { + describe('constructor', () => { - it('should throw if used with new', function () { - throwsWithMessage(function () { - /* jshint ignore:start */ + it('should throw if used with new', () => { + throwsWithMessage(() => { var T = maybe(Str, 'T'); - var x = new (T)(); - /* jshint ignore:end */ + var x = new ( T)(); }, 'Operator `new` is forbidden for type `T`'); }); - it('should coerce values', function () { + it('should coerce values', () => { var T = maybe(Point); eq(T(null), null); eq(T(undefined), null); ok(Point.is(T({x: 0, y: 0}))); }); - it('should be idempotent', function () { + it('should be idempotent', () => { var T = maybe(Point); var p1 = T({x: 0, y: 0}); var p2 = T(p1); @@ -1283,9 +1261,9 @@ describe('maybe', function () { }); - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is an instance of the maybe', function () { + it('should return true when x is an instance of the maybe', () => { var Radio = maybe(Str); ok(Radio.is('a')); ok(Radio.is(null)); @@ -1300,50 +1278,50 @@ describe('maybe', function () { // tuple // -describe('tuple', function () { +describe('tuple', () => { var Area = tuple([Num, Num], 'Area'); - describe('combinator', function () { + describe('combinator', () => { - it('should throw if used with wrong arguments', function () { + it('should throw if used with wrong arguments', () => { - throwsWithMessage(function () { - (tuple)(); + throwsWithMessage(() => { + ( tuple)(); }, 'Invalid argument `types` = `undefined` supplied to `tuple` combinator'); - throwsWithMessage(function () { - (tuple)([Point, Point], 1); + throwsWithMessage(() => { + ( tuple)([Point, Point], 1); }, 'Invalid argument `name` = `1` supplied to `tuple` combinator'); }); }); - describe('constructor', function () { + describe('constructor', () => { var S = struct({}, 'S'); var T = tuple([S, S], 'T'); - it('should coerce values', function () { + it('should coerce values', () => { var t = T([{}, {}]); ok(S.is(( t)[0])); ok(S.is(( t)[1])); }); - it('should accept only valid values', function () { + it('should accept only valid values', () => { - throwsWithMessage(function () { + throwsWithMessage(() => { T(1); }, 'Invalid argument `value` = `1` supplied to tuple type `T`, expected an `Arr` of length `2`'); - throwsWithMessage(function () { + throwsWithMessage(() => { T([1, 1]); }, 'Invalid argument `value` = `1` supplied to struct type `S`'); }); - it('should be idempotent', function () { + it('should be idempotent', () => { var T = tuple([Str, Num]); var p1 = T(['a', 1]); var p2 = T(p1); @@ -1354,30 +1332,30 @@ describe('tuple', function () { }); - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is an instance of the tuple', function () { + it('should return true when x is an instance of the tuple', () => { ok(Area.is([1, 2])); }); - it('should return false when x is not an instance of the tuple', function () { + it('should return false when x is not an instance of the tuple', () => { ko(Area.is([1])); ko(Area.is([1, 2, 3])); ko(Area.is([1, 'a'])); }); - it('should not depend on `this`', function () { + it('should not depend on `this`', () => { ok([[1, 2]].every(Area.is)); }); }); - describe('#update()', function () { + describe('#update()', () => { var Type = tuple([Str, Num]); var instance = Type(['a', 1]); - it('should return a new instance', function () { + it('should return a new instance', () => { var newInstance = Type.update(instance, {0: {$set: 'b'}}); assert(Type.is(newInstance)); assert(( instance)[0] === 'a'); @@ -1392,47 +1370,47 @@ describe('tuple', function () { // list // -describe('list', function () { +describe('list', () => { - describe('combinator', function () { + describe('combinator', () => { - it('should throw if used with wrong arguments', function () { + it('should throw if used with wrong arguments', () => { - throwsWithMessage(function () { - (list)(); + throwsWithMessage(() => { + ( list)(); }, 'Invalid argument `type` = `undefined` supplied to `list` combinator'); - throwsWithMessage(function () { - (list)(Point, 1); + throwsWithMessage(() => { + ( list)(Point, 1); }, 'Invalid argument `name` = `1` supplied to `list` combinator'); }); }); - describe('constructor', function () { + describe('constructor', () => { var S = struct({}, 'S'); var T = list(S, 'T'); - it('should coerce values', function () { + it('should coerce values', () => { var t = T([{}]); ok(S.is(( t)[0])); }); - it('should accept only valid values', function () { + it('should accept only valid values', () => { - throwsWithMessage(function () { + throwsWithMessage(() => { T(1); }, 'Invalid argument `value` = `1` supplied to list type `T`'); - throwsWithMessage(function () { + throwsWithMessage(() => { T([1]); }, 'Invalid argument `value` = `1` supplied to struct type `S`'); }); - it('should be idempotent', function () { + it('should be idempotent', () => { var T = list(Num); var p1 = T([1, 2]); var p2 = T(p1); @@ -1443,32 +1421,32 @@ describe('list', function () { }); - describe('#is(x)', function () { + describe('#is(x)', () => { var Path = list(Point); var p1 = new Point({x: 0, y: 0}); var p2 = new Point({x: 1, y: 1}); - it('should return true when x is a list', function () { + it('should return true when x is a list', () => { ok(Path.is([p1, p2])); }); - it('should not depend on `this`', function () { + it('should not depend on `this`', () => { ok([[p1, p2]].every(Path.is)); }); }); - describe('#update()', function () { + describe('#update()', () => { var Type = list(Str); var instance = Type(['a', 'b']); - it('should return a new instance', function () { - var newInstance = Type.update(instance, {'$push': ['c']}); + it('should return a new instance', () => { + var newInstance = Type.update(instance, {$push: ['c']}); assert(Type.is(newInstance)); - assert((instance).length === 2); - assert((newInstance).length === 3); + assert(( instance).length === 2); + assert(( newInstance).length === 3); }); }); @@ -1479,80 +1457,76 @@ describe('list', function () { // subtype // -describe('subtype', function () { +describe('subtype', () => { - var True = function () { return true; }; + var True = () => true; - describe('combinator', function () { + describe('combinator', () => { - it('should throw if used with wrong arguments', function () { + it('should throw if used with wrong arguments', () => { - throwsWithMessage(function () { - (subtype)(); + throwsWithMessage(() => { + ( subtype)(); }, 'Invalid argument `type` = `undefined` supplied to `subtype` combinator'); - throwsWithMessage(function () { + throwsWithMessage(() => { subtype(Point, null); }, 'Invalid argument `predicate` = `null` supplied to `subtype` combinator'); - throwsWithMessage(function () { - (subtype)(Point, True, 1); + throwsWithMessage(() => { + ( subtype)(Point, True, 1); }, 'Invalid argument `name` = `1` supplied to `subtype` combinator'); }); }); - describe('constructor', function () { + describe('constructor', () => { - it('should throw if used with new and a type that is not instantiable with new', function () { - throwsWithMessage(function () { - /* jshint ignore:start */ - var T = subtype(Str, function () { return true; }, 'T'); + it('should throw if used with new and a type that is not instantiable with new', () => { + throwsWithMessage(() => { + var T = subtype(Str, () => true, 'T'); var x = new( T)(); - /* jshint ignore:end */ }, 'Operator `new` is forbidden for type `T`'); }); - it('should coerce values', function () { - var T = subtype(Point, function () { return true; }); + it('should coerce values', () => { + var T = subtype(Point, () => true); var p = T({x: 0, y: 0}); ok(Point.is(p)); }); - it('should accept only valid values', function () { - var predicate = function (p:any) { return p.x > 0; }; + it('should accept only valid values', () => { + var predicate = (p: any) => p.x > 0; var T = subtype(Point, predicate, 'T'); - throwsWithMessage(function () { + throwsWithMessage(() => { T({x: 0, y: 0}); }, 'Invalid argument `value` = `[object Object]` supplied to subtype type `T`'); }); }); - describe('#is(x)', function () { + describe('#is(x)', () => { - var Positive = subtype(Num, function (n) { - return n >= 0; - }); + var Positive = subtype(Num, n => n >= 0); - it('should return true when x is a subtype', function () { + it('should return true when x is a subtype', () => { ok(Positive.is(1)); }); - it('should return false when x is not a subtype', function () { + it('should return false when x is not a subtype', () => { ko(Positive.is(-1)); }); }); - describe('#update()', function () { + describe('#update()', () => { - var Type = subtype(Str, function (s) { return s.length > 2; }); + var Type = subtype(Str, s => s.length > 2); var instance = Type('abc'); - it('should return a new instance', function () { - var newInstance = Type.update(instance, {'$set': 'bca'}); + it('should return a new instance', () => { + var newInstance = Type.update(instance, {$set: 'bca'}); assert(Type.is(newInstance)); eq(newInstance, 'bca'); }); @@ -1565,58 +1539,56 @@ describe('subtype', function () { // dict // -describe('dict', function () { +describe('dict', () => { - describe('combinator', function () { + describe('combinator', () => { - it('should throw if used with wrong arguments', function () { + it('should throw if used with wrong arguments', () => { - throwsWithMessage(function () { - (dict)(); + throwsWithMessage(() => { + ( dict)(); }, 'Invalid argument `domain` = `undefined` supplied to `dict` combinator'); - throwsWithMessage(function () { - (dict)(Str); + throwsWithMessage(() => { + ( dict)(Str); }, 'Invalid argument `codomain` = `undefined` supplied to `dict` combinator'); - throwsWithMessage(function () { - (dict)(Str, Point, 1); + throwsWithMessage(() => { + ( dict)(Str, Point, 1); }, 'Invalid argument `name` = `1` supplied to `dict` combinator'); }); }); - describe('constructor', function () { + describe('constructor', () => { var S = struct({}, 'S'); - var Domain = subtype(Str, function (x) { - return x !== 'forbidden'; - }, 'Domain'); + var Domain = subtype(Str, x => x !== 'forbidden', 'Domain'); var T = dict(Domain, S, 'T'); - it('should coerce values', function () { + it('should coerce values', () => { var t = T({a: {}}); - ok(S.is((t).a)); + ok(S.is(( t).a)); }); - it('should accept only valid values', function () { + it('should accept only valid values', () => { - throwsWithMessage(function () { + throwsWithMessage(() => { T(1); }, 'Invalid argument `value` = `1` supplied to dict type `T`'); - throwsWithMessage(function () { + throwsWithMessage(() => { T({a: 1}); }, 'Invalid argument `value` = `1` supplied to struct type `S`'); - throwsWithMessage(function () { + throwsWithMessage(() => { T({forbidden: {}}); }, 'Invalid argument `value` = `forbidden` supplied to subtype type `Domain`'); }); - it('should be idempotent', function () { + it('should be idempotent', () => { var T = dict(Str, Str); var p1 = T({a: 'a', b: 'b'}); var p2 = T(p1); @@ -1627,32 +1599,32 @@ describe('dict', function () { }); - describe('#is(x)', function () { + describe('#is(x)', () => { var T = dict(Str, Point); var p1 = new Point({x: 0, y: 0}); var p2 = new Point({x: 1, y: 1}); - it('should return true when x is a list', function () { + it('should return true when x is a list', () => { ok(T.is({a: p1, b: p2})); }); - it('should not depend on `this`', function () { + it('should not depend on `this`', () => { ok([{a: p1, b: p2}].every(T.is)); }); }); - describe('#update()', function () { + describe('#update()', () => { var Type = dict(Str, Str); var instance = Type({p1: 'a', p2: 'b'}); - it('should return a new instance', function () { + it('should return a new instance', () => { var newInstance = Type.update(instance, {p2: {$set: 'c'}}); ok(Type.is(newInstance)); - eq((instance).p2, 'b'); - eq((newInstance).p2, 'c'); + eq(( instance).p2, 'b'); + eq(( newInstance).p2, 'c'); }); }); @@ -1663,84 +1635,78 @@ describe('dict', function () { // func // -describe('func', function () { +describe('func', () => { - it('should handle a no types', function () { + it('should handle a no types', () => { var T = func([], Str); eq(T.meta.domain.length, 0); - var getGreeting = T.of(function () { return 'Hi'; }); + var getGreeting = T.of(() => 'Hi'); eq(getGreeting(), 'Hi'); }); - it('should handle a single type', function () { + it('should handle a single type', () => { var T = func(Num, Num); eq(T.meta.domain.length, 1); ok(T.meta.domain[0] === Num); }); - it('should automatically instrument a function', function () { + it('should automatically instrument a function', () => { var T = func(Num, Num); - var f = function () { return 'hi'; }; + var f = () => 'hi'; ok(T.is(T(f))); }); - describe('of', function () { + describe('of', () => { - it('should check the arguments', function () { + it('should check the arguments', () => { var T = func([Num, Num], Num); - var sum = T.of(function (a:any, b:any) { - return a + b; - }); + var sum = T.of((a: any, b: any) => a + b); eq(sum(1, 2), 3); - throwsWithMessage(function () { + throwsWithMessage(() => { sum(1, 2, 3); }, 'Invalid argument `value` = `1,2,3` supplied to tuple type `[Num, Num]`, expected an `Arr` of length `2`'); - throwsWithMessage(function () { + throwsWithMessage(() => { sum('a', 2); }, 'Invalid argument `value` = `a` supplied to irreducible type `Num`'); }); - it('should check the return value', function () { + it('should check the return value', () => { var T = func([Num, Num], Num); - var sum = T.of(function () { + var sum = T.of(() => { return 'a'; }); - throwsWithMessage(function () { + throwsWithMessage(() => { sum(1, 2); }, 'Invalid argument `value` = `a` supplied to irreducible type `Num`'); }); - it('should preserve `this`', function () { + it('should preserve `this`', () => { var o = {name: 'giulio'}; - (o).getTypeName = func([], Str).of(function () { + ( o).getTypeName = func([], Str).of(function(this: any) { return this.name; }); - eq((o).getTypeName(), 'giulio'); + eq(( o).getTypeName(), 'giulio'); }); - it('should handle function types', function () { + it('should handle function types', () => { var A = func([Str], Str); var B = func([Str, A], Str); - var f = A.of(function (s:any) { - return s + '!'; - }); - var g = B.of(function (str:any, strAction:any) { - return strAction(str); - }); + var f = A.of((s: any) => s + '!'); + var g = B.of((str: any, strAction: any) => strAction(str)); eq(g('hello', f), 'hello!'); }); - it('should be idempotent', function () { - var f = function (s:any) { return s; }; + it('should be idempotent', () => { + var f = (s: any) => s; var g = func([Str], Str).of(f); var h = func([Str], Str).of(g); ok(h === g); @@ -1748,13 +1714,11 @@ describe('func', function () { }); - describe('currying', function () { + describe('currying', () => { - it('should curry functions', function () { + it('should curry functions', () => { var Type = func([Num, Num, Num], Num); - var sum = Type.of(function (a:any, b:any, c:any) { - return a + b + c; - }); + var sum = Type.of((a: any, b: any, c: any) => a + b + c); eq(sum(1, 2, 3), 6); eq(sum(1, 2)(3), 6); eq(sum(1)(2, 3), 6); @@ -1768,18 +1732,16 @@ describe('func', function () { ok(CurriedType.is(sum1)); }); - it('should throw if partial arguments are wrong', function () { + it('should throw if partial arguments are wrong', () => { var T = func([Num, Num], Num); - var sum = T.of(function (a:any, b:any) { - return a + b; - }); + var sum = T.of((a: any, b: any) => a + b); - throwsWithMessage(function () { + throwsWithMessage(() => { sum('a'); }, 'Invalid argument `value` = `a` supplied to irreducible type `Num`'); - throwsWithMessage(function () { + throwsWithMessage(() => { var sum1 = sum(1); sum1('a'); }, 'Invalid argument `value` = `a` supplied to irreducible type `Num`'); diff --git a/tcomb/tsconfig.json b/tcomb/tsconfig.json index 214f9a631b..91290a69e2 100644 --- a/tcomb/tsconfig.json +++ b/tcomb/tsconfig.json @@ -5,7 +5,7 @@ "es6" ], "noImplicitAny": true, - "noImplicitThis": false, + "noImplicitThis": true, "strictNullChecks": false, "baseUrl": "../", "typeRoots": [ diff --git a/tcomb/tslint.json b/tcomb/tslint.json new file mode 100644 index 0000000000..c3d18eb9dd --- /dev/null +++ b/tcomb/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "../tslint.json", + "rules": { + "callable-types": false, + "forbidden-types": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "unified-signatures": false + } +} diff --git a/tedious-connection-pool/index.d.ts b/tedious-connection-pool/index.d.ts index d9334f74cd..7d144bfc22 100644 --- a/tedious-connection-pool/index.d.ts +++ b/tedious-connection-pool/index.d.ts @@ -1,14 +1,14 @@ -// Type definitions for tedious-connection-pool +// Type definitions for tedious-connection-pool 1.0 // Project: https://github.com/pekim/tedious-connection-pool // Definitions by: Cyprien Autexier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// +import events = require('events'); import tedious = require('tedious'); declare namespace tcp { - /** * Extends Tedious Connection with release function */ @@ -20,22 +20,16 @@ declare namespace tcp { } /** - * Acquire function callback signature + * Provides a connection or an error + * @param err error if any + * @param connection issued from the pool */ - export interface ConnectionCallback { - /** - * Provides a connection or an error - * @param err error if any - * @param connection issued from the pool - */ - (err: Error, connection: PooledConnection): void; - } + export type ConnectionCallback = (err: Error, connection: PooledConnection) => void; /** * Pool Configuration interface */ export interface PoolConfig { - /** * Minimum concurrent connections */ @@ -66,15 +60,12 @@ declare namespace tcp { */ acquireTimeout?: number; } - - } /** * Tedious Connection Pool Class */ -declare class tcp { - +declare class tcp extends events.EventEmitter { /** * Connection Pool constructor * @param poolConfig the pool configuration @@ -88,20 +79,10 @@ declare class tcp { */ acquire(callback: tcp.ConnectionCallback): void; - /** - * listens for a specific connection pool event - * @param event the event name - * @param callback invoked when the event is raised - */ - on(event: string, callback: Function): void; - /** * closes opened connections */ drain(): void; } - - - export = tcp; diff --git a/tedious-connection-pool/tedious-connection-pool-tests.ts b/tedious-connection-pool/tedious-connection-pool-tests.ts index 31715e2090..bdf504274a 100644 --- a/tedious-connection-pool/tedious-connection-pool-tests.ts +++ b/tedious-connection-pool/tedious-connection-pool-tests.ts @@ -30,6 +30,12 @@ pool.on('error', (err: Error) => { console.error(err); }); +pool.once('error', (err: Error) => { + console.error(err); +}); + +pool.removeAllListeners(); + pool.acquire((err: Error, connection: ConnectionPool.PooledConnection) =>{ console.log("hurray"); connection.beginTransaction((error: Error): void => {}, "some name"); diff --git a/tedious-connection-pool/tslint.json b/tedious-connection-pool/tslint.json new file mode 100644 index 0000000000..f9e30021f4 --- /dev/null +++ b/tedious-connection-pool/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} diff --git a/three/index.d.ts b/three/index.d.ts index 100e3ecf8c..70ca653745 100644 --- a/three/index.d.ts +++ b/three/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for three.js 0.83 // Project: http://mrdoob.github.com/three.js/ -// Definitions by: Kon , Satoru Kimura , Florent Poujol , SereznoKot , HouChunlei +// Definitions by: Kon , Satoru Kimura , Florent Poujol , SereznoKot , HouChunlei , Ivo // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -22,6 +22,7 @@ /// /// /// +/// declare namespace THREE { export const REVISION: string; @@ -6415,13 +6416,13 @@ declare namespace THREE { } export interface TextGeometryParameters { - font: Font; - size: number; - height: number; - curveSegments: number; - bevelEnabled: boolean; - bevelThickness: number; - bevelSize: number; + font?: Font; + size?: number; + height?: number; + curveSegments?: number; + bevelEnabled?: boolean; + bevelThickness?: number; + bevelSize?: number; } export class TextGeometry extends ExtrudeGeometry { diff --git a/three/three-colladaLoader.d.ts b/three/three-colladaLoader.d.ts new file mode 100644 index 0000000000..6bdec6a9da --- /dev/null +++ b/three/three-colladaLoader.d.ts @@ -0,0 +1,23 @@ +// Type definitions for three.js (ColladaLoader2.js) +// NOTE : These typings are for the loader named ColladaLoader2.js +// supplied by the npm package @types/three 0.81. +// Definitions by: Brandon Roberge + +declare namespace THREE { + export interface ColladaLoaderReturnType { + + } + export class ColladaModel { + animations: any[]; + kinematics: any; + scene: THREE.Scene; + library: any; + } + export class ColladaLoader { + constructor(); + + load(url: string, onLoad: (model: ColladaModel) => void, onProgress?: (request: ProgressEvent) => void, onError?:(event: ErrorEvent) => void): void; + setCrossOrigin(value: any): void; + parse(text: string): ColladaModel; + } +} \ No newline at end of file diff --git a/tinymce/tslint.json b/tinymce/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/tinymce/tslint.json +++ b/tinymce/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/transducers-js/index.d.ts b/transducers-js/index.d.ts index 0c63bd11c9..0ac1d18235 100644 --- a/transducers-js/index.d.ts +++ b/transducers-js/index.d.ts @@ -1,304 +1,297 @@ -// Type definitions for transducers-js +// Type definitions for transducers-js 0.4 // Project: https://github.com/cognitect-labs/transducers-js // Definitions by: Colin Kahn // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'transducers-js' { - export interface IteratorResult { - done: boolean; - value?: T - } - - export interface Iterator { - next (value?: any): IteratorResult; - return? (value?: any): IteratorResult; - throw? (e?: any): IteratorResult; - } - - export interface Reduced { - ['@@transducer/reduced']: boolean; - ['@@transducer/value']: TResult; - } - - export interface Reducer { - (result: TResult, input: TInput): TResult; - } - - export interface Transducer { - (xf: Transformer): Transformer; - } - - export interface CompletingTransformer { - ['@@transducer/init'] (): TResult | void; - ['@@transducer/step'] (result: TResult, input: TInput): TResult | Reduced; - ['@@transducer/result'] (result: TResult): TCompleteResult; - } - - export interface Transformer extends CompletingTransformer { - } - - /** - * Return a reduced value. Reduced values short circuit transduce. - */ - export function reduced (x: TResult): Reduced; - - /** - * Check if a value is reduced. - */ - export function isReduced (x : any) : Boolean; - - /** - * Function composition. Take N function and return their composition. - */ - export function comp (...args: T[]): T; - - /** - * Take a predicate function and return its complement. - */ - export function complement (f: Function): Function; - - /** - * Identity function. - */ - export function identity (arg: T): T; - - export class Map implements Transformer { - constructor (f: (x: TInput) => TOutput, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * Mapping transducer constructor - */ - export function map (f: (x: TInput) => TOutput): Transducer; - - export class Filter implements Transformer { - constructor (pred: (x: TInput) => boolean, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * Filtering transducer constructor - */ - export function filter (pred: (x: TInput) => boolean): Transducer; - - /** - * Similar to filter except the predicate is used to - * eliminate values. - */ - export function remove (pred: (x: TInput) => boolean): Transducer; - - export class Keep implements Transformer { - constructor (f: (x: TInput) => any, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * A keeping transducer. Keep inputs as long as the provided - * function does not return null or undefined. - */ - export function keep (f: (x: TInput) => any): Transducer; - - export class KeepIndexed implements Transformer { - constructor (f: (i: number, x:TInput) => any, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * Like keep but the provided function will be passed the - * index as the fist argument. - */ - export function keepIndexed (f: (i: number, x: TInput) => any): Transducer; - - export class Take implements Transformer { - constructor (n: number, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult | Reduced; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * A take transducer constructor. Will take n values before - * returning a reduced result. - */ - export function take (n: number): Transducer; - - export class TakeWhile implements Transformer { - constructor (pred: (n: TInput) => boolean, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult | Reduced; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * Like the take transducer except takes as long as the pred - * return true for inputs. - */ - export function takeWhile (pred: (n: TInput) => boolean): Transducer; - - export class TakeNth implements Transformer { - constructor (n: number, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * A transducer that takes every Nth input - */ - export function takeNth (n: number): Transducer; - - export class Drop implements Transformer { - constructor (n: number, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * A dropping transducer constructor - */ - export function drop (n: number): Transducer; - - export class DropWhile implements Transformer { - constructor (pred: (input: TInput) => boolean, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * A dropping transducer that drop inputs as long as - * pred is true. - */ - export function dropWhile (pred: (input: TInput) => boolean): Transducer; - - export class PartitionBy implements Transformer { - constructor (f: (input: TInput) => any, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult - ['@@transducer/result'] (result: TResult): TResult - } - - /** - * A partitioning transducer. Collects inputs into - * arrays as long as predicate remains true for contiguous - * inputs. - */ - export function partitionBy (f: (input: TInput) => any): Transducer; - - export class PartitionAll implements Transformer { - constructor (n: number, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult - ['@@transducer/result'] (result: TResult): TResult - } - - /** - * A partitioning transducer. Collects inputs into - * arrays of size N. - */ - export function partitionAll (n: number): Transducer; - - export class Completing implements CompletingTransformer { - constructor (cf: (result: TResult) => TCompleteResult, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult - ['@@transducer/result'] (result: TResult): TCompleteResult - } - - /** - * A completing transducer constructor. Useful to provide cleanup - * logic at the end of a reduction/transduction. - */ - export function completing (cf: (result: TResult) => TCompleteResult): CompletingTransformer; - - export class Wrap implements Transformer { - constructor (stepFn: Reducer, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult - ['@@transducer/result'] (result: TResult): TResult - } - - /** - * Take a two-arity reducing function where the first argument is the - * accumluation and the second argument is the next input and convert - * it into a transducer transformer object. - */ - export function wrap (stepFn: Reducer): Transducer; - - /** - * Given a transformer return a concatenating transformer - */ - export function cat (xf: Transformer): Transformer ; - - /** - * A mapping concatenating transformer - */ - export function mapcat (f: (arr: TInput[]) => TOutput[]): Transducer; - - /** - * Given a transducer, a builder function, an initial value - * and a iterable collection - returns the reduction. - */ - export function transduce ( - xf: Transducer, - f: Transformer | Reducer, - init: TResult, - coll: TInput[] | Iterator | string | Object): TResult; - - /** - * Given a transducer, an intial value and a - * collection - returns the reduction. - */ - export function reduce ( - xf: Transducer, - init: TResult, - coll: TInput[] | Iterator | string | Object): TResult - - /** - * Reduce a value into the given empty value using a transducer. - */ - export function into( - empty: TResult, - xf: Transducer, - coll: TInput[] | Iterator | string | Object): TResult; - - /** - * Convert a transducer transformer object into a function so - * that it can be used with existing reduce implementation i.e. native, - * Underscore, lodash - */ - export function toFn ( - xf: Transducer, - builder: Reducer | Transformer - ): Reducer; - - /** - * A transformer which simply returns the first input. - */ - export function first (): Wrap; - - /** - * Ensure that a value is reduced. If already reduced will not re-wrap. - */ - export function ensureReduced (x: TResult | Reduced): Reduced; - - /** - * Ensure a value is not reduced. Unwraps if reduced. - */ - export function unreduced (x: TResult | Reduced): TResult; - - /** - * Returns the value of a reduced result. - */ - export function deref (x: Reduced): TResult; +export interface IteratorResult { + done: boolean; + value?: T; } + +export interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +export interface Reduced { + ['@@transducer/reduced']: boolean; + ['@@transducer/value']: TResult; +} + +export type Reducer = (result: TResult, input: TInput) => TResult; + +export type Transducer = (xf: Transformer) => Transformer; + +export interface CompletingTransformer { + ['@@transducer/init'](): TResult | void; + ['@@transducer/step'](result: TResult, input: TInput): TResult | Reduced; + ['@@transducer/result'](result: TResult): TCompleteResult; +} + +export type Transformer = CompletingTransformer; + +/** + * Return a reduced value. Reduced values short circuit transduce. + */ +export function reduced(x: TResult): Reduced; + +/** + * Check if a value is reduced. + */ +export function isReduced(x: any): boolean; + +/** + * Function composition. Take N function and return their composition. + */ +export function comp(...args: T[]): T; + +/** + * Take a predicate function and return its complement. + */ +export function complement(f: Function): Function; + +/** + * Identity function. + */ +export function identity(arg: T): T; + +export class Map implements Transformer { + constructor(f: (x: TInput) => TOutput, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * Mapping transducer constructor + */ +export function map(f: (x: TInput) => TOutput): Transducer; + +export class Filter implements Transformer { + constructor(pred: (x: TInput) => boolean, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * Filtering transducer constructor + */ +export function filter(pred: (x: TInput) => boolean): Transducer; + +/** + * Similar to filter except the predicate is used to + * eliminate values. + */ +export function remove(pred: (x: TInput) => boolean): Transducer; + +export class Keep implements Transformer { + constructor(f: (x: TInput) => any, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * A keeping transducer. Keep inputs as long as the provided + * function does not return null or undefined. + */ +export function keep(f: (x: TInput) => any): Transducer; + +export class KeepIndexed implements Transformer { + constructor(f: (i: number, x: TInput) => any, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * Like keep but the provided function will be passed the + * index as the fist argument. + */ +export function keepIndexed(f: (i: number, x: TInput) => any): Transducer; + +export class Take implements Transformer { + constructor(n: number, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult | Reduced; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * A take transducer constructor. Will take n values before + * returning a reduced result. + */ +export function take(n: number): Transducer; + +export class TakeWhile implements Transformer { + constructor(pred: (n: TInput) => boolean, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult | Reduced; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * Like the take transducer except takes as long as the pred + * return true for inputs. + */ +export function takeWhile(pred: (n: TInput) => boolean): Transducer; + +export class TakeNth implements Transformer { + constructor(n: number, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * A transducer that takes every Nth input + */ +export function takeNth(n: number): Transducer; + +export class Drop implements Transformer { + constructor(n: number, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * A dropping transducer constructor + */ +export function drop(n: number): Transducer; + +export class DropWhile implements Transformer { + constructor(pred: (input: TInput) => boolean, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * A dropping transducer that drop inputs as long as + * pred is true. + */ +export function dropWhile(pred: (input: TInput) => boolean): Transducer; + +export class PartitionBy implements Transformer { + constructor(f: (input: TInput) => any, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult + ['@@transducer/result'](result: TResult): TResult +} + +/** + * A partitioning transducer. Collects inputs into + * arrays as long as predicate remains true for contiguous + * inputs. + */ +export function partitionBy(f: (input: TInput) => any): Transducer; + +export class PartitionAll implements Transformer { + constructor(n: number, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult + ['@@transducer/result'](result: TResult): TResult +} + +/** + * A partitioning transducer. Collects inputs into + * arrays of size N. + */ +export function partitionAll(n: number): Transducer; + +export class Completing implements CompletingTransformer { + constructor(cf: (result: TResult) => TCompleteResult, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult + ['@@transducer/result'](result: TResult): TCompleteResult +} + +/** + * A completing transducer constructor. Useful to provide cleanup + * logic at the end of a reduction/transduction. + */ +export function completing(cf: (result: TResult) => TCompleteResult): CompletingTransformer; + +export class Wrap implements Transformer { + constructor(stepFn: Reducer, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult + ['@@transducer/result'](result: TResult): TResult +} + +/** + * Take a two-arity reducing function where the first argument is the + * accumluation and the second argument is the next input and convert + * it into a transducer transformer object. + */ +export function wrap(stepFn: Reducer): Transducer; + +/** + * Given a transformer return a concatenating transformer + */ +export function cat(xf: Transformer): Transformer ; + +/** + * A mapping concatenating transformer + */ +export function mapcat(f: (arr: TInput[]) => TOutput[]): Transducer; + +/** + * Given a transducer, a builder function, an initial value + * and a iterable collection - returns the reduction. + */ +export function transduce( + xf: Transducer, + f: Transformer | Reducer, + init: TResult, + coll: TInput[] | Iterator | string | Object): TResult; + +/** + * Given a transducer, an intial value and a + * collection - returns the reduction. + */ +export function reduce( + xf: Transducer, + init: TResult, + coll: TInput[] | Iterator | string | Object): TResult; + +/** + * Reduce a value into the given empty value using a transducer. + */ +export function into( + empty: TResult, + xf: Transducer, + coll: TInput[] | Iterator | string | Object): TResult; + +/** + * Convert a transducer transformer object into a function so + * that it can be used with existing reduce implementation i.e. native, + * Underscore, lodash + */ +export function toFn( + xf: Transducer, + builder: Reducer | Transformer +): Reducer; + +/** + * A transformer which simply returns the first input. + */ +export function first(): Wrap; + +/** + * Ensure that a value is reduced. If already reduced will not re-wrap. + */ +export function ensureReduced(x: TResult | Reduced): Reduced; + +/** + * Ensure a value is not reduced. Unwraps if reduced. + */ +export function unreduced(x: TResult | Reduced): TResult; + +/** + * Returns the value of a reduced result. + */ +export function deref(x: Reduced): TResult; diff --git a/transducers-js/transducers-js-tests.ts b/transducers-js/transducers-js-tests.ts index 21c527be41..f40575fe72 100644 --- a/transducers-js/transducers-js-tests.ts +++ b/transducers-js/transducers-js-tests.ts @@ -1,6 +1,3 @@ -/// -/// - // tests taken from https://github.com/cognitect-labs/transducers-js import * as t from 'transducers-js'; @@ -13,16 +10,16 @@ var map = t.map, // basic usage -var inc = function(n: number) { return n + 1; }; -var isEven = function(n: number) { return n % 2 == 0; }; +function inc(n: number) { return n + 1; }; +function isEven(n: number) { return n % 2 === 0; }; var xf = comp(map(inc), filter(isEven)); -console.log(into([], xf, [0,1,2,3,4])); // [2,4] +console.log(into([], xf, [0, 1, 2, 3, 4])); // [2, 4] // integration -var arr = [0,1,2,3,4,5,6,7,8,9,10], - apush = function(arr: number[], x: number) { arr.push(x); return arr; }, +var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + apush = (arr: number[], x: number) => { arr.push(x); return arr; }, xf = comp(map(inc), filter(isEven)), toFn = t.toFn; @@ -33,14 +30,12 @@ _(arr).reduce(toFn(xf, apush), []); // underscore or lodash import * as Immutable from 'immutable'; -var inc = function(n: number): number { return n + 1; }; -var isEven = function(n: number): boolean { return n % 2 == 0; }; -var sum = function(a: number, b: number): number { return a + b; }; +function sum(a: number, b: number): number { return a + b; }; var transduce = t.transduce; var largeVector = Immutable.List(); -for(var i = 0; i < 1000000; i++) { +for (var i = 0; i < 1000000; i++) { largeVector = largeVector.push(i); } @@ -48,121 +43,109 @@ for(var i = 0; i < 1000000; i++) { largeVector.map(inc).filter(isEven).reduce(sum); // faster with transducers -var xf = comp(map(inc),filter(isEven)); +var xf = comp(map(inc), filter(isEven)); transduce(xf, sum, 0, largeVector); // source examples -function mapExample () { - var inc = function(n: number) { return n+1; }; +function mapExample() { var xf = t.map(inc); - t.into([], xf, [1,2,3]); // [2,3,4] + t.into([], xf, [1, 2, 3]); // [2, 3, 4] } -function filterExample () { - var isEven = function(n: number) { return n % 2 == 0; }; +function filterExample() { var xf = t.filter(isEven); - t.into([], xf, [0,1,2,3,4]); // [0,2,4]; + t.into([], xf, [0, 1, 2, 3, 4]); // [0, 2, 4]; } -function removeExample () { - var isEven = function(n: number) { return n % 2 == 0; }; +function removeExample() { var xf = t.remove(isEven); - t.into([], xf, [0,1,2,3,4]); // [1,3]; + t.into([], xf, [0, 1, 2, 3, 4]); // [1, 3]; } -function complementExample () { - var isEven = function(n: number) { return n % 2 == 0; }; +function complementExample() { var isOdd = t.complement(isEven); } -function keepIndexedExample () { - var xf = t.keepIndexed(function(i: number, x: string|number) { if (typeof x == "string") return "cool"; }); - t.into([], xf, [0,1,"foo",3,4,"bar"]); // ["foo","bar"] +function keepIndexedExample() { + var xf = t.keepIndexed((i: number, x: string|number) => { if (typeof x === "string") return "cool"; }); + t.into([], xf, [0, 1, "foo", 3, 4, "bar"]); // ["foo", "bar"] } -function takeExample () { +function takeExample() { var xf = t.take(3); - t.into([], xf, [0,1,2,3,4,5]); // [0,1,2]; + t.into([], xf, [0, 1, 2, 3, 4, 5]); // [0, 1, 2]; } -function takeWhileExample () { - var xf = t.takeWhile(function(n) { return n < 3; }); - t.into([], xf, [0,1,2,3,4,5]); // [0,1,2]; +function takeWhileExample() { + var xf = t.takeWhile(n => n < 3); + t.into([], xf, [0, 1, 2, 3, 4, 5]); // [0, 1, 2]; } -function intoExample () { - var inc = function(n: number) { return n+1; }; - var isEven = function(n: number) { return n % 2 == 0; }; - var apush = function(arr: number[], x: number) { arr.push(x); return arr; }; - var xf = t.comp(t.map(inc),t.filter(isEven)); - t.into([], xf, [1,2,3,4]); // [2,4] +function intoExample() { + var xf = t.comp(t.map(inc), t.filter(isEven)); + t.into([], xf, [1, 2, 3, 4]); // [2, 4] } -function toFnExample () { - var arr = [0,1,2,3,4,5]; - var apush = function(arr: number[], x: number) { arr.push(x); return arr; }; - var xf = t.comp(t.map(inc),t.filter(isEven)); - arr.reduce(t.toFn(xf, apush), []); // [2,4,6] +function toFnExample() { + var arr = [0, 1, 2, 3, 4, 5]; + var xf = t.comp(t.map(inc), t.filter(isEven)); + arr.reduce(t.toFn(xf, apush), []); // [2, 4, 6] } -function takeNthExample () { +function takeNthExample() { var xf = t.takeNth(3); - t.into([], xf, [0,1,2,3,4,5]); // [2,5]; + t.into([], xf, [0, 1, 2, 3, 4, 5]); // [2, 5]; } -function dropExample () { +function dropExample() { var xf = t.drop(3); - t.into([], xf, [0,1,2,3,4,5]); // [3,4,5]; + t.into([], xf, [0, 1, 2, 3, 4, 5]); // [3, 4, 5]; } -function dropWhileExample () { - var xf = t.dropWhile(function(n: number) { return n < 3; }); - t.into([], xf, [0,1,2,3,4,5]); // [3,4,5]; +function dropWhileExample() { + var xf = t.dropWhile(n => n < 3); + t.into([], xf, [0, 1, 2, 3, 4, 5]); // [3, 4, 5]; } -function partitionByExample () { - var xf = t.partitionBy(function(x: string|number) { return typeof x == "string"; }); - t.into([], xf, [0,1,"foo","bar",2,3,"bar","baz"]); // [[0,1],["foo","bar"],[2,3],["bar","baz"]]; +function partitionByExample() { + var xf = t.partitionBy((x: string|number) => typeof x === "string"); + t.into([], xf, [0, 1, "foo", "bar", 2, 3, "bar", "baz"]); // [[0, 1], ["foo", "bar"], [2, 3], ["bar", "baz"]]; } -function partitionAllExample () { +function partitionAllExample() { var xf = t.partitionAll(3); - t.into([], xf, [0,1,2,3,4,5]); // [[0,1,2],[3,4,5]] + t.into([], xf, [0, 1, 2, 3, 4, 5]); // [[0, 1, 2], [3, 4, 5]] } -function wrapExample () { - var arrayPush = t.wrap(function(arr: number[], x: number) { arr.push(x); return arr; }); +function wrapExample() { + var arrayPush = t.wrap((arr: number[], x: number) => { arr.push(x); return arr; }); } -function ensureReducedExample () { +function ensureReducedExample() { var x = t.ensureReduced(1); var y = t.ensureReduced(x); x === y; // true } -function unreducedExample () { +function unreducedExample() { var x = t.reduced(1); t.unreduced(x); // 1 t.unreduced(t.unreduced(x)); // 1 } -function catExample () { - var reverse = function(arr: number[]) { - var arr: number[] = Array.prototype.slice.call(arr, 0); - arr.reverse(); - return arr; - }; - var xf = t.comp(t.map(reverse), t.cat); - t.into([], xf, [[3,2,1],[6,5,4]]); // [1,2,3,4,5,6] +function reverse(arr: number[]) { + var arr: number[] = Array.prototype.slice.call(arr, 0); + arr.reverse(); + return arr; } -function mapcatExample () { - var reverse = function(arr: number[]) { - var arr: number[] = Array.prototype.slice.call(arr, 0); - arr.reverse(); - return arr; - }; +function catExample() { + var xf = t.comp(t.map(reverse), t.cat); + t.into([], xf, [[3, 2, 1], [6, 5, 4]]); // [1, 2, 3, 4, 5, 6] +} + +function mapcatExample() { var xf = t.mapcat(reverse); - t.into([], xf, [[3,2,1],[6,5,4]]); // [1,2,3,4,5,6] + t.into([], xf, [[3, 2, 1], [6, 5, 4]]); // [1, 2, 3, 4, 5, 6] } diff --git a/transducers-js/tslint.json b/transducers-js/tslint.json new file mode 100644 index 0000000000..f05741c59b --- /dev/null +++ b/transducers-js/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/tstl/index.d.ts b/tstl/index.d.ts new file mode 100644 index 0000000000..c1bd7d7aeb --- /dev/null +++ b/tstl/index.d.ts @@ -0,0 +1,11136 @@ +// Type definitions for TSTL v1.3.10 +// Project: https://github.com/samchon/tstl +// Definitions by: Jeongho Nam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "tstl" +{ + export = std; +} + +/** + * # TypeScript-STL + * + * + * + * + * STL (Standard Template Library) Containers and Algorithms for TypeScript. + * + * **T**ypeScript-**STL** is a TypeScript's Standard Template Library who is migrated from C++ STL. Most of classes + * and functions of STL have implemented. Just enjoy it. + * + * @git https://github.com/samchon/tstl + * @author Jeongho Nam + */ +declare namespace std { +} +/** + * Base classes composing STL in background. + * + * @author Jeongho Nam + */ +declare namespace std.base { +} +declare namespace std { + /** + * Apply function to range. + * + * Applies function fn to each of the elements in the range [first, last). + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * @param fn Unary function that accepts an element in the range as argument. This can either be a function p + * ointer or a move constructible function object. Its return value, if any, is ignored. + */ + function for_each, Func extends (val: T) => any>(first: InputIterator, last: InputIterator, fn: Func): Func; + /** + * Apply function to range. + * + * Applies function *fn* to each of the elements in the range [*first*, *first + n*). + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param n the number of elements to apply the function to + * @param fn Unary function that accepts an element in the range as argument. This can either be a function p + * ointer or a move constructible function object. Its return value, if any, is ignored. + * + * @return first + n + */ + function for_each_n>(first: InputIterator, n: number, fn: (val: T) => any): InputIterator; + /** + * Test condition on all elements in range. + * + * Returns true if pred returns true for all the elements in the range + * [first, last) or if the range is {@link Container.empty empty}, and false otherwise. + * + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * @param pred Unary function that accepts an element in the range as argument and returns a value convertible to + * boolean. The value returned indicates whether the element fulfills the condition + * checked by this function. The function shall not modify its argument. + * + * @return true if pred returns true for all the elements in the range or if the range is + * {@link Container.empty empty}, and false otherwise. + */ + function all_of>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): boolean; + /** + * Test if any element in range fulfills condition. + * + * Returns true if pred returns true for any of the elements in the range + * [first, last), and false otherwise. + * + * If [first, last) is an {@link Container.empty empty} range, the function returns + * false. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * @param pred Unary function that accepts an element in the range as argument and returns a value convertible to + * boolean. The value returned indicates whether the element fulfills the condition + * checked by this function. The function shall not modify its argument. + * + * @return true if pred returns true for any of the elements in the range + * [first, last), and false otherwise. If [first, last) is an + * {@link Container.empty empty} range, the function returns false. + */ + function any_of>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): boolean; + /** + * Test if no elements fulfill condition. + * + * Returns true if pred returns false for all the elements in the range + * [first, last) or if the range is {@link Container.empty empty}, and false otherwise. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * @param pred Unary function that accepts an element in the range as argument and returns a value convertible to + * boolean. The value returned indicates whether the element fulfills the condition + * checked by this function. The function shall not modify its argument. + * + * @return true if pred returns false for all the elements in the range + * [first, last) or if the range is {@link Container.empty empty}, and false + * otherwise. + */ + function none_of>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): boolean; + /** + * Test whether the elements in two ranges are equal. + * + * Compares the elements in the range [first1, last1) with those in the range beginning at + * first2, and returns true if all of the elements in both ranges match. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to + * as many elements of this sequence as those in the range [first1, last1). + * + * @return true if all the elements in the range [first1, last1) compare equal to those + * of the range starting at first2, and false otherwise. + */ + function equal>(first1: InputIterator, last1: InputIterator, first2: Iterator): boolean; + /** + * Test whether the elements in two ranges are equal. + * + * Compares the elements in the range [first1, last1) with those in the range beginning at + * first2, and returns true if all of the elements in both ranges match. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to + * as many elements of this sequence as those in the range [first1, last1). + * @param pred Binary function that accepts two elements as argument (one of each of the two sequences, in the same + * order), and returns a value convertible to bool. The value returned indicates whether + * the elements are considered to match in the context of this function. + * + * @return true if all the elements in the range [first1, last1) compare equal to those + * of the range starting at first2, and false otherwise. + */ + function equal>(first1: InputIterator, last1: InputIterator, first2: Iterator, pred: (x: T, y: T) => boolean): boolean; + /** + * Lexicographical less-than comparison. + * + * Returns true if the range [first1, last1) compares lexicographically less + * than the range [first2, last2). + * + * A lexicographical comparison is the kind of comparison generally used to sort words alphabetically in + * dictionaries; It involves comparing sequentially the elements that have the same position in both ranges against + * each other until one element is not equivalent to the other. The result of comparing these first non-matching + * elements is the result of the lexicographical comparison. + * + * If both sequences compare equal until one of them ends, the shorter sequence is lexicographically less + * than the longer one. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the second sequence. + * @param last2 An {@link Iterator} to the final position of the second sequence. The ranged used is + * [first2, last2). + * + * @return true if the first range compares lexicographically less than than the second. + * false otherwise (including when all the elements of both ranges are equivalent). + */ + function lexicographical_compare, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): boolean; + /** + * Lexicographical comparison. + * + * Returns true if the range [first1, last1) compares lexicographically + * relationship than the range [first2, last2). + * + * A lexicographical comparison is the kind of comparison generally used to sort words alphabetically in + * dictionaries; It involves comparing sequentially the elements that have the same position in both ranges against + * each other until one element is not equivalent to the other. The result of comparing these first non-matching + * elements is the result of the lexicographical comparison. + * + * If both sequences compare equal until one of them ends, the shorter sequence is lexicographically + * relationship than the longer one. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the second sequence. + * @param last2 An {@link Iterator} to the final position of the second sequence. The ranged used is + * [first2, last2). + * @param compare Binary function that accepts two arguments of the types pointed by the iterators, and returns a + * value convertible to bool. The value returned indicates whether the first argument is + * considered to go before the second in the specific strict weak ordering it defines. + * + * @return true if the first range compares lexicographically relationship than than the + * second. false otherwise (including when all the elements of both ranges are equivalent). + */ + function lexicographical_compare, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, compare: (x: T, y: T) => boolean): boolean; + /** + * Find value in range. + * + * Returns an iterator to the first element in the range [first, last) that compares equal to + * val. If no such element is found, the function returns last. + * + * The function uses {@link equal_to equal_to} to compare the individual elements to val. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * @param val Value to search for in the range. + * + * @return An {@link Iterator} to the first element in the range that compares equal to val. If no elements + * match, the function returns last. + */ + function find>(first: InputIterator, last: InputIterator, val: T): InputIterator; + /** + * Find element in range. + * + * Returns an iterator to the first element in the range [first, last) for which pred returns + * true. If no such element is found, the function returns last. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * @param pred Unary function that accepts an element in the range as argument and returns a value convertible + * to bool. The value returned indicates whether the element is considered a match in + * the context of this function. The function shall not modify its argument. + * + * @return An {@link Iterator} to the first element in the range for which pred does not return + * false. If pred is false for all elements, the function returns + * last. + */ + function find_if>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): InputIterator; + /** + * Find element in range. + * + * Returns an iterator to the first element in the range [first, last) for which pred returns + * true. If no such element is found, the function returns last. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * @param pred Unary function that accepts an element in the range as argument and returns a value convertible + * to bool. The value returned indicates whether the element is considered a match in + * the context of this function. The function shall not modify its argument. + * + * @return An {@link Iterator} to the first element in the range for which pred returns false. + * If pred is true for all elements, the function returns last. + */ + function find_if_not>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): InputIterator; + /** + * Find last subsequence in range. + * + * Searches the range [first1, last1) for the last occurrence of the sequence defined by + * [first2, last2), and returns an {@link Iterator} to its first element, or last1,/i> if no + * occurrences are found. + * + * The elements in both ranges are compared sequentially using {@link equal_to}: A subsequence of + * [first1, last1) is considered a match only when this is true for all the elements of + * [first2, last2). + * + * This function returns the last of such occurrences. For an algorithm that returns the first instead, see + * {@link search}. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the element values to be searched for. + * @param last2 An {@link Iterator} to the final position of the element values to be searched for. The range used + * is [first2, last2). + * @param pred Binary function that accepts two elements as arguments (one of each of the two sequences, in the + * same order), and returns a value convertible to bool. The value returned indicates + * whether the elements are considered to match in the context of this function. + * + * @return An {@link Iterator} to the first element of the last occurrence of [first2, last2) in + * [first1, last1). If the sequence is not found, the function returns ,i>last1. Otherwise + * [first2, last2) is an empty range, the function returns last1. + */ + function find_end, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): Iterator1; + /** + * Find last subsequence in range. + * + * Searches the range [first1, last1) for the last occurrence of the sequence defined by + * [first2, last2), and returns an {@link Iterator} to its first element, or last1,/i> if no + * occurrences are found. + * + * The elements in both ranges are compared sequentially using pred: A subsequence of + * [first1, last1) is considered a match only when this is true for all the elements of + * [first2, last2). + * + * This function returns the last of such occurrences. For an algorithm that returns the first instead, see + * {@link search}. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the element values to be searched for. + * @param last2 An {@link Iterator} to the final position of the element values to be searched for. The range used + * is [first2, last2). + * @param pred Binary function that accepts two elements as arguments (one of each of the two sequences, in the + * same order), and returns a value convertible to bool. The value returned indicates + * whether the elements are considered to match in the context of this function. + * + * @return An {@link Iterator} to the first element of the last occurrence of [first2, last2) in + * [first1, last1). If the sequence is not found, the function returns ,i>last1. Otherwise + * [first2, last2) is an empty range, the function returns last1. + */ + function find_end, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, pred: (x: T, y: T) => boolean): Iterator1; + /** + * Find element from set in range. + * + * Returns an iterator to the first element in the range [first1, last1) that matches any of the + * elements in [first2, last2). If no such element is found, the function returns last1. + * + * The elements in [first1, last1) are sequentially compared to each of the values in + * [first2, last2) using {@link equal_to}, until a pair matches. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the element values to be searched for. + * @param last2 An {@link Iterator} to the final position of the element values to be searched for. The range used + * is [first2, last2). + * + * @return An {@link Iterator} to the first element in [first1, last1) that is part of + * [first2, last2). If no matches are found, the function returns last1. + */ + function find_first_of, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): Iterator1; + /** + * Find element from set in range. + * + * Returns an iterator to the first element in the range [first1, last1) that matches any of the + * elements in [first2, last2). If no such element is found, the function returns last1. + * + * The elements in [first1, last1) are sequentially compared to each of the values in + * [first2, last2) using pred, until a pair matches. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the element values to be searched for. + * @param last2 An {@link Iterator} to the final position of the element values to be searched for. The range used + * is [first2, last2). + * @param pred Binary function that accepts two elements as arguments (one of each of the two sequences, in the + * same order), and returns a value convertible to bool. The value returned indicates + * whether the elements are considered to match in the context of this function. + * + * @return An {@link Iterator} to the first element in [first1, last1) that is part of + * [first2, last2). If no matches are found, the function returns last1. + */ + function find_first_of, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, pred: (x: T, y: T) => boolean): Iterator1; + /** + * Find equal adjacent elements in range. + * + * Searches the range [first, last) for the first occurrence of two consecutive elements that match, + * and returns an {@link Iterator} to the first of these two elements, or last if no such pair is found. + * + * Two elements match if they compare equal using {@link equal_to}. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * + * @return An {@link Iterator} to the first element of the first pair of matching consecutive elements in the range + * [first, last). If no such pair is found, the function returns last. + */ + function adjacent_find>(first: InputIterator, last: InputIterator): InputIterator; + /** + * Find equal adjacent elements in range. + * + * Searches the range [first, last) for the first occurrence of two consecutive elements that match, + * and returns an {@link Iterator} to the first of these two elements, or last if no such pair is found. + * + * Two elements match if they compare equal using pred. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * @param pred Unary function that accepts an element in the range as argument and returns a value convertible to + * bool. The value returned indicates whether the element is considered a match in the + * context of this function. The function shall not modify its argument. + * + * @return An {@link Iterator} to the first element of the first pair of matching consecutive elements in the range + * [first, last). If no such pair is found, the function returns last. + */ + function adjacent_find>(first: InputIterator, last: InputIterator, pred: (x: T, y: T) => boolean): InputIterator; + /** + * Search range for subsequence. + * + * Searches the range [first1, last1) for the first occurrence of the sequence defined by + * [first2, last2), and returns an iterator to its first element, or last1 if no occurrences are + * found. + * + * The elements in both ranges are compared sequentially using {@link equal_to}: A subsequence of + * [first1, last1) is considered a match only when this is true for all the elements of + * [first2, last2). + * + * This function returns the first of such occurrences. For an algorithm that returns the last instead, see + * {@link find_end}. + * + * @param first1 {@link Iterator Forward iterator} to the initial position of the searched sequence. + * @param last1 {@link Iterator Forward iterator} to the final position of the searched sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Forward iterator} to the initial position of the sequence to be searched for. + * @param last2 {@link Iterator Forward iterator} to the final position of the sequence to be searched for. The range + * used is [first2, last2). + * + * @return An iterator to the first element of the first occurrence of [first2, last2) in first1 + * and last1. If the sequence is not found, the function returns last1. Otherwise + * [first2, last2) is an empty range, the function returns first1. + */ + function search, ForwardIterator2 extends Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2, last2: ForwardIterator2): ForwardIterator1; + /** + * Search range for subsequence. + * + * Searches the range [first1, last1) for the first occurrence of the sequence defined by + * [first2, last2), and returns an iterator to its first element, or last1 if no occurrences are + * found. + * + * The elements in both ranges are compared sequentially using pred: A subsequence of + * [first1, last1) is considered a match only when this is true for all the elements of + * [first2, last2). + * + * This function returns the first of such occurrences. For an algorithm that returns the last instead, see + * {@link find_end}. + * + * @param first1 {@link Iterator Forward iterator} to the initial position of the searched sequence. + * @param last1 {@link Iterator Forward iterator} to the final position of the searched sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Forward iterator} to the initial position of the sequence to be searched for. + * @param last2 {@link Iterator Forward iterator} to the final position of the sequence to be searched for. The range + * used is [first2, last2). + * @param pred Binary function that accepts two elements as arguments (one of each of the two sequences, in the same + * order), and returns a value convertible to bool. The returned value indicates whether the elements are + * considered to match in the context of this function. The function shall not modify any of its + * arguments. + * + * @return An iterator to the first element of the first occurrence of [first2, last2) in + * [first1, last1). If the sequence is not found, the function returns last1. Otherwise + * [first2, last2) is an empty range, the function returns first1. + */ + function search, ForwardIterator2 extends Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2, last2: ForwardIterator2, pred: (x: T, y: T) => boolean): ForwardIterator1; + /** + * Search range for elements. + * + * Searches the range [first, last) for a sequence of count elements, each comparing equal to + * val. + * + * The function returns an iterator to the first of such elements, or last if no such sequence is found. + * + * @param first {@link Iterator Forward iterator} to the initial position of the searched sequence. + * @param last {@link Iterator Forward iterator} to the final position of the searched sequence. 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. + * @param count Minimum number of successive elements to match. + * @param val Individual value to be compared, or to be used as argument for {@link equal_to}. + * + * @return An iterator to the first element of the sequence. If no such sequence is found, the function returns + * last. + */ + function search_n>(first: ForwardIterator, last: ForwardIterator, count: number, val: T): ForwardIterator; + /** + * Search range for elements. + * + * Searches the range [first, last) for a sequence of count elements, each comparing equal to + * val. + * + * The function returns an iterator to the first of such elements, or last if no such sequence is found. + * + * + * @param first {@link Iterator Forward iterator} to the initial position of the searched sequence. + * @param last {@link Iterator Forward iterator} to the final position of the searched sequence. 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. + * @param count Minimum number of successive elements to match. + * @param val Individual value to be compared, or to be used as argument for pred. + * @param pred Binary function that accepts two arguments (one element from the sequence as first, and val as + * second), and returns a value convertible to bool. The value returned indicates whether the + * element is considered a match in the context of this function. The function shall not modify any of its + * arguments. + * + * @return An {@link Iterator} to the first element of the sequence. If no such sequence is found, the function + * returns last. + */ + function search_n>(first: ForwardIterator, last: ForwardIterator, count: number, val: T, pred: (x: T, y: T) => boolean): ForwardIterator; + /** + * Return first position where two ranges differ. + * + * Compares the elements in the range [first1, last1) with those in the range beginning at + * first2, and returns the first element of both sequences that does not match. + * + * The function returns a {@link Pair} of {@link iterators Iterator} to the first element in each range that + * does not match. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to + * as many elements of this sequence as those in the range [first1, last1). + * + * @return A {@link Pair}, where its members {@link Pair.first first} and {@link Pair.second second} point to the + * first element in both sequences that did not compare equal to each other. If the elements compared in + * both sequences have all matched, the function returns a {@link Pair} with {@link Pair.first first} set + * to last1 and {@link Pair.second second} set to the element in that same relative position in the + * second sequence. If none matched, it returns {@link make_pair}(first1, first2). + */ + function mismatch, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2): Pair; + /** + * Return first position where two ranges differ. + * + * Compares the elements in the range [first1, last1) with those in the range beginning at + * first2, and returns the first element of both sequences that does not match. + * + * The function returns a {@link Pair} of {@link iterators Iterator} to the first element in each range that + * does not match. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to + * as many elements of this sequence as those in the range [first1, last1). + * @param pred Binary function that accepts two elements as argument (one of each of the two sequences, in the same + * order), and returns a value convertible to bool. The value returned indicates whether + * the elements are considered to match in the context of this function. + * + * @return A {@link Pair}, where its members {@link Pair.first first} and {@link Pair.second second} point to the + * first element in both sequences that did not compare equal to each other. If the elements compared in + * both sequences have all matched, the function returns a {@link Pair} with {@link Pair.first first} set + * to last1 and {@link Pair.second second} set to the element in that same relative position in the + * second sequence. If none matched, it returns {@link make_pair}(first1, first2). + */ + function mismatch, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, compare: (x: T, y: T) => boolean): Pair; + /** + * Count appearances of value in range. + * + * Returns the number of elements in the range [first, last) that compare equal to val. + * + * The function uses {@link equal_to} to compare the individual elements to val. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * @param val Value to match. + * + * @return The number of elements in the range [first, last) that compare equal to val. + */ + function count>(first: InputIterator, last: InputIterator, val: T): number; + /** + * Return number of elements in range satisfying condition. + * + * Returns the number of elements in the range [first, last) for which pred is true. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible + * to bool. The value returned indicates whether the element is counted by this function. + * The function shall not modify its argument. This can either be a function pointer or a function + * object. + */ + function count_if>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): number; +} +declare namespace std { + /** + * Copy range of elements. + * + * Copies the elements in the range [first, last) into the range beginning at result. + * + * The function returns an iterator to the end of the destination range (which points to the element following the + * last element copied). + * + * The ranges shall not overlap in such a way that result points to an element in the range + * [first, last). For such cases, see {@link copy_backward}. + * + * @param first {@link Iterator Input iterator} to the initial position in a sequence to be copied. + * @param last {@link Iterator Input iterator} to the initial position in a sequence to be copied. 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. + * @param result {@link Iterator Output iterator} to the initial position in the destination sequence. This shall not + * point to any element in the range [first, last). + * + * @return An iterator to the end of the destination range where elements have been copied. + */ + function copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator): OutputIterator; + /** + * Copy elements. + * + * Copies the first n elements from the range beginning at first into the range beginning at + * result. + * + * The function returns an iterator to the end of the destination range (which points to one past the last element + * copied). + * + * If n is negative, the function does nothing. + * + * If the ranges overlap, some of the elements in the range pointed by result may have undefined but valid values. + * + * @param first {@link Iterator Input iterator} to the initial position in a sequence of at least n elements to + * be copied. InputIterator shall point to a type assignable to the elements pointed by + * OutputIterator. + * @param n Number of elements to copy. If this value is negative, the function does nothing. + * @param result {@link Iterator Output iterator} to the initial position in the destination sequence of at least + * n elements. This shall not point to any element in the range [first, last]. + * + * @return An iterator to the end of the destination range where elements have been copied. + */ + function copy_n, OutputIterator extends base.ILinearIterator>(first: InputIterator, n: number, result: OutputIterator): OutputIterator; + /** + * Copy certain elements of range. + * + * Copies the elements in the range [first, last) for which pred returns true to the + * range beginning at result. + * + * @param first {@link Iterator Input iterator} to the initial position in a sequence to be copied. + * @param last {@link Iterator Input iterator} to the initial position in a sequence to be copied. 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. + * @param result {@link Iterator Output iterator} to the initial position in the destination sequence. This shall not + * point to any element in the range [first, last). + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element is to be copied (if + * true, it is copied). The function shall not modify any of its arguments. + * + * @return An iterator to the end of the destination range where elements have been copied. + */ + function copy_if, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (x: T) => boolean): OutputIterator; + /** + * Copy range of elements backward. + * + * Copies the elements in the range [first, last) starting from the end into the range terminating + * at result. + * + * The function returns an iterator to the first element in the destination range. + * + * The resulting range has the elements in the exact same order as [first, last). To reverse their + * order, see {@link reverse_copy}. + * + * The function begins by copying *(last-1) into *(result-1), and then follows backward + * by the elements preceding these, until first is reached (and including it). + * + * The ranges shall not overlap in such a way that result (which is the past-the-end element in the + * destination range) points to an element in the range (first,last]. For such cases, see {@link copy}. + * + * @param first {@link Iterator Bidirectional iterator} to the initial position in a sequence to be copied. + * @param last {@link Iterator Bidirectional iterator} to the initial position in a sequence to be copied. 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. + * @param result {@link Iterator Bidirectional iterator} to the initial position in the destination sequence. This + * shall not point to any element in the range [first, last). + * + * @return An iterator to the first element of the destination sequence where elements have been copied. + */ + function copy_backward, BidirectionalIterator2 extends base.ILinearIterator>(first: BidirectionalIterator1, last: BidirectionalIterator1, result: BidirectionalIterator2): BidirectionalIterator2; + /** + * Fill range with value. + * + * Assigns val to all the elements in the range [first, last). + * + * @param first {@link Iterator Forward iterator} to the initial position in a sequence of elements that support being + * assigned a value of type T. + * @param last {@link Iterator Forward iterator} to the final position in a sequence of elements that support being + * assigned a value of type T.. The range filled 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. + * @param val Value to assign to the elements in the filled range. + */ + function fill>(first: ForwardIterator, last: ForwardIterator, val: T): void; + /** + * Fill sequence with value. + * + * Assigns val to the first n elements of the sequence pointed by first. + * + * @param first {@link Iterator Output iterator} to the initial position in a sequence of elements that support being + * assigned a value of type T. + * @param n Number of elements to fill. If negative, the function does nothing. + * @param val Value to be used to fill the range. + * + * @return An iterator pointing to the element that follows the last element filled. + */ + function fill_n>(first: OutputIterator, n: number, val: T): OutputIterator; + /** + * Transform range. + * + * Applies op to each of the elements in the range [first, last) and stores the value returned + * by each operation in the range that begins at result. + * + * @param first {@link Iterator Input iterator} to the initial position in a sequence to be transformed. + * @param last {@link Iterator Input iterator} to the initial position in a sequence to be transformed. 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. + * @param result {@link Iterator Output} iterator to the initial position of the range where the operation results are + * stored. The range includes as many elements as [first, last). + * @param op Unary function that accepts one element of the type pointed to by InputIterator as argument, and + * returns some result value convertible to the type pointed to by OutputIterator. + * + * @return An iterator pointing to the element that follows the last element written in the result sequence. + */ + function transform, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, op: (val: T) => T): OutputIterator; + /** + * Transform range. + * + * Calls binary_op using each of the elements in the range [first1, last1) as first argument, + * and the respective argument in the range that begins at first2 as second argument. The value returned by + * each call is stored in the range that begins at result. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second range. The range includes as + * many elements as [first1, last1). + * @param result {@link Iterator Output} iterator to the initial position of the range where the operation results are + * stored. The range includes as many elements as [first1, last1). + * @param binary_op Binary function that accepts two elements as argument (one of each of the two sequences), and + * returns some result value convertible to the type pointed to by OutputIterator. + * + * @return An iterator pointing to the element that follows the last element written in the result sequence. + */ + function transform, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, result: OutputIterator, binary_op: (x: T, y: T) => T): OutputIterator; + /** + * Generate values for range with function. + * + * Assigns the value returned by successive calls to gen to the elements in the range [first, last). + * + * @param first {@link Iterator Forward iterator} to the initial position in a sequence. + * @param last {@link Iterator Forward iterator} to the final position in a sequence. The range affected 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. + * @param gen Generator function that is called with no arguments and returns some value of a type convertible to + * those pointed by the iterators. + */ + function generate>(first: ForwardIterator, last: ForwardIterator, gen: () => T): void; + /** + * Generate values for sequence with function. + * + * Assigns the value returned by successive calls to gen to the first n elements of the sequence + * pointed by first. + * + * @param first {@link Iterator Output iterator} to the initial position in a sequence of at least n elements + * that support being assigned a value of the type returned by gen. + * @param n Number of values to generate. If negative, the function does nothing. + * @param gen Generator function that is called with no arguments and returns some value of a type convertible to + * those pointed by the iterators. + * + * @return An iterator pointing to the element that follows the last element whose value has been generated. + */ + function generate_n>(first: ForwardIterator, n: number, gen: () => T): ForwardIterator; + /** + * Remove consecutive duplicates in range. + * + * Removes all but the first element from every consecutive group of equivalent elements in the range + * [first, last). + * + * The function cannot alter the properties of the object containing the range of elements (i.e., it cannot + * alter the size of an array or a container): The removal is done by replacing the duplicate elements by the next + * element that is not a duplicate, and signaling the new size of the shortened range by returning an iterator to + * the element that should be considered its new past-the-last element. + * + * The relative order of the elements not removed is preserved, while the elements between the returned + * iterator and last are left in a valid but unspecified state. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * + * @return An iterator to the element that follows the last element not removed. The range between first and + * this iterator includes all the elements in the sequence that were not considered duplicates. + */ + function unique>(first: InputIterator, last: InputIterator): InputIterator; + /** + * Remove consecutive duplicates in range. + * + * Removes all but the first element from every consecutive group of equivalent elements in the range + * [first, last). + * + * The function cannot alter the properties of the object containing the range of elements (i.e., it cannot + * alter the size of an array or a container): The removal is done by replacing the duplicate elements by the next + * element that is not a duplicate, and signaling the new size of the shortened range by returning an iterator to + * the element that should be considered its new past-the-last element. + * + * The relative order of the elements not removed is preserved, while the elements between the returned + * iterator and last are left in a valid but unspecified state. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * @param pred Binary function that accepts two elements in the range as argument, and returns a value convertible + * to bool. The value returned indicates whether both arguments are considered equivalent + * (if true, they are equivalent and one of them is removed). The function shall not modify + * any of its arguments. + * + * @return An iterator to the element that follows the last element not removed. The range between first and + * this iterator includes all the elements in the sequence that were not considered duplicates. + */ + function unique>(first: InputIterator, last: InputIterator, pred: (left: t, right: t) => boolean): InputIterator; + /** + * Copy range removing duplicates. + * + * Copies the elements in the range [first, last) to the range beginning at result, except + * consecutive duplicates (elements that compare equal to the element preceding). + * + * Only the first element from every consecutive group of equivalent elements in the range + * [first, last) is copied. + * + * The comparison between elements is performed by applying {@lnk equal_to}. + * + * @param first {@link Iterator Forward iterator} to the initial position in a sequence. + * @param last {@link Iterator Forward iterator} to the final position in a sequence. 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. + * @param result Output iterator to the initial position of the range where the resulting range of values is stored. + * The pointed type shall support being assigned the value of an element in the range + * [first, last). + * + * @return An iterator pointing to the end of the copied range, which contains no consecutive duplicates. + */ + function unique_copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator): OutputIterator; + /** + * Copy range removing duplicates. + * + * Copies the elements in the range [first, last) to the range beginning at result, except + * consecutive duplicates (elements that compare equal to the element preceding). + * + * Only the first element from every consecutive group of equivalent elements in the range + * [first, last) is copied. + * + * The comparison between elements is performed by applying pred. + * + * @param first {@link Iterator Forward iterator} to the initial position in a sequence. + * @param last {@link Iterator Forward iterator} to the final position in a sequence. 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. + * @param result Output iterator to the initial position of the range where the resulting range of values is stored. + * The pointed type shall support being assigned the value of an element in the range + * [first, last). + * @param pred Binary function that accepts two elements in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether both arguments are considered equivalent (if + * true, they are equivalent and one of them is removed). The function shall not modify any + * of its arguments. + * + * @return An iterator pointing to the end of the copied range, which contains no consecutive duplicates. + */ + function unique_copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (x: T, y: T) => boolean): OutputIterator; + /** + * Remove value from range. + * + * Transforms the range [first, last) into a range with all the elements that compare equal to + * val removed, and returns an iterator to the new last of that range. + * + * The function cannot alter the properties of the object containing the range of elements (i.e., it cannot alter + * the size of an array or a container): The removal is done by replacing the elements that compare equal to + * val by the next element that does not, and signaling the new size of the shortened range by returning an + * iterator to the element that should be considered its new past-the-last element. + * + * The relative order of the elements not removed is preserved, while the elements between the returned iterator + * and last are left in a valid but unspecified state. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * @param val Value to be removed. + */ + function remove>(first: InputIterator, last: InputIterator, val: T): InputIterator; + /** + * Remove elements from range. + * + * Transforms the range [first, last) into a range with all the elements for which pred returns + * true removed, and returns an iterator to the new last of that range. + * + * The function cannot alter the properties of the object containing the range of elements (i.e., it cannot + * alter the size of an array or a container): The removal is done by replacing the elements for which pred returns + * true by the next element for which it does not, and signaling the new size of the shortened range + * by returning an iterator to the element that should be considered its new past-the-last element. + * + * The relative order of the elements not removed is preserved, while the elements between the returned + * iterator and last are left in a valid but unspecified state. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element is to be removed (if + * true, it is removed). The function shall not modify its argument. + */ + function remove_if>(first: InputIterator, last: InputIterator, pred: (left: T) => boolean): InputIterator; + /** + * Copy range removing value. + * + * Copies the elements in the range [first, last) to the range beginning at result, except + * those elements that compare equal to val. + * + * The resulting range is shorter than [first, last) by as many elements as matches in the sequence, + * which are "removed". + * + * The function uses {@link equal_to} to compare the individual elements to val. + * + * @param first {@link Iterator InputIterator} to the initial position in a sequence. + * @param last {@link Iterator InputIterator} to the final position in a sequence. 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. + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element in the range + * [first, last). + * @param val Value to be removed. + * + * @return An iterator pointing to the end of the copied range, which includes all the elements in + * [first, last) except those that compare equal to val. + */ + function remove_copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, val: T): OutputIterator; + /** + * Copy range removing values. + * + * Copies the elements in the range [first, last) to the range beginning at result, except + * those elements for which pred returns true. + * + * The resulting range is shorter than [first, last) by as many elements as matches, which are + * "removed". + * + * @param first {@link Iterator InputIterator} to the initial position in a sequence. + * @param last {@link Iterator InputIterator} to the final position in a sequence. 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. + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element in the range + * [first, last). + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element is to be removed from the copy (if + * true, it is not copied). The function shall not modify its argument. + * + * @return An iterator pointing to the end of the copied range, which includes all the elements in + * [first, last) except those for which pred returns true. + */ + function remove_copy_if, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (val: T) => boolean): OutputIterator; + /** + * Replace value in range. + * + * Assigns new_val to all the elements in the range [first, last) that compare equal to + * old_val. + * + * The function uses {@link equal_to} to compare the individual elements to old_val. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * @param old_val Value to be replaced. + * @param new_val Replacement value. + */ + function replace>(first: InputIterator, last: InputIterator, old_val: T, new_val: T): void; + /** + * Replace value in range. + * + * Assigns new_val to all the elements in the range [first, last) for which pred returns + * true. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element is to be replaced (if + * true, it is replaced). The function shall not modify its argument. + * @param new_val Value to assign to replaced elements. + */ + function replace_if>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean, new_val: T): void; + /** + * Copy range replacing value. + * + * Copies the elements in the range [first, last) to the range beginning at result, replacing + * the appearances of old_value by new_value. + * + * The function uses {@link equal_to} to compare the individual elements to old_value. + * + * The ranges shall not overlap in such a way that result points to an element in the range + * [first, last). + * + * @param first {@link Iterator InputIterator} to the initial position in a sequence. + * @param last {@link Iterator InputIterator} to the final position in a sequence. 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. + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element in the range + * [first, last). + * @param old_val Value to be replaced. + * @param new_val Replacement value. + * + * @return An iterator pointing to the element that follows the last element written in the result sequence. + */ + function replace_copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, old_val: T, new_val: T): OutputIterator; + /** + * Copy range replacing value. + * + * Copies the elements in the range [first, last) to the range beginning at result, replacing + * those for which pred returns true by new_value. + * + * @param first {@link Iterator InputIterator} to the initial position in a sequence. + * @param last {@link Iterator InputIterator} to the final position in a sequence. 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. + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element in the range + * [first, last). + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element is to be removed from the copy (if + * true, it is not copied). The function shall not modify its argument. + * @param new_val Value to assign to replaced values. + * + * @return An iterator pointing to the element that follows the last element written in the result sequence. + */ + function replace_copy_if, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (val: T) => boolean, new_val: T): OutputIterator; + /** + * Exchange values of objects pointed to by two iterators. + * + * Swaps the elements pointed to by x and y. + * + * The function calls {@link Iterator.swap} to exchange the elements. + * + * @param x {@link Iterator Forward iterator} to the objects to swap. + * @param y {@link Iterator Forward iterator} to the objects to swap. + */ + function iter_swap(x: Iterator, y: Iterator): void; + /** + * Exchange values of two ranges. + * + * Exchanges the values of each of the elements in the range [first1, last1) with those of their + * respective elements in the range beginning at first2. + * + * The function calls {@link Iterator.swap} to exchange the elements. + * + * @param first1 {@link Iterator Forward iterator} to the initial position of the first sequence. + * @param last1 {@link Iterator Forward iterator} to the final position of the first sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 {@link Iterator Forward iterator} to the initial position of the second range. The range includes as + * many elements as [first1, last1). The two ranges shall not overlap. + * + * @return An iterator to the last element swapped in the second sequence. + */ + function swap_ranges, ForwardIterator2 extends Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2): ForwardIterator2; + /** + * Reverse range. + * + * Reverses the order of the elements in the range [first, last). + * + * The function calls {@link iter_swap} to swap the elements to their new locations. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + */ + function reverse>(first: InputIterator, last: InputIterator): void; + /** + * Copy range reversed. + * + * Copies the elements in the range [first, last) to the range beginning at result, but in + * reverse order. + * + * @param first {@link Iterator Bidirectional iterator} to the initial position in a sequence to be copied. + * @param last {@link Iterator Bidirectional iterator} to the initial position in a sequence to be copied. 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. + * @param result {@link Iterator Output iterator} to the initial position of the range where the reserved range is + * stored. The pointed type shall support being assigned the value of an element in the range + * [first, last). + * + * @return An output iterator pointing to the end of the copied range, which contains the same elements in reverse + * order. + */ + function reverse_copy, OutputIterator extends base.ILinearIterator>(first: BidirectionalIterator, last: BidirectionalIterator, result: OutputIterator): OutputIterator; + /** + * Rotate left the elements in range. + * + * Rotates the order of the elements in the range [first, last), in such a way that the element + * pointed by middle becomes the new first element. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param middle An {@link Iterator} pointing to the element within the range [first, last) that is + * moved to the first position in the range. + * @param last An {@link Iterator} to the final position in a sequence. 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. + * + * @return An iterator pointing to the element that now contains the value previously pointed by first. + */ + function rotate>(first: InputIterator, middle: InputIterator, last: InputIterator): InputIterator; + /** + * Copy range rotated left. + * + * Copies the elements in the range [first, last) to the range beginning at result, but + * rotating the order of the elements in such a way that the element pointed by middle becomes the first + * element in the resulting range. + * + * @param first {@link Iterator Forward iterator} to the initial position of the range to be copy-rotated. + * @param middle Forward iterator pointing to the element within the range [first, last) that is copied as the first element in the resulting range. + * @param last {@link Iterator Forward iterator} to the final positions of the range to be copy-rotated. 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. + * Notice that in this function, these are not consecutive parameters, but the first and third ones. + * @param result {@link Iterator Output iterator} to the initial position of the range where the reserved range is + * stored. The pointed type shall support being assigned the value of an element in the range + * [first, last). + * + * @return An output iterator pointing to the end of the copied range. + */ + function rotate_copy, OutputIterator extends base.ILinearIterator>(first: ForwardIterator, middle: ForwardIterator, last: ForwardIterator, result: OutputIterator): OutputIterator; + /** + * Randomly rearrange elements in range. + * + * Rearranges the elements in the range [first, last) randomly. + * + * The function swaps the value of each element with that of some other randomly picked element. When provided, + * the function gen determines which element is picked in every case. Otherwise, the function uses some unspecified + * source of randomness. + * + * To specify a uniform random generator, see {@link shuffle}. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + */ + function random_shuffle>(first: RandomAccessIterator, last: RandomAccessIterator): void; + /** + * Randomly rearrange elements in range using generator. + * + * Rearranges the elements in the range [first, last) randomly, using g as uniform random + * number generator. + * + * The function swaps the value of each element with that of some other randomly picked element. The function + * determines the element picked by calling g(). + * + * To shuffle the elements of the range without such a generator, see {@link random_shuffle} instead. + * + *
    Note
    + * Using random generator engine is not implemented yet. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. 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. + */ + function shuffle>(first: RandomAccessIterator, last: RandomAccessIterator): void; +} +declare namespace std { + /** + * Sort elements in range. + * + * Sorts the elements in the range [first, last) into ascending order. The elements are compared + * using {@link less}. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be sorted. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. + * 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. {@link IArrayIterator RandomAccessIterator} shall point to a type for which + * {@link Iterator.swap swap} is properly defined. + */ + function sort>(first: RandomAccessIterator, last: RandomAccessIterator): void; + /** + * Sort elements in range. + * + * Sorts the elements in the range [first, last) into specific order. The elements are compared + * using compare. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be sorted. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. + * 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. {@link IArrayIterator RandomAccessIterator} shall point to a type for which + * {@link Iterator.swap swap} is properly defined. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value + * convertible to boolean. The value returned indicates whether the element passed as first + * argument is considered to go before the second in the specific strict weak ordering it defines. The + * function shall not modify any of its arguments. This can either be a function pointer or a function + * object. + */ + function sort>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (left: T, right: T) => boolean): void; + /** + * Partially sort elements in range. + * + * Rearranges the elements in the range [first, last), in such a way that the elements before + * middle are the smallest elements in the entire range and are sorted in ascending order, while the remaining + * elements are left without any specific order. + * + * The elements are compared using {@link less}. + * + * @param last {@link IArrayIterator Random-access iterator} to the first position of the sequence to be sorted. + * @param middle {@link IArrayIterator Random-access iterator} pointing to the element within the range [first, last) that is used as the upper boundary of the elements that are fully sorted. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. + * 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. + */ + function partial_sort>(first: RandomAccessIterator, middle: RandomAccessIterator, last: RandomAccessIterator): void; + /** + * Partially sort elements in range. + * + * Rearranges the elements in the range [first, last), in such a way that the elements before + * middle are the smallest elements in the entire range and are sorted in ascending order, while the remaining + * elements are left without any specific order. + * + * The elements are compared using comp. + * + * @param last {@link IArrayIterator Random-access iterator} to the first position of the sequence to be sorted. + * @param middle {@link IArrayIterator Random-access iterator} pointing to the element within the range [first, last) that is used as the upper boundary of the elements that are fully sorted. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. + * 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. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value + * convertible to boolean. The value returned indicates whether the element passed as + * first argument is considered to go before the second in the specific strict weak ordering it + * defines. The function shall not modify any of its arguments. + */ + function partial_sort>(first: RandomAccessIterator, middle: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; + /** + * Copy and partially sort range. + * + * Copies the smallest elements in the range [first, last) to + * [result_first, result_last), sorting the elements copied. The number of elements copied is the same + * as the {@link distance} between result_first and result_last (unless this is more than the amount of + * elements in [first, last)). + * + * The range [first, last) is not modified. + * + * The elements are compared using {@link less}. + * + * @param first {@link Iterator Input iterator} to the initial position of the sequence to copy from. + * @param last {@link Iterator Input iterator} to the final position of the sequence to copy from. 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. + * InputIterator shall point to a type assignable to the elements pointed by + * RandomAccessIterator. + * @param result_first {@link Iterator Random-access iterator} to the initial position of the destination sequence. + * @param result_last {@link Iterator Random-access iterator} to the final position of the destination sequence. + * The range used is [result_first, result_last). + * @param compare Binary function that accepts two elements in the result range as arguments, and returns a value + * convertible to bool. The value returned indicates whether the element passed as first + * argument is considered to go before the second in the specific strict weak ordering it + * defines. The function shall not modify any of its arguments. + * + * @return An iterator pointing to the element that follows the last element written in the result sequence. + */ + function partial_sort_copy, RandomAccessIterator extends Iterator>(first: InputIterator, last: InputIterator, result_first: RandomAccessIterator, result_last: RandomAccessIterator): RandomAccessIterator; + /** + * Copy and partially sort range. + * + * Copies the smallest (or largest) elements in the range [first, last) to + * [result_first, result_last), sorting the elements copied. The number of elements copied is the same + * as the {@link distance} between result_first and result_last (unless this is more than the amount of + * elements in [first, last)). + * + * The range [first, last) is not modified. + * + * The elements are compared using compare. + * + * @param first {@link Iterator Input iterator} to the initial position of the sequence to copy from. + * @param last {@link Iterator Input iterator} to the final position of the sequence to copy from. 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. + * InputIterator shall point to a type assignable to the elements pointed by + * RandomAccessIterator. + * @param result_first {@link Iterator Random-access iterator} to the initial position of the destination sequence. + * @param result_last {@link Iterator Random-access iterator} to the final position of the destination sequence. + * The range used is [result_first, result_last). + * @param compare Binary function that accepts two elements in the result range as arguments, and returns a value + * convertible to bool. The value returned indicates whether the element passed as first + * argument is considered to go before the second in the specific strict weak ordering it + * defines. The function shall not modify any of its arguments. + * + * @return An iterator pointing to the element that follows the last element written in the result sequence. + */ + function partial_sort_copy, RandomAccessIterator extends Iterator>(first: InputIterator, last: InputIterator, result_first: RandomAccessIterator, result_last: RandomAccessIterator, compare: (x: T, y: T) => boolean): RandomAccessIterator; + /** + * Check whether range is sorted. + * + * Returns true if the range [first, last) is sorted into ascending order. + * + * The elements are compared using {@link less}. + * + * @param first {@link Iterator Forward iterator} to the initial position of the sequence. + * @param last {@link Iterator Forward iterator} to the final position of the sequence. The range checked 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. + * + * @return true if the range [first, last) is sorted into ascending order, + * false otherwise. If the range [first, last) contains less than two elements, + * the function always returns true. + */ + function is_sorted>(first: ForwardIterator, last: ForwardIterator): boolean; + /** + * Check whether range is sorted. + * + * Returns true if the range [first, last) is sorted into ascending order. + * + * The elements are compared using compare. + * + * @param first {@link Iterator Forward iterator} to the initial position of the sequence. + * @param last {@link Iterator Forward iterator} to the final position of the sequence. The range checked 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. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible + * to bool. The value returned indicates whether the element passed as first argument is + * considered to go before the second in the specific strict weak ordering it defines. The function + * shall not modify any of its arguments. + * + * @return true if the range [first, last) is sorted into ascending order, + * false otherwise. If the range [first, last) contains less than two elements, + * the function always returns true. + */ + function is_sorted>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): boolean; + /** + * Find first unsorted element in range. + * + * Returns an iterator to the first element in the range [first, last) which does not follow an + * ascending order. + * + * The range between first and the iterator returned {@link is_sorted is sorted}. + * + * If the entire range is sorted, the function returns last. + * + * The elements are compared using {@link equal_to}. + * + * @param first {@link Iterator Forward iterator} to the initial position of the sequence. + * @param last {@link Iterator Forward iterator} to the final position of the sequence. The range checked 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. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible + * to bool. The value returned indicates whether the element passed as first argument is + * considered to go before the second in the specific strict weak ordering it defines. The function + * shall not modify any of its arguments. + * + * @return An iterator to the first element in the range which does not follow an ascending order, or last if + * all elements are sorted or if the range contains less than two elements. + */ + function is_sorted_until>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; + /** + * Find first unsorted element in range. + * + * Returns an iterator to the first element in the range [first, last) which does not follow an + * ascending order. + * + * The range between first and the iterator returned {@link is_sorted is sorted}. + * + * If the entire range is sorted, the function returns last. + * + * The elements are compared using compare. + * + * @param first {@link Iterator Forward iterator} to the initial position of the sequence. + * @param last {@link Iterator Forward iterator} to the final position of the sequence. The range checked 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. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible + * to bool. The value returned indicates whether the element passed as first argument is + * considered to go before the second in the specific strict weak ordering it defines. The function + * shall not modify any of its arguments. + * + * @return An iterator to the first element in the range which does not follow an ascending order, or last if + * all elements are sorted or if the range contains less than two elements. + */ + function is_sorted_until>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): ForwardIterator; +} +declare namespace std { + /** + * Make heap from range. + * + * Rearranges the elements in the range [first, last) in such a way that they form a heap. + * + * A heap is a way to organize the elements of a range that allows for fast retrieval of the element with the + * highest value at any moment (with {@link pop_heap}), even repeatedly, while allowing for fast insertion of new + * elements (with {@link push_heap}). + * + * The element with the highest value is always pointed by first. The order of the other elements depends on the + * particular implementation, but it is consistent throughout all heap-related functions of this header. + * + * The elements are compared using {@link less}: The element with the highest value is an element for which this + * would return false when compared to every other element in the range. + * + * The standard container adaptor {@link PriorityQueue} calls {@link make_heap}, {@link push_heap} and + * {@link pop_heap} automatically to maintain heap properties for a container. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be + * transformed into a heap. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be transformed + * into a heap. 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. {@link IArrayIterator RandomAccessIterator} shall point to a type for which + * {@link Iterator.swap swap} is properly defined. + */ + function make_heap>(first: RandomAccessIterator, last: RandomAccessIterator): void; + /** + * Make heap from range. + * + * Rearranges the elements in the range [first, last) in such a way that they form a heap. + * + * A heap is a way to organize the elements of a range that allows for fast retrieval of the element with the + * highest value at any moment (with {@link pop_heap}), even repeatedly, while allowing for fast insertion of new + * elements (with {@link push_heap}). + * + * The element with the highest value is always pointed by first. The order of the other elements depends on the + * particular implementation, but it is consistent throughout all heap-related functions of this header. + * + * The elements are compared using compare: The element with the highest value is an element for which this + * would return false when compared to every other element in the range. + * + * The standard container adaptor {@link PriorityQueue} calls {@link make_heap}, {@link push_heap} and + * {@link pop_heap} automatically to maintain heap properties for a container. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be + * transformed into a heap. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be transformed + * into a heap. 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. {@link IArrayIterator RandomAccessIterator} shall point to a type for which + * {@link Iterator.swap swap} is properly defined. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value + * convertible to boolean. The value returned indicates whether the element passed as + * first argument is considered to go before the second in the specific strict weak ordering it defines. + * The function shall not modify any of its arguments. This can either be a function pointer or a + * function object. + */ + function make_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; + /** + * Push element into heap range. + * + * Given a heap in the range [first, last - 1), this function extends the range considered a heap to + * [first, last) by placing the value in (last - 1) into its corresponding location within it. + * + * + * A range can be organized into a heap by calling {@link make_heap}. After that, its heap properties are + * preserved if elements are added and removed from it using {@link push_heap} and {@link pop_heap}, respectively. + * + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the new heap range, including + * the pushed element. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the new heap range, including + * the pushed element. 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. {@link IArrayIterator RandomAccessIterator} shall point to a type for which + * {@link Iterator.swap swap} is properly defined. + */ + function push_heap>(first: RandomAccessIterator, last: RandomAccessIterator): void; + /** + * Push element into heap range. + * + * Given a heap in the range [first, last - 1), this function extends the range considered a heap to + * [first, last) by placing the value in (last - 1) into its corresponding location within it. + * + * A range can be organized into a heap by calling {@link make_heap}. After that, its heap properties are + * preserved if elements are added and removed from it using {@link push_heap} and {@link pop_heap}, respectively. + * + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the new heap range, including + * the pushed element. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the new heap range, including + * the pushed element. 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. {@link IArrayIterator RandomAccessIterator} shall point to a type for which + * {@link Iterator.swap swap} is properly defined. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value + * convertible to boolean. The value returned indicates whether the element passed as + * first argument is considered to go before the second in the specific strict weak ordering it defines. + * The function shall not modify any of its arguments. This can either be a function pointer or a + * function object. + */ + function push_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; + /** + * Pop element from heap range. + * + * Rearranges the elements in the heap range [first, last) in such a way that the part considered a + * heap is shortened by one: The element with the highest value is moved to (last - 1). + * + * While the element with the highest value is moved from first to (last - 1) (which now is out of the + * heap), the other elements are reorganized in such a way that the range [first, last - 1) preserves + * the properties of a heap. + * + * A range can be organized into a heap by calling {@link make_heap}. After that, its heap properties are + * preserved if elements are added and removed from it using {@link push_heap} and {@link pop_heap}, respectively. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the heap to be shrank by one. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the heap to be shrank by one. + * 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. + * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} + * is properly defined. + */ + function pop_heap>(first: RandomAccessIterator, last: RandomAccessIterator): void; + /** + * Pop element from heap range. + * + * Rearranges the elements in the heap range [first, last) in such a way that the part considered a + * heap is shortened by one: The element with the highest value is moved to (last - 1). + * + * While the element with the highest value is moved from first to (last - 1) (which now is out of the + * heap), the other elements are reorganized in such a way that the range [first, last - 1) preserves + * the properties of a heap. + * + * A range can be organized into a heap by calling {@link make_heap}. After that, its heap properties are + * preserved if elements are added and removed from it using {@link push_heap} and {@link pop_heap}, respectively. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the heap to be shrank by one. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the heap to be shrank by one. + * 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. + * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} + * is properly defined. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value + * convertible to boolean. The value returned indicates whether the element passed as + * first argument is considered to go before the second in the specific strict weak ordering it defines. + * The function shall not modify any of its arguments. This can either be a function pointer or a + * function object. + */ + function pop_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; + /** + * Test if range is heap. + * + * Returns true if the range [first, last) forms a heap, as if constructed with {@link make_heap}. + * + * The elements are compared using {@link less}. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence. 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. + * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} + * is properly defined. + * + * @return true if the range [first, last) is a heap (as if constructed with + * {@link make_heap}), false otherwise. If the range [first, last) contains less + * than two elements, the function always returns true. + */ + function is_heap>(first: RandomAccessIterator, last: RandomAccessIterator): boolean; + /** + * Test if range is heap. + * + * Returns true if the range [first, last) forms a heap, as if constructed with {@link make_heap}. + * + * The elements are compared using compare. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence. 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. + * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} + * is properly defined. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value + * convertible to boolean. The value returned indicates whether the element passed as + * first argument is considered to go before the second in the specific strict weak ordering it defines. + * The function shall not modify any of its arguments. This can either be a function pointer or a + * function object. + * + * @return true if the range [first, last) is a heap (as if constructed with + * {@link make_heap}), false otherwise. If the range [first, last) contains less + * than two elements, the function always returns true. + */ + function is_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): boolean; + /** + * Find first element not in heap order. + * + * Returns an iterator to the first element in the range [first, last) which is not in a valid + * position if the range is considered a heap (as if constructed with {@link make_heap}). + * + * The range between first and the iterator returned is a heap. + * + * If the entire range is a valid heap, the function returns last. + * + * The elements are compared using {@link less}. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence. 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. + * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} + * is properly defined. + */ + function is_heap_until>(first: RandomAccessIterator, last: RandomAccessIterator): RandomAccessIterator; + /** + * Find first element not in heap order. + * + * Returns an iterator to the first element in the range [first, last) which is not in a valid + * position if the range is considered a heap (as if constructed with {@link make_heap}). + * + * The range between first and the iterator returned is a heap. + * + * If the entire range is a valid heap, the function returns last. + * + * The elements are compared using {@link less}. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence. 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. + * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} + * is properly defined. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value + * convertible to boolean. The value returned indicates whether the element passed as + * first argument is considered to go before the second in the specific strict weak ordering it defines. + * The function shall not modify any of its arguments. This can either be a function pointer or a + * function object. + */ + function is_heap_until>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): RandomAccessIterator; + /** + * Sort elements of heap. + * + * Sorts the elements in the heap range [first, last) into ascending order. + * + * The elements are compared using {@link less}, which shall be the same as used to construct the heap. + * + * The range loses its properties as a heap. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be sorted. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. + * 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. + * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} + * is properly defined. + */ + function sort_heap>(first: RandomAccessIterator, last: RandomAccessIterator): void; + /** + * Sort elements of heap. + * + * Sorts the elements in the heap range [first, last) into ascending order. + * + * The elements are compared using compare, which shall be the same as used to construct the heap. + * + * The range loses its properties as a heap. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be sorted. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. + * 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. + * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} + * is properly defined. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value + * convertible to boolean. The value returned indicates whether the element passed as + * first argument is considered to go before the second in the specific strict weak ordering it defines. + * The function shall not modify any of its arguments. This can either be a function pointer or a + * function object. + */ + function sort_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; +} +declare namespace std { + /** + * Return iterator to lower bound. + * + * Returns an iterator pointing to the first element in the range [first, last) which does not + * compare less than val. + * + * The elements are compared using {@link less}. The elements in the range shall already be {@link is_sorted sorted} + * according to this same criterion ({@link less}), or at least {@link is_partitioned partitioned} with respect to + * val. + * + * The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted + * range, which is specially efficient for {@link IArrayIterator random-access iterators}. + * + * Unlike {@link upper_bound}, the value pointed by the iterator returned by this function may also be equivalent + * to val, and not only greater. + * + * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. + * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. 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. + * @param val Value of the lower bound to search for in the range. T shall be a type supporting being compared + * with elements of the range [first, last) as the left-hand side operand of {@link less}. + * + * @return An iterator to the lower bound of val in the range. If all the element in the range compare less than + * val, the function returns last. + */ + function lower_bound>(first: ForwardIterator, last: ForwardIterator, val: T): ForwardIterator; + /** + * Return iterator to lower bound. + * + * Returns an iterator pointing to the first element in the range [first, last) which does not + * compare less than val. + * + * The elements are compared using compare. The elements in the range shall already be + * {@link is_sorted sorted} according to this same criterion (compare), or at least + * {@link is_partitioned partitioned} with respect to val. + * + * The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted + * range, which is specially efficient for {@link IArrayIterator random-access iterators}. + * + * Unlike {@link upper_bound}, the value pointed by the iterator returned by this function may also be equivalent + * to val, and not only greater. + * + * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. + * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. 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. + * @param val Value of the lower bound to search for in the range. + * @param compare Binary function that accepts two arguments (the first of the type pointed by ForwardIterator, + * and the second, always val), and returns a value convertible to bool. The value + * returned indicates whether the first argument is considered to go before the second. The function + * shall not modify any of its arguments. + * + * @return An iterator to the lower bound of val in the range. If all the element in the range compare less than + * val, the function returns last. + */ + function lower_bound>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): ForwardIterator; + /** + * Return iterator to upper bound. + * + * Returns an iterator pointing to the first element in the range [first, last) which compares + * greater than val. + * + * The elements are compared using {@link less}. The elements in the range shall already be {@link is_sorted sorted} + * according to this same criterion ({@link less}), or at least {@link is_partitioned partitioned} with respect to + * val. + * + * The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted + * range, which is specially efficient for {@link IArrayIterator random-access iterators}. + * + * Unlike {@link lower_bound}, the value pointed by the iterator returned by this function cannot be equivalent to + * val, only greater. + * + * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. + * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. 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. + * @param val Value of the lower bound to search for in the range. T shall be a type supporting being compared + * with elements of the range [first, last) as the left-hand side operand of {@link less}. + * + * @return An iterator to the upper bound of val in the range. If no element in the range comparse greater than + * val, the function returns last. + */ + function upper_bound>(first: ForwardIterator, last: ForwardIterator, val: T): ForwardIterator; + /** + * Return iterator to upper bound. + * + * Returns an iterator pointing to the first element in the range [first, last) which compares + * greater than val. + * + * The elements are compared using compare. The elements in the range shall already be + * {@link is_sorted sorted} according to this same criterion (compare), or at least + * {@link is_partitioned partitioned} with respect to val. + * + * The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted + * range, which is specially efficient for {@link IArrayIterator random-access iterators}. + * + * Unlike {@link lower_bound}, the value pointed by the iterator returned by this function cannot be equivalent to + * val, only greater. + * + * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. + * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. 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. + * @param val Value of the lower bound to search for in the range. + * @param compare Binary function that accepts two arguments (the first of the type pointed by ForwardIterator, + * and the second, always val), and returns a value convertible to bool. The value + * returned indicates whether the first argument is considered to go before the second. The function + * shall not modify any of its arguments. + * + * @return An iterator to the upper bound of val in the range. If no element in the range comparse greater than + * val, the function returns last. + */ + function upper_bound>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): ForwardIterator; + /** + * Get subrange of equal elements. + * + * Returns the bounds of the subrange that includes all the elements of the range [first, last) with + * values equivalent to val. + * + * The elements are compared using {@link less}. Two elements, ax/i> and y are considered equivalent + * if (!less(x, y) && !less(y, x)). + * + * The elements in the range shall already be {@link is_sorted sorted} according to this same criterion + * ({@link less}), or at least {@link is_partitioned partitioned} with respect to val. + * + * If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both + * iterators pointing to the nearest value greater than val, if any, or to last, if val compares + * greater than all the elements in the range. + * + * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. + * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. 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. + * @param val Value of the lower bound to search for in the range. T shall be a type supporting being compared + * with elements of the range [first, last) as the left-hand side operand of {@link less}. + * + * @return A {@link Pair} object, whose member {@link Pair.first} is an iterator to the lower bound of the subrange of + * equivalent values, and {@link Pair.second} its upper bound. The values are the same as those that would be + * returned by functions {@link lower_bound} and {@link upper_bound} respectively. + */ + function equal_range>(first: ForwardIterator, last: ForwardIterator, val: T): Pair; + /** + * Get subrange of equal elements. + * + * Returns the bounds of the subrange that includes all the elements of the range [first, last) with + * values equivalent to val. + * + * The elements are compared using compare. Two elements, ax/i> and y are considered equivalent + * if (!compare(x, y) && !compare(y, x)). + * + * The elements in the range shall already be {@link is_sorted sorted} according to this same criterion + * (compare), or at least {@link is_partitioned partitioned} with respect to val. + * + * If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both + * iterators pointing to the nearest value greater than val, if any, or to last, if val compares + * greater than all the elements in the range. + * + * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. + * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. 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. + * @param val Value of the lower bound to search for in the range. + * @param compare Binary function that accepts two arguments of the type pointed by ForwardIterator (and of type + * T), and returns a value convertible to bool. The value returned indicates whether + * the first argument is considered to go before the second. The function shall not modify any of its + * arguments. + * + * @return A {@link Pair} object, whose member {@link Pair.first} is an iterator to the lower bound of the subrange of + * equivalent values, and {@link Pair.second} its upper bound. The values are the same as those that would be + * returned by functions {@link lower_bound} and {@link upper_bound} respectively. + */ + function equal_range>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): Pair; + /** + * Get subrange of equal elements. + * + * Returns the bounds of the subrange that includes all the elements of the range [first, last) with + * values equivalent to val. + * + * The elements are compared using {@link less}. Two elements, x and y are considered equivalent + * if (!less(x, y) && !less(y, x)). + * + * The elements in the range shall already be {@link is_sorted sorted} according to this same criterion + * ({@link less}), or at least {@link is_partitioned partitioned} with respect to val. + * + * If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both + * iterators pointing to the nearest value greater than val, if any, or to last, if val compares + * greater than all the elements in the range. + * + * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. + * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. 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. + * @param val Value of the lower bound to search for in the range. T shall be a type supporting being compared + * with elements of the range [first, last) as the left-hand side operand of {@link less}. + * + * @return true if an element equivalent to val is found, and false otherwise. + */ + function binary_search>(first: ForwardIterator, last: ForwardIterator, val: T): boolean; + /** + * Get subrange of equal elements. + * + * Returns the bounds of the subrange that includes all the elements of the range [first, last) with + * values equivalent to val. + * + * The elements are compared using {compare}. Two elements, x and y are considered equivalent + * if (!compare(x, y) && !compare(y, x)). + * + * The elements in the range shall already be {@link is_sorted sorted} according to this same criterion + * (compare), or at least {@link is_partitioned partitioned} with respect to val. + * + * If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both + * iterators pointing to the nearest value greater than val, if any, or to last, if val compares + * greater than all the elements in the range. + * + * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. + * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. 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. + * @param val Value of the lower bound to search for in the range. + * @param compare Binary function that accepts two arguments of the type pointed by ForwardIterator (and of type + * T), and returns a value convertible to bool. The value returned indicates whether + * the first argument is considered to go before the second. The function shall not modify any of its + * arguments. + * + * @return true if an element equivalent to val is found, and false otherwise. + */ + function binary_search>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): boolean; +} +declare namespace std { + /** + * Test whether range is partitioned. + * + * Returns true if all the elements in the range [first, last) for which pred + * returns true precede those for which it returns false. + * + * If the range is {@link Container.empty empty}, the function returns true. + * + * @param first {@link Iterator Input iterator} to the initial position of the sequence. + * @param last {@link Iterator Input iterator} to the final position of the sequence. 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. + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element belongs to the first group (if + * true, the element is expected before all the elements for which it returns + * false). The function shall not modify its argument. + * + * @return true if all the elements in the range [first, last) for which pred returns + * true precede those for which it returns false. Otherwise it returns + * false. If the range is {@link Container.empty empty}, the function returns true. + */ + function is_partitioned>(first: InputIterator, last: InputIterator, pred: (x: T) => boolean): boolean; + /** + * Partition range in two. + * + * Rearranges the elements from the range [first, last), in such a way that all the elements for + * which pred returns true precede all those for which it returns false. The iterator + * returned points to the first element of the second group. + * + * The relative ordering within each group is not necessarily the same as before the call. See + * {@link stable_partition} for a function with a similar behavior but with stable ordering within each group. + * + * @param first {@link Iterator Forward iterator} to the initial position of the sequence to partition. + * @param last {@link Iterator Forward iterator} to the final position of the sequence to partition. 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. + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element belongs to the first group (if + * true, the element is expected before all the elements for which it returns + * false). The function shall not modify its argument. + * + * @return An iterator that points to the first element of the second group of elements (those for which pred + * returns false), or last if this group is {@link Container.empty empty}. + */ + function partition>(first: BidirectionalIterator, last: BidirectionalIterator, pred: (x: T) => boolean): BidirectionalIterator; + /** + * Partition range in two - stable ordering. + * + * Rearranges the elements in the range [first, last), in such a way that all the elements for which + * pred returns true precede all those for which it returns false, and, unlike + * function {@link partition}, the relative order of elements within each group is preserved. + * + * This is generally implemented using an internal temporary buffer. + * + * @param first {@link Iterator Bidirectional iterator} to the initial position of the sequence to partition. + * @param last {@link Iterator Bidirectional iterator} to the final position of the sequence to partition. 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. + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element belongs to the first group (if + * true, the element is expected before all the elements for which it returns + * false). The function shall not modify its argument. + * + * @return An iterator that points to the first element of the second group of elements (those for which pred + * returns false), or last if this group is {@link Container.empty empty}. + */ + function stable_partition>(first: BidirectionalIterator, last: BidirectionalIterator, pred: (x: T) => boolean): BidirectionalIterator; + /** + * Partition range into two. + * + * Copies the elements in the range [first, last) for which pred returns true + * into the range pointed by result_true, and those for which it does not into the range pointed by + * result_false. + * + * @param first {@link Iterator Input iterator} to the initial position of the range to be copy-partitioned. + * @param last {@link Iterator Input iterator} to the final position of the range to be copy-partitioned. 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. + * @param result_true {@link Iterator Output iterator} to the initial position of the range where the elements for + * which pred returns true are stored. + * @param result_false {@link Iterator Output iterator} to the initial position of the range where the elements for + * which pred returns false are stored. + * @param pred Unary function that accepts an element pointed by InputIterator as argument, and returns a value + * convertible to bool. The value returned indicates on which result range the element is + * copied. The function shall not modify its argument. + * + * @return A {@link Pair} of iterators with the end of the generated sequences pointed by result_true and + * result_false, respectivelly. Its member {@link Pair.first first} points to the element that follows + * the last element copied to the sequence of elements for which pred returned true. Its + * member {@link Pair.second second} points to the element that follows the last element copied to the sequence + * of elements for which pred returned false. + */ + function partition_copy, OutputIterator1 extends base.ILinearIterator, OutputIterator2 extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result_true: OutputIterator1, result_false: OutputIterator2, pred: (val: T) => T): Pair; + /** + * Get partition point. + * + * Returns an iterator to the first element in the partitioned range [first, last) for which + * pred is not true, indicating its partition point. + * + * The elements in the range shall already {@link is_partitioned be partitioned}, as if {@link partition} had been + * called with the same arguments. + * + * The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted + * range, which is specially efficient for {@link Iteartor random-access iterators}. + * + * @param first {@link Iterator Forward iterator} to the initial position of the partitioned sequence. + * @param last {@link Iterator Forward iterator} to the final position of the partitioned sequence. The range checked + * is [first, last), which contains all the elements between first an last, + * including the element pointed by first but not the element pointed by last. + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element goes before the partition point (if + * true, it goes before; if false goes at or after it). The function shall not + * modify its argument. + * + * @return An iterator to the first element in the partitioned range [first, last) for which pred + * is not true, or last if it is not true for any element. + */ + function partition_point>(first: ForwardIterator, last: ForwardIterator, pred: (x: T) => boolean): ForwardIterator; +} +declare namespace std { + /** + * Merge sorted ranges. + * + * Combines the elements in the sorted ranges [first1, last1) and [first2, last2), into + * a new range beginning at result with all its elements sorted. + * + * The elements are compared using {@link less}. The elements in both ranges shall already be ordered according to + * this same criterion ({@link less}). The resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting combined + * range is stored. Its size is equal to the sum of both ranges above. + * + * @return An iterator pointing to the past-the-end element in the resulting sequence. + */ + function merge, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; + /** + * Merge sorted ranges. + * + * Combines the elements in the sorted ranges [first1, last1) and [first2, last2), into + * a new range beginning at result with all its elements sorted. + * + * The elements are compared using {@link less}. The elements in both ranges shall already be ordered according to + * this same criterion (compare). The resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting combined + * range is stored. Its size is equal to the sum of both ranges above. + * @param compare Binary function that accepts two arguments of the types pointed by the iterators, and returns a value + * convertible to bool. The value returned indicates whether the first argument is + * considered to go before the second in the specific strict weak ordering it defines. The + * function shall not modify any of its arguments. + * + * @return An iterator pointing to the past-the-end element in the resulting sequence. + */ + function merge, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; + /** + * Merge consecutive sorted ranges. + * + * Merges two consecutive sorted ranges: [first, middle) and [middle, last), putting + * the result into the combined sorted range [first, last). + * + * The elements are compared using {@link less}. The elements in both ranges shall already be ordered according to + * this same criterion ({@link less}). The resulting range is also sorted according to this. + * + * The function preserves the relative order of elements with equivalent values, with the elements in the first + * range preceding those equivalent in the second. + * + * @param first {@link Iterator Bidirectional iterator} to the initial position in the first sorted sequence to merge. + * This is also the initial position where the resulting merged range is stored. + * @param middle {@link Iterator Bidirectional iterator} to the initial position of the second sorted sequence, which + * because both sequences must be consecutive, matches the past-the-end position of the first + * sequence. + * @param last {@link Iterator Bidirectional iterator} to the past-the-end position of the second sorted + * sequence. This is also the past-the-end position of the range where the resulting merged range is + * stored. + */ + function inplace_merge>(first: BidirectionalIterator, middle: BidirectionalIterator, last: BidirectionalIterator): void; + /** + * Merge consecutive sorted ranges. + * + * Merges two consecutive sorted ranges: [first, middle) and [middle, last), putting + * the result into the combined sorted range [first, last). + * + * The elements are compared using compare. The elements in both ranges shall already be ordered according + * to this same criterion (compare). The resulting range is also sorted according to this. + * + * The function preserves the relative order of elements with equivalent values, with the elements in the first + * range preceding those equivalent in the second. + * + * @param first {@link Iterator Bidirectional iterator} to the initial position in the first sorted sequence to merge. + * This is also the initial position where the resulting merged range is stored. + * @param middle {@link Iterator Bidirectional iterator} to the initial position of the second sorted sequence, which + * because both sequences must be consecutive, matches the past-the-end position of the first + * sequence. + * @param last {@link Iterator Bidirectional iterator} to the past-the-end position of the second sorted + * sequence. This is also the past-the-end position of the range where the resulting merged range is + * stored. + * @param compare Binary function that accepts two arguments of the types pointed by the iterators, and returns a value + * convertible to bool. The value returned indicates whether the first argument is + * considered to go before the second in the specific strict weak ordering it defines. The + * function shall not modify any of its arguments. + */ + function inplace_merge>(first: BidirectionalIterator, middle: BidirectionalIterator, last: BidirectionalIterator, compare: (x: T, y: T) => boolean): void; + /** + * Test whether sorted range includes another sorted range. + * + * Returns true if the sorted range [first1, last1) contains all the elements in the + * sorted range [first2, last2). + * + * The elements are compared using {@link less}. Two elements, x and y are considered equivalent + * if (!less(x, y) && !less(y, x)). + * + * The elements in the range shall already be ordered according to this same criterion ({@link less}). + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence (which is tested on + * whether it contains the second sequence). The range used is [first1, last1), which + * contains all the elements between first1 and last1, including the element pointed by + * first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. (which is tested + * on whether it is contained in the first sequence). The range used is [first2, last2). + * + * @return true if every element in the range [first2, last2) is contained in the range + * [first1, last1), false otherwise. If [first2, last2) is an empty + * range, the function returns true. + */ + function includes, InputIterator2 extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2): boolean; + /** + * Test whether sorted range includes another sorted range. + * + * Returns true if the sorted range [first1, last1) contains all the elements in the + * sorted range [first2, last2). + * + * The elements are compared using compare. Two elements, x and y are considered equivalent + * if (!compare(x, y) && !compare(y, x)). + * + * The elements in the range shall already be ordered according to this same criterion (compare). + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence (which is tested on + * whether it contains the second sequence). The range used is [first1, last1), which + * contains all the elements between first1 and last1, including the element pointed by + * first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. (which is tested + * on whether it is contained in the first sequence). The range used is [first2, last2). + * @param compare Binary function that accepts two elements as arguments (one from each of the two sequences, in the + * same order), and returns a value convertible to bool. The value returned indicates + * whether the element passed as first argument is considered to go before the second in the specific + * strict weak ordering it defines. The function shall not modify any of its arguments. + * + * @return true if every element in the range [first2, last2) is contained in the range + * [first1, last1), false otherwise. If [first2, last2) is an empty + * range, the function returns true. + */ + function includes, InputIterator2 extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, compare: (x: T, y: T) => boolean): boolean; + /** + * Union of two sorted ranges. + * + * Constructs a sorted range beginning in the location pointed by result with the set union of the + * two sorted ranges [first1, last1) and [first2, last2). + * + * The union of two sets is formed by the elements that are present in either one of the sets, or in both. + * Elements from the second range that have an equivalent element in the first range are not copied to the resulting + * range. + * + * The elements are compared using {@link less}. Two elements, x and y are considered equivalent + * if (!less(x, y) && !less(y, x)). + * + * The elements in the ranges shall already be ordered according to this same criterion ({@link less}). The + * resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element from the other ranges. + * + * @return An iterator to the end of the constructed range. + */ + function set_union, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; + /** + * Union of two sorted ranges. + * + * Constructs a sorted range beginning in the location pointed by result with the set union of the + * two sorted ranges [first1, last1) and [first2, last2). + * + * The union of two sets is formed by the elements that are present in either one of the sets, or in both. + * Elements from the second range that have an equivalent element in the first range are not copied to the resulting + * range. + * + * The elements are compared using compare. Two elements, x and y are considered equivalent + * if (!compare(x, y) && !compare(y, x)). + * + * The elements in the ranges shall already be ordered according to this same criterion (compare). The + * resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element from the other ranges. + * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a + * value convertible to bool. The value returned indicates whether the first argument is + * considered to go before the second in the specific strict weak ordering it defines. The + * function shall not modify any of its arguments. + * + * @return An iterator to the end of the constructed range. + */ + function set_union, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; + /** + * Intersection of two sorted ranges. + * + * Constructs a sorted range beginning in the location pointed by result with the set intersection of + * the two sorted ranges [first1, last1) and [first2, last2). + * + * The intersection of two sets is formed only by the elements that are present in both sets. The elements + * copied by the function come always from the first range, in the same order. + * + * The elements are compared using {@link less}. Two elements, x and y are considered equivalent + * if (!less(x, y) && !less(y, x)). + * + * The elements in the ranges shall already be ordered according to this same criterion ({@link less}). The + * resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element from the first range. + * + * @return An iterator to the end of the constructed range. + */ + function set_intersection, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; + /** + * Intersection of two sorted ranges. + * + * Constructs a sorted range beginning in the location pointed by result with the set intersection of + * the two sorted ranges [first1, last1) and [first2, last2). + * + * The intersection of two sets is formed only by the elements that are present in both sets. The elements + * copied by the function come always from the first range, in the same order. + * + * The elements are compared using compare. Two elements, x and y are considered equivalent + * if (!compare(x, y) && !compare(y, x)). + * + * The elements in the ranges shall already be ordered according to this same criterion (compare). The + * resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element from the first range. + * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a + * value convertible to bool. The value returned indicates whether the first argument is + * considered to go before the second in the specific strict weak ordering it defines. The + * function shall not modify any of its arguments. + * + * @return An iterator to the end of the constructed range. + */ + function set_intersection, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; + /** + * Difference of two sorted ranges. + * + * Constructs a sorted range beginning in the location pointed by result with the set difference of + * the sorted range [first1, last1) with respect to the sorted range [first2, last2). + * + * The difference of two sets is formed by the elements that are present in the first set, but not in the + * second one. The elements copied by the function come always from the first range, in the same order. + * + * For containers supporting multiple occurrences of a value, the difference includes as many occurrences of + * a given value as in the first range, minus the amount of matching elements in the second, preserving order. + * + * Notice that this is a directional operation - for a symmetrical equivalent, see {@link set_symmetric_difference}. + * + * The elements are compared using {@link less}. Two elements, x and y are considered equivalent + * if (!less(x, y) && !less(y, x)). + * + * The elements in the ranges shall already be ordered according to this same criterion ({@link less}). The + * resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element from the first range. + * + * @return An iterator to the end of the constructed range. + */ + function set_difference, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; + /** + * Difference of two sorted ranges. + * + * Constructs a sorted range beginning in the location pointed by result with the set difference of + * the sorted range [first1, last1) with respect to the sorted range [first2, last2). + * + * The difference of two sets is formed by the elements that are present in the first set, but not in the + * second one. The elements copied by the function come always from the first range, in the same order. + * + * For containers supporting multiple occurrences of a value, the difference includes as many occurrences of + * a given value as in the first range, minus the amount of matching elements in the second, preserving order. + * + * Notice that this is a directional operation - for a symmetrical equivalent, see {@link set_symmetric_difference}. + * + * The elements are compared using compare. Two elements, x and y are considered equivalent + * if (!compare(x, y) && !compare(y, x)). + * + * The elements in the ranges shall already be ordered according to this same criterion (compare). The + * resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element from the first range. + * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a + * value convertible to bool. The value returned indicates whether the first argument is + * considered to go before the second in the specific strict weak ordering it defines. The + * function shall not modify any of its arguments. + * + * @return An iterator to the end of the constructed range. + */ + function set_difference, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; + /** + * Symmetric difference of two sorted ranges. + * + * Constructs a sorted range beginning in the location pointed by0 result with the set + * symmetric difference of the two sorted ranges [first1, last1) and [first2, last2). + * + * The symmetric difference of two sets is formed by the elements that are present in one of the sets, but + * not in the other. Among the equivalent elements in each range, those discarded are those that appear before in the + * existent order before the call. The existing order is also preserved for the copied elements. + * + * The elements are compared using {@link less}. Two elements, x and y are considered equivalent + * if (!less(x, y) && !less(y, x)). + * + * The elements in the ranges shall already be ordered according to this same criterion ({@link less}). The + * resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element from the other ranges. + * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a + * value convertible to bool. The value returned indicates whether the first argument is + * considered to go before the second in the specific strict weak ordering it defines. The + * function shall not modify any of its arguments. + * + * @return An iterator to the end of the constructed range. + */ + function set_symmetric_difference, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; + /** + * Symmetric difference of two sorted ranges. + * + * Constructs a sorted range beginning in the location pointed by0 result with the set + * symmetric difference of the two sorted ranges [first1, last1) and [first2, last2). + * + * The symmetric difference of two sets is formed by the elements that are present in one of the sets, but + * not in the other. Among the equivalent elements in each range, those discarded are those that appear before in the + * existent order before the call. The existing order is also preserved for the copied elements. + * + * The elements are compared using compare. Two elements, x and y are considered equivalent + * if (!compare(x, y) && !compare(y, x)). + * + * The elements in the ranges shall already be ordered according to this same criterion (compare). The + * resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element from the other ranges. + * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a + * value convertible to bool. The value returned indicates whether the first argument is + * considered to go before the second in the specific strict weak ordering it defines. The + * function shall not modify any of its arguments. + * + * @return An iterator to the end of the constructed range. + */ + function set_symmetric_difference, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; +} +declare namespace std { + /** + * Return the smallest. + * + * Returns the smallest of all the elements in the args. + * + * @param args Values to compare. + * + * @return The lesser of the values passed as arguments. + */ + function min(...args: T[]): T; + /** + * Return the largest. + * + * Returns the largest of all the elements in the args. + * + * @param args Values to compare. + * + * @return The largest of the values passed as arguments. + */ + function max(...args: T[]): T; + /** + * Return smallest and largest elements. + * + * Returns a {@link Pair} with the smallest of all the elements in the args as first element (the first of + * them, if there are more than one), and the largest as second (the last of them, if there are more than one). + * + * @param args Values to compare. + * + * @return The lesser and greatest of the values passed as arguments. + */ + function minmax(...args: T[]): Pair; + /** + * Return smallest element in range. + * + * Returns an iterator pointing to the element with the smallest value in the range [first, last). + * + * The comparisons are performed using either {@link less}; An element is the smallest if no other element + * compares less than it. If more than one element fulfills this condition, the iterator returned points to the first + * of such elements. + * + * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. + * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. 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. + * + * @return An iterator to smallest value in the range, or last if the range is empty. + */ + function min_element>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; + /** + * Return smallest element in range. + * + * Returns an iterator pointing to the element with the smallest value in the range [first, last). + * + * The comparisons are performed using either compare; An element is the smallest if no other element + * compares less than it. If more than one element fulfills this condition, the iterator returned points to the first + * of such elements. + * + * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. + * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. 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. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible + * to bool. The value returned indicates whether the element passed as first argument is + * considered less than the second. The function shall not modify any of its arguments. + * + * @return An iterator to smallest value in the range, or last if the range is empty. + */ + function min_element>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): ForwardIterator; + /** + * Return largest element in range. + * + * Returns an iterator pointing to the element with the largest value in the range [first, last). + * + * The comparisons are performed using either {@link greater}; An element is the largest if no other element + * compares less than it. If more than one element fulfills this condition, the iterator returned points to the first + * of such elements. + * + * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. + * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. 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. + * + * @return An iterator to largest value in the range, or last if the range is empty. + */ + function max_element>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; + /** + * Return largest element in range. + * + * Returns an iterator pointing to the element with the largest value in the range [first, last). + * + * The comparisons are performed using either compare; An element is the largest if no other element + * compares less than it. If more than one element fulfills this condition, the iterator returned points to the first + * of such elements. + * + * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. + * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. 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. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible + * to bool. The value returned indicates whether the element passed as first argument is + * considered less than the second. The function shall not modify any of its arguments. + * + * @return An iterator to largest value in the range, or last if the range is empty. + */ + function max_element>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): ForwardIterator; + /** + * Return smallest and largest elements in range. + * + * Returns a {@link Pair} with an iterator pointing to the element with the smallest value in the range + * [first, last) as first element, and the largest as second. + * + * The comparisons are performed using either {@link less} and {@link greater}. + * + * If more than one equivalent element has the smallest value, the first iterator points to the first of such + * elements. + * + * If more than one equivalent element has the largest value, the second iterator points to the last of such + * elements. + * + * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. + * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. 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. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible + * to bool. The value returned indicates whether the element passed as first argument is + * considered less than the second. The function shall not modify any of its arguments. + * + * @return A {@link Pair} with an iterator pointing to the element with the smallest value in the range + * [first, last) as first element, and the largest as second. + */ + function minmax_element>(first: ForwardIterator, last: ForwardIterator): Pair; + /** + * Return smallest and largest elements in range. + * + * Returns a {@link Pair} with an iterator pointing to the element with the smallest value in the range + * [first, last) as first element, and the largest as second. + * + * The comparisons are performed using either compare. + * + * If more than one equivalent element has the smallest value, the first iterator points to the first of such + * elements. + * + * If more than one equivalent element has the largest value, the second iterator points to the last of such + * elements. + * + * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. + * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. 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. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible + * to bool. The value returned indicates whether the element passed as first argument is + * considered less than the second. The function shall not modify any of its arguments. + * + * @return A {@link Pair} with an iterator pointing to the element with the smallest value in the range + * [first, last) as first element, and the largest as second. + */ + function minmax_element>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): Pair; + /** + * Clamp a value between a pair of boundary. + * + * @param v The value to clamp. + * @param lo Start of the boundaries to clamp *v* to. + * @param hi Terminal of the boundaries to clamp *v* to. + * + * @return *lo* if *v* is less than *lo*, *hi* if *hi* is less than *v*, otherwise *v*. + */ + function clamp(v: T, lo: T, hi: T): T; + /** + * Clamp a value between a pair of boundary. + * + * @param v The value to clamp. + * @param lo Start of the boundaries to clamp *v* to. + * @param hi Terminal of the boundaries to clamp *v* to. + * @param comp Binary function that accepts two elements as arguments (one of each of the two sequences, in the + * same order), and returns a value convertible to bool. The value returned indicates + * whether the elements are considered to match in the context of this function. + * + * @return *lo* if *v* is less than *lo*, *hi* if *hi* is less than *v*, otherwise *v*. + */ + function clamp(v: T, lo: T, hi: T, comp: (x: T, y: T) => boolean): T; + /** + * Test whether range is permutation of another. + * + * Compares the elements in the range [first1, last1) with those in the range beginning at + * first2, and returns true if all of the elements in both ranges match, even in a different + * order. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to + * as many elements of this sequence as those in the range [first1, last1). + * + * @return true if all the elements in the range [first1, last1) compare equal to those + * of the range starting at first2 in any order, and false otherwise. + */ + function is_permutation, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2): boolean; + /** + * Test whether range is permutation of another. + * + * Compares the elements in the range [first1, last1) with those in the range beginning at + * first2, and returns true if all of the elements in both ranges match, even in a different + * order. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to + * as many elements of this sequence as those in the range [first1, last1). + * @param pred Binary function that accepts two elements as argument (one of each of the two sequences, in the same + * order), and returns a value convertible to bool. The value returned indicates whether + * the elements are considered to match in the context of this function. + * + * @return true if all the elements in the range [first1, last1) compare equal to those + * of the range starting at first2 in any order, and false otherwise. + */ + function is_permutation, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, pred: (x: T, y: T) => boolean): boolean; + /** + * Transform range to previous permutation. + * + * Rearranges the elements in the range [*first*, *last*) into the previous *lexicographically-ordered* permutation. + * + * A *permutation* is each one of the N! possible arrangements the elements can take (where *N* is the number of + * elements in the range). Different permutations can be ordered according to how they compare + * {@link lexicographicaly lexicographical_compare} to each other; The first such-sorted possible permutation (the one + * that would compare *lexicographically smaller* to all other permutations) is the one which has all its elements + * sorted in ascending order, and the largest has all its elements sorted in descending order. + * + * The comparisons of individual elements are performed using the {@link less less()} function. + * + * If the function can determine the previous permutation, it rearranges the elements as such and returns true. If + * that was not possible (because it is already at the lowest possible permutation), it rearranges the elements + * according to the last permutation (sorted in descending order) and returns false. + * + * @param first Bidirectional iterators to the initial positions of the sequence + * @param last Bidirectional iterators to the final positions of the sequence. 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*. + * + * @return true if the function could rearrange the object as a lexicographicaly smaller permutation. Otherwise, the + * function returns false to indicate that the arrangement is not less than the previous, but the largest + * possible (sorted in descending order). + */ + function prev_permutation>(first: BidirectionalIterator, last: BidirectionalIterator): boolean; + /** + * Transform range to previous permutation. + * + * Rearranges the elements in the range [*first*, *last*) into the previous *lexicographically-ordered* permutation. + * + * A *permutation* is each one of the N! possible arrangements the elements can take (where *N* is the number of + * elements in the range). Different permutations can be ordered according to how they compare + * {@link lexicographicaly lexicographical_compare} to each other; The first such-sorted possible permutation (the one + * that would compare *lexicographically smaller* to all other permutations) is the one which has all its elements + * sorted in ascending order, and the largest has all its elements sorted in descending order. + * + * The comparisons of individual elements are performed using the *compare*. + * + * If the function can determine the previous permutation, it rearranges the elements as such and returns true. If + * that was not possible (because it is already at the lowest possible permutation), it rearranges the elements + * according to the last permutation (sorted in descending order) and returns false. + * + * @param first Bidirectional iterators to the initial positions of the sequence + * @param last Bidirectional iterators to the final positions of the sequence. 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*. + * @param compare Binary function that accepts two arguments of the type pointed by BidirectionalIterator, and returns + * a value convertible to bool. The value returned indicates whether the first argument is considered + * to go before the second in the specific strict weak ordering it defines. + * + * @return true if the function could rearrange the object as a lexicographicaly smaller permutation. Otherwise, the + * function returns false to indicate that the arrangement is not less than the previous, but the largest + * possible (sorted in descending order). + */ + function prev_permutation>(first: BidirectionalIterator, last: BidirectionalIterator, compare: (x: T, y: T) => boolean): boolean; + /** + * Transform range to next permutation. + * + * Rearranges the elements in the range [*first*, *last*) into the next *lexicographically greater* permutation. + * + * A permutation is each one of the *N!* possible arrangements the elements can take (where *N* is the number of + * elements in the range). Different permutations can be ordered according to how they compare + * {@link lexicographicaly lexicographical_compare} to each other; The first such-sorted possible permutation (the one + * that would compare *lexicographically smaller* to all other permutations) is the one which has all its elements + * sorted in ascending order, and the largest has all its elements sorted in descending order. + * + * The comparisons of individual elements are performed using the {@link less} function. + * + * If the function can determine the next higher permutation, it rearranges the elements as such and returns true. If + * that was not possible (because it is already at the largest possible permutation), it rearranges the elements + * according to the first permutation (sorted in ascending order) and returns false. + * + * @param first Bidirectional iterators to the initial positions of the sequence + * @param last Bidirectional iterators to the final positions of the sequence. 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*. + * + * @return true if the function could rearrange the object as a lexicographicaly greater permutation. Otherwise, the + * function returns false to indicate that the arrangement is not greater than the previous, but the lowest + * possible (sorted in ascending order). + */ + function next_permutation>(first: BidirectionalIterator, last: BidirectionalIterator): boolean; + /** + * Transform range to next permutation. + * + * Rearranges the elements in the range [*first*, *last*) into the next *lexicographically greater* permutation. + * + * A permutation is each one of the *N!* possible arrangements the elements can take (where *N* is the number of + * elements in the range). Different permutations can be ordered according to how they compare + * {@link lexicographicaly lexicographical_compare} to each other; The first such-sorted possible permutation (the one + * that would compare *lexicographically smaller* to all other permutations) is the one which has all its elements + * sorted in ascending order, and the largest has all its elements sorted in descending order. + * + * The comparisons of individual elements are performed using the *compare*. + * + * If the function can determine the next higher permutation, it rearranges the elements as such and returns true. If + * that was not possible (because it is already at the largest possible permutation), it rearranges the elements + * according to the first permutation (sorted in ascending order) and returns false. + * + * @param first Bidirectional iterators to the initial positions of the sequence + * @param last Bidirectional iterators to the final positions of the sequence. 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*. + * @param compare Binary function that accepts two arguments of the type pointed by BidirectionalIterator, and returns + * a value convertible to bool. The value returned indicates whether the first argument is considered + * to go before the second in the specific strict weak ordering it defines. + * + * @return true if the function could rearrange the object as a lexicographicaly greater permutation. Otherwise, the + * function returns false to indicate that the arrangement is not greater than the previous, but the lowest + * possible (sorted in ascending order). + */ + function next_permutation>(first: BidirectionalIterator, last: BidirectionalIterator, compare: (x: T, y: T) => boolean): boolean; +} +declare namespace std.base { + /** + * An abstract container. + * + * + * + * + * + * ### Container properties + *
    + *
    Sequence
    + *
    Elements in sequence containers are ordered in a strict linear sequence. Individual elements are + * accessed by their position in this sequence.
    + * + *
    Doubly-linked list
    + *
    Each element keeps information on how to locate the next and the previous elements, allowing + * constant time insert and erase operations before or after a specific element (even of entire ranges), + * but no direct random access.
    + *
    + * + * @param Type of elements. + * + * @author Jeongho Nam + */ + abstract class Container { + /** + * Default Constructor. + */ + protected constructor(); + /** + * Assign new content to content. + * + * Assigns new contents to the container, replacing its current contents, and modifying its + * {@link size} accordingly. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + */ + abstract assign>(begin: InputIterator, end: InputIterator): void; + /** + * Clear content. + * + * Removes all elements from the Container, leaving the container with a size of 0. + */ + clear(): void; + /** + * Return iterator to beginning. + * + * Returns an iterator referring the first element in the + * + * #### Note + * If the container is {@link empty}, the returned iterator is same with {@link end end()}. + * + * @return An iterator to the first element in the The iterator containes the first element's value. + */ + abstract begin(): Iterator; + /** + * Return iterator to end. + * Returns an iterator referring to the past-the-end element in the + * + * The past-the-end element is the theoretical element that would follow the last element in the + * It does not point to any element, and thus shall not be dereferenced. + * + * Because the ranges used by functions of the Container do not include the element reference by their + * closing iterator, this function is often used in combination with {@link Container}.{@link begin} to + * specify a range including all the elements in the container. + * + * #### Note + * Returned iterator from {@link Container}.{@link end} does not refer any element. Trying to accessing + * element by the iterator will cause throwing exception ({@link OutOfRange}). + * + * If the container is {@link empty}, this function returns the same as {@link Container}.{@link begin}. + * + * + * @return An iterator to the end element in the + */ + abstract end(): Iterator; + /** + * Return {@link ReverseIterator reverse iterator} to reverse beginning. + * + * Returns a {@link ReverseIterator reverse iterator} pointing to the last element in the container (i.e., + * its reverse beginning). + * + * {@link ReverseIterator reverse iterators} iterate backwards: increasing them moves them towards the + * beginning of the + * + * {@link rbegin} points to the element right before the one that would be pointed to by member {@link end}. + * + * + * @return A {@link ReverseIterator reverse iterator} to the reverse beginning of the sequence + */ + abstract rbegin(): IReverseIterator; + /** + * Return {@link ReverseIterator reverse iterator} to reverse end. + * + * Returns a {@link ReverseIterator reverse iterator} pointing to the theoretical element preceding the + * first element in the container (which is considered its reverse end). + * + * The range between {@link Container}.{@link rbegin} and {@link Container}.{@link rend} contains all + * the elements of the container (in reverse order). + * + * @return A {@link ReverseIterator reverse iterator} to the reverse end of the sequence + */ + abstract rend(): IReverseIterator; + /** + * Return the number of elements in the {@link Container}. + * + * @return The number of elements in the container. + */ + abstract size(): number; + /** + * Test whether the container is empty. + * Returns whether the container is empty (i.e. whether its size is 0). + * + * This function does not modify the container in any way. To clear the content of the container, + * see {@link clear clear()}. + * + * @return true if the container size is 0, false otherwise. + */ + empty(): boolean; + /** + * Insert elements. + * + * Appends new elements to the container, and returns the new size of the + * + * @param items New elements to insert. + * + * @return New size of the Container. + */ + abstract push(...items: T[]): number; + /** + * Insert an element. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link Container.size container size} by the amount of + * elements inserted. + * + * @param position Position in the {@link Container} where the new element is inserted. + * {@link iterator} is a member type, defined as a {@link Iterator random access iterator} + * type that points to elements. + * @param val Value to be copied to the inserted element. + * + * @re + public abstract insert(position: Iterator, val: T): Iterator; + + /* --------------------------------------------------------- + ERASE + --------------------------------------------------------- */ + /** + * Erase an element. + * + * Removes from the container a single element. + * + * This effectively reduces the container size by the number of element removed. + * + * @param position Iterator pointing to a single element to be removed from the Container. + * + * @return An iterator pointing to the element that followed the last element erased by the function + * call. This is the {@link end Container.end} if the operation erased the last element in the + * sequence. + */ + abstract erase(position: Iterator): Iterator; + /** + * Erase elements. + * + * Removes from the container a range of elements. + * + * This effectively reduces the container size by the number of elements removed. + * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + * + * @return An iterator pointing to the element that followed the last element erased by the function + * call. This is the {@link end Container.end} if the operation erased the last element in + * the sequence. + */ + abstract erase(begin: Iterator, end: Iterator): Iterator; + /** + * Swap content. + * + * Exchanges the content of the container by the content of obj, which is another + * {@link Container 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 swap swap}, overloading that + * algorithm with an optimization that behaves like this member function. + * + * @param obj Another {@link Container 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 container}. + */ + swap(obj: Container): void; + } + interface IReverseIterator extends ReverseIterator, Iterator, IReverseIterator> { + } +} +declare namespace std { + /** + * Bi-directional iterator. + * + * {@link Iterator Bidirectional iterators} are iterators that can be used to access the sequence of elements + * in a range in both directions (towards the end and towards the beginning). + * + * All {@link IArrayIterator random-access iterators} are also valid {@link Iterrator bidirectional iterators}. + * + * There is not a single type of {@link Iterator bidirectional iterator}: {@link Container 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 + * @author Jeongho Nam + */ + abstract class Iterator { + /** + * @hidden + */ + protected source_: base.Container; + /** + * Construct from the source {@link Container container}. + * + * @param source The source container. + */ + protected constructor(source: base.Container); + /** + * Get iterator to previous element. + * + * If current iterator is the first item(equal with {@link Container.begin Container.begin()}), + * returns {@link Container.end Container.end()}. + * + * @return An iterator of the previous item. + */ + abstract prev(): Iterator; + /** + * Get iterator to next element. + * + * If current iterator is the last item, returns {@link Container.end Container.end()}. + * + * @return An iterator of the next item. + */ + abstract next(): Iterator; + /** + * Advances the {@link Iterator} by n element positions. + * + * @param n Number of element positions to advance. + * @return An advanced iterator. + */ + abstract advance(n: number): Iterator; + /** + * Get source container. + * + * Get source container of this iterator is directing for. + */ + abstract source(): base.Container; + /** + * Whether an iterator is equal with the iterator. + * + * Compare two iterators and returns whether they are equal or not. + * + * #### Note + * Iterator's {@link equals equals()} only compare souce container and index number. + * + * Although elements in a pair, key and value are {@link equal_to equal_to}, if the source map or + * index number is different, then the {@link equals equals()} will return false. If you want to + * compare the elements of a pair, compare them directly by yourself. + * + * @param obj An iterator to compare + * @return Indicates whether equal or not. + */ + equals(obj: Iterator): boolean; + /** + * Get value of the iterator is pointing. + * + * @return A value of the iterator. + */ + readonly abstract value: T; + abstract swap(obj: Iterator): void; + } +} +declare namespace std { + /** + * This class reverses the direction in which a bidirectional or random-access iterator iterates through a range. + * + * A copy of the original iterator (the {@link Iterator base iterator}) is kept internally and used to reflect + * the operations performed on the {@link ReverseIterator}: whenever the {@link ReverseIterator} is incremented, its + * {@link Iterator base iterator} is decreased, and vice versa. A copy of the {@link Iterator base iterator} with the + * current state can be obtained at any time by calling member {@link base}. + * + * Notice however that when an iterator is reversed, the reversed version does not point to the same element in + * the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a + * range: An iterator pointing to a past-the-end element in a range, when reversed, is pointing to the last element + * (not past it) of the range (this would be the first element of the reversed range). And if an iterator to the + * 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, Base extends Iterator, 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. + */ + protected constructor(base: Base); + /** + * @hidden + */ + protected abstract _Create_neighbor(base: Base): This; + source(): Source; + /** + * 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; + /** + * Get value of the iterator is pointing. + * + * @return A value of the reverse iterator. + */ + readonly value: T; + /** + * @inheritdoc + */ + prev(): This; + /** + * @inheritdoc + */ + next(): This; + /** + * @inheritdoc + */ + advance(n: number): This; + /** + * @inheritdoc + */ + equals(obj: This): boolean; + /** + * @inheritdoc + */ + swap(obj: This): void; + } + /** + * Return the number of elements in the {@link Container}. + * + * @param container A container with a size method. + * @return The number of elements in the container. + */ + function size(container: base.Container): number; + /** + * Test whether the container is empty. + * + * Returns whether the {@link Container} is empty (i.e. whether its {@link size} is 0). + * + * @param container A container with a empty method. + * @return true if the container size is 0, false otherwise. + */ + function empty(container: base.Container): boolean; + /** + * Return distance between {@link Iterator iterators}. + * + * Calculates the number of elements between first and last. + * + * If it is a {@link IArrayIterator random-access iterator}, the function uses operator- to calculate this. + * Otherwise, the function uses the increase operator {@link Iterator.next next()} repeatedly. + * + * @param first Iterator pointing to the initial element. + * @param last Iterator pointing to the final element. This must be reachable from first. + * + * @return The number of elements between first and last. + */ + function distance>(first: InputIterator, last: InputIterator): number; + /** + * Advance iterator. + * + * Advances the iterator it by n elements positions. + * + * @param it Iterator to be advanced. + * @param n Number of element positions to advance. + * + * @return An iterator to the element n positions before it. + */ + function advance>(it: InputIterator, n: number): InputIterator; + /** + * Get iterator to previous element. + * + * Returns an iterator pointing to the element that it would be pointing to if advanced -n positions. + * + * @param it Iterator to base position. + * @param n Number of element positions offset (1 by default). + * + * @return An iterator to the element n positions before it. + */ + function prev>(it: BidirectionalIterator, n?: number): BidirectionalIterator; + /** + * Get iterator to next element. + * + * Returns an iterator pointing to the element that it would be pointing to if advanced n positions. + * + * @param it Iterator to base position. + * @param n Number of element positions offset (1 by default). + * + * @return An iterator to the element n positions away from it. + */ + function next>(it: ForwardIterator, n?: number): ForwardIterator; + /** + * Iterator to beginning. + * + * Returns an iterator pointing to the first element in the sequence. + * + * If the sequence is {@link empty}, the returned value shall not be dereferenced. + * + * @param container A container object of a class type for which member {@link begin} is defined. + * @return The same as returned by {@link begin begin()}. + */ + function begin(container: base.Container): Iterator; + function begin(container: Vector): VectorIterator; + function begin(container: List): ListIterator; + function begin(container: Deque): DequeIterator; + function begin(container: base.SetContainer): SetIterator; + function begin(container: base.MapContainer): MapIterator; + /** + * Iterator to reverse-beginning. + * + * Returns a reverse iterator pointing to the last element in the sequence. + * + * If the sequence is {@link empty}, the returned value shall not be dereferenced. + * + * @param container A container object of a class type for which member {@link rbegin} is defined. + * @return The same as returned by {@link rbegin()}. + */ + function rbegin(container: base.Container): base.IReverseIterator; + function rbegin(container: Vector): VectorReverseIterator; + function rbegin(container: List): ListReverseIterator; + function rbegin(container: Deque): DequeReverseIterator; + function rbegin(container: base.SetContainer): SetReverseIterator; + function rbegin(container: base.MapContainer): MapReverseIterator; + /** + * Iterator to end. + * + * Returns an iterator pointing to the past-the-end element in the sequence. + * + * If the sequence is {@link empty}, the returned value compares equal to the one returned by {@link begin} with the same argument. + * + * @param container A container of a class type for which member {@link end} is defined. + * @return The same as returned by {@link end end()}. + */ + function end(container: base.Container): Iterator; + function end(container: Vector): VectorIterator; + function end(container: List): ListIterator; + function end(container: Deque): DequeIterator; + function end(container: base.SetContainer): SetIterator; + function end(container: base.MapContainer): MapIterator; + /** + * Iterator to end. + * + * Returns an iterator pointing to the past-the-end element in the sequence. + * + * If the sequence is {@link empty}, the returned value compares equal to the one returned by {@link begin} with the same argument. + * + * @param container A container of a class type for which member {@link end} is defined. + * @return The same as returned by {@link end end()}. + */ + function rend(container: base.Container): base.IReverseIterator; + function rend(container: Vector): VectorReverseIterator; + function rend(container: List): ListReverseIterator; + function rend(container: Deque): DequeReverseIterator; + function rend(container: base.SetContainer): SetReverseIterator; + function rend(container: base.MapContainer): MapReverseIterator; + /** + * Make reverse iterator. + * + * @param it A reference of the base iterator, which iterates in the opposite direction. + * @return A {@link ReverseIterator reverse iterator} based on *it*. + */ + function make_reverse_iterator(it: VectorIterator): VectorReverseIterator; + function make_reverse_iterator(it: DequeIterator): DequeReverseIterator; + function make_reverse_iterator(it: ListIterator): ListReverseIterator; + function make_reverse_iterator(it: SetIterator): SetReverseIterator; + function make_reverse_iterator(it: MapIterator): MapReverseIterator; +} +declare namespace std.base { + /** + * @hidden + */ + abstract class _ListContainer> extends Container implements IDequeContainer { + /** + * @hidden + */ + private begin_; + /** + * @hidden + */ + private end_; + /** + * @hidden + */ + private size_; + /** + * Default Constructor. + */ + protected constructor(); + /** + * @hidden + */ + protected abstract _Create_iterator(prev: BidirectionalIterator, next: BidirectionalIterator, val: T): BidirectionalIterator; + /** + * @hidden + */ + protected _Set_begin(it: BidirectionalIterator): void; + /** + * @inheritdoc + */ + assign>(first: InputIterator, last: InputIterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + begin(): BidirectionalIterator; + /** + * @inheritdoc + */ + end(): BidirectionalIterator; + /** + * @inheritdoc + */ + size(): number; + /** + * @inheritdoc + */ + front(): T; + /** + * @inheritdoc + */ + back(): T; + /** + * @inheritdoc + */ + push_front(val: T): void; + /** + * @inheritdoc + */ + push_back(val: T): void; + /** + * @inheritdoc + */ + pop_front(): void; + /** + * @inheritdoc + */ + pop_back(): void; + /** + * @inheritdoc + */ + push(...items: T[]): number; + /** + * Insert an element. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new element is inserted. + * {@link iterator}> is a member type, defined as a + * {@link ListIterator bidirectional iterator} type that points to elements. + * @param val Value to be inserted as an element. + * + * @return An iterator that points to the newly inserted element; val. + */ + insert(position: BidirectionalIterator, val: T): BidirectionalIterator; + /** + * Insert elements by repeated filling. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new elements are inserted. The {@link iterator} is a + * member type, defined as a {@link ListIterator bidirectional iterator} type that points to + * elements. + * @param size Number of elements to insert. + * @param val Value to be inserted as an element. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert(position: BidirectionalIterator, size: number, val: T): BidirectionalIterator; + /** + * Insert elements by range iterators. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new elements are inserted. The {@link iterator} is a + * member type, defined as a {@link ListIterator bidirectional iterator} type that points to + * elements. + * @param begin An iterator specifying range of the begining element. + * @param end An iterator specifying range of the ending element. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert>(position: BidirectionalIterator, begin: InputIterator, end: InputIterator): BidirectionalIterator; + /** + * @hidden + */ + private _Insert_by_repeating_val(position, n, val); + /** + * @hidden + */ + protected _Insert_by_range>(position: BidirectionalIterator, begin: InputIterator, end: InputIterator): BidirectionalIterator; + /** + * Erase an element. + * + * Removes from the {@link List} either a single element; position. + * + * This effectively reduces the container size by the number of element removed. + * + * Unlike other standard sequence containers, {@link List} objects are specifically designed to be + * efficient inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Iterator pointing to a single element to be removed from the {@link List}. + * + * @return An iterator pointing to the element that followed the last element erased by the function call. + * This is the {@link end end()} if the operation erased the last element in the sequence. + */ + erase(position: BidirectionalIterator): BidirectionalIterator; + /** + * Erase elements. + * + * Removes from the {@link List} container a range of elements. + * + * This effectively reduces the container {@link size} by the number of elements removed. + * + * Unlike other standard sequence containers, {@link List} objects are specifically designed to be + * efficient inserting and removing elements in any position, even in the middle of the sequence. + * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + * + * @return An iterator pointing to the element that followed the last element erased by the function call. + * This is the {@link end end()} if the operation erased the last element in the sequence. + */ + erase(begin: BidirectionalIterator, end: BidirectionalIterator): BidirectionalIterator; + /** + * @hidden + */ + protected _Erase_by_range(first: BidirectionalIterator, last: BidirectionalIterator): BidirectionalIterator; + /** + * 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 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 List container}. + */ + swap(obj: _ListContainer): void; + /** + * @inheritdoc + */ + swap(obj: Container): void; + } +} +declare namespace std.base { + /** + * @hidden + */ + abstract class _ListIteratorBase extends Iterator { + /** + * @hidden + */ + protected prev_: _ListIteratorBase; + /** + * @hidden + */ + protected next_: _ListIteratorBase; + /** + * @hidden + */ + protected value_: T; + /** + * Initializer Constructor. + * + * @param source The source {@link Container} to reference. + * @param prev A refenrece of previous node ({@link ListIterator iterator}). + * @param next A refenrece of next node ({@link ListIterator iterator}). + * @param value Value to be stored in the node (iterator). + */ + protected constructor(source: Container, prev: _ListIteratorBase, next: _ListIteratorBase, value: T); + /** + * @inheritdoc + */ + prev(): _ListIteratorBase; + /** + * @inheritdoc + */ + next(): _ListIteratorBase; + /** + * @inheritdoc + */ + advance(step: number): _ListIteratorBase; + /** + * @inheritdoc + */ + readonly value: T; + /** + * @inheritdoc + */ + equals(obj: _ListIteratorBase): boolean; + /** + * @inheritdoc + */ + swap(obj: _ListIteratorBase): void; + } +} +declare namespace std.base { + /** + * An abstract error instance. + * + * {@link ErrorInstance} is an abstract class of {@link ErrorCode} and {@link ErrorCondition} + * holding an error instance's identifier {@link value}, associated with a {@link category}. + * + * The operating system and other low-level applications and libraries generate numerical error codes to + * represent possible results. These numerical values may carry essential information for a specific platform, + * but be non-portable from one platform to another. + * + * 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}. + * + * + * + * + * @author Jeongho Nam + */ + abstract class ErrorInstance { + /** + * @hidden + */ + protected category_: ErrorCategory; + /** + * @hidden + */ + protected value_: number; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from a numeric value and error category. + * + * @param val A numerical value identifying an error instance. + * @param category A reference to an {@link ErrorCategory} object. + */ + constructor(val: number, category: ErrorCategory); + /** + * Assign error instance. + * + * Assigns the {@link ErrorCode} object a value of val associated with the {@link ErrorCategory}. + * + * @param val A numerical value identifying an error instance. + * @param category A reference to an {@link ErrorCategory} object. + */ + assign(val: number, category: ErrorCategory): void; + /** + * Clear error instance. + * + * Clears the value in the {@link ErrorCode} object so that it is set to a value of 0 of the + * {@link ErrorCategory.systemCategory ErrorCategory.systemCategory()} (indicating no error). + */ + clear(): void; + /** + * Get category. + * + * Returns a reference to the {@link ErrorCategory} associated with the {@link ErrorCode} object. + * + * @return A reference to a non-copyable object of a type derived from {@link ErrorCategory}. + */ + category(): ErrorCategory; + /** + * Error value. + * + * Returns the error value associated with the {@link ErrorCode} object. + * + * @return The error value. + */ + value(): number; + /** + * Get message. + * + * Returns the message associated with the error instance. + * + * Error messages are defined by the {@link category} the error instance belongs to. + * + * This function returns the same as if the following member was called: + * + * category().message(value()) + * + * @return A string object with the message associated with the {@link ErrorCode}. + */ + message(): string; + /** + * Default error condition. + * + * Returns the default {@link ErrorCondition}object associated with the {@link ErrorCode} object. + * + * This function returns the same as if the following member was called: + * + * category().default_error_condition(value()) + * + * {@link ErrorCategory.default_error_condition ErrorCategory.default_error_condition()} + * is a virtual member function, that can operate differently for each category. + * + * @return An {@link ErrorCondition}object that corresponds to the {@link ErrorCode} object. + */ + default_error_condition(): ErrorCondition; + /** + * Convert to bool. + * + * Returns whether the error instance has a numerical {@link value} other than 0. + * + * If it is zero (which is generally used to represent no error), the function returns false, otherwise it returns true. + * + * @return true if the error's numerical value is not zero. + * false otherwise. + */ + to_bool(): boolean; + } +} +declare namespace std.base { + /** + * @hidden + */ + enum _Hash { + MIN_SIZE = 10, + RATIO = 1, + MAX_RATIO = 2, + } + /** + * @hidden + */ + abstract class _HashBuckets { + private buckets_; + private item_size_; + protected constructor(); + rehash(size: number): void; + clear(): void; + size(): number; + item_size(): number; + capacity(): number; + at(index: number): Vector; + hash_index(val: T): number; + insert(val: T): void; + erase(val: T): void; + } +} +declare namespace std.base { + /** + * @hidden + */ + class _MapHashBuckets extends _HashBuckets> { + private map_; + constructor(map: IHashMap); + find(key: K): MapIterator; + } +} +declare namespace std.base { + /** + * @hidden + */ + class _SetHashBuckets extends _HashBuckets> { + private set_; + constructor(set: IHashSet); + find(val: T): SetIterator; + } +} +declare namespace std.base { + /** + * Array Container. + * + * {@link IArrayContainer} is an interface for sequence containers representing arrays that can change in + * {@link size}. However, compared to arrays, {@link IArrayContainer} objectss consume more memory in exchange for + * the ability to manage storage and grow dynamically in an efficient way. + * + * Both {@link Vector Vectors} and {@link Deque Deques} who implemented {@link IArrayContainer} provide a very + * similar interface and can be used for similar purposes, but internally both work in quite different ways: + * While {@link Vector Vectors} use a single array that needs to be occasionally reallocated for growth, the + * elements of a {@link Deque} can be scattered in different chunks of storage, with the container keeping the + * necessary information internally to provide direct access to any of its elements in constant time and with a + * uniform sequential interface (through iterators). Therefore, {@link Deque Deques} are a little more complex + * internally than {@link Vector Vectors}, but this allows them to grow more efficiently under certain + * circumstances, especially with very long sequences, where reallocations become more expensive. + * + * Both {@link Vector Vectors} and {@link Deque Deques} provide a very similar interface and can be used for + * similar purposes, but internally both work in quite different ways: While {@link Vector Vectors} use a single + * array that needs to be occasionally reallocated for growth, the elements of a {@link Deque} can be scattered + * in different chunks of storage, with the container keeping the necessary information internally to provide + * direct access to any of its elements in constant time and with a uniform sequential interface (through + * iterators). Therefore, {@link Deque Deques} are a little more complex internally than {@link Vector Vectors}, + * but this allows them to grow more efficiently under certain circumstances, especially with very long + * sequences, where reallocations become more expensive. + * + * For operations that involve frequent insertion or removals of elements at positions other than the + * beginning or the end, {@link IArrayContainer} objects perform worse and have less consistent iterators and references + * than {@link List Lists}. + * + * + * + * + * + * ### Container properties + *
    + *
    Sequence
    + *
    + * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are + * accessed by their position in this sequence. + *
    + * + *
    Dynamic array
    + *
    + * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides + * relatively fast addition/removal of elements at the end of the sequence. + *
    + *
    + * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + interface IArrayContainer extends ILinearContainer { + /** + * Access element. + * Returns a value to the element at position index in the {@link IArrayContainer container}.

    + * + * The function automatically checks whether index is within the bounds of valid elements + * in the {@link IArrayContainer container}, throwing an {@link OutOfRange} exception if it is not (i.e., + * if index is greater or equal than its {@link size}). + * + * @param index Position of an element in the + * If this is greater than or equal to the {@link IArrayContainer container} {@link size}, an + * exception of type {@link OutOfRange} is thrown. Notice that the first + * element has a position of 0 (not 1). + * + * @return The element at the specified position in the + */ + at(index: number): T; + /** + * Modify element. + * Replaces an element at the specified position (index) in this {@link IArrayContainer container} + * with the specified element (val). + * + * The function automatically checks whether index is within the bounds of valid elements + * in the {@link IArrayContainer container}, throwing an {@link OutOfRange} exception if it is not (i.e., if + * index is greater or equal than its {@link size}). + * + * @.param index A specified position of the value to replace. + * @param val A value to be stored at the specified position. + * + * @return The previous element had stored at the specified position. + */ + set(index: number, val: T): void; + } + /** + * Random-access iterator. + * + * {@link IArrayIterator Random-access iterators} are iterators that can be used to access elements at an + * arbitrary offset position relative to the element they point to, offering the same functionality as pointers. + * + * {@link IArrayIterator Random-access iterators} are the most complete iterators in terms of functionality. + * All pointer types are also valid {@link IArrayIterator random-access iterators}. + * + * 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 + * @author Jeongho Nam + */ + interface IArrayIterator extends ILinearIterator { + /** + * @inheritdoc + */ + source(): IArrayContainer; + /** + * Get index, sequence number of the iterator in the source {@link IArrayContainer array}. + * + * @return Sequence number of the iterator in the source {@link IArrayContainer array}. + */ + index(): number; + /** + * @inheritdoc + */ + prev(): IArrayIterator; + /** + * @inheritdoc + */ + next(): IArrayIterator; + } +} +declare namespace std.base { + /** + * An interface for deque + * + * + * + * + * + * @author Jeongho Nam + */ + interface IDequeContainer extends ILinearContainer { + /** + * Insert element at beginning. + * + * Inserts a new element at the beginning of the {@link IDeque container}, right before its + * current first element. This effectively increases the {@link IDeque container} {@link size} by + * one. + * + * @param val Value to be inserted as an element. + */ + push_front(val: T): void; + /** + * Delete first element. + * + * Removes the first element in the {@link IDeque container}, effectively reducing its + * {@link size} by one. + */ + pop_front(): void; + } +} +declare namespace std.base { + /** + * Common interface for hash map. + * + * {@link IHashMap}s are associative containers that store elements formed by the combination of + * a key value and a mapped value. + * + * In an {@link IHashMap}, 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 IHashMap} 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). + * + * 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 + *
    + *
    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.
    + * + *
    Map
    + *
    Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value.
    + *
    + * + * @param Type of the key values. + * Each element in an {@link IHashMap} is identified by a key value. + * @param Type of the mapped value. + * Each element in an {@link IHashMap} is used to store some data as its mapped value. + * + * @reference http://www.cplusplus.com/reference/unordered_map + * @author Jeongho Nam + */ + interface IHashMap extends MapContainer { + /** + * Return number of buckets. + * + * Returns the number of buckets in the {@link IHashMap} container. + * + * A bucket is a slot in the container's internal hash table to which elements are assigned based on the + * hash value of their key. + * + * The number of buckets influences directly the {@link load_factor load factor} of the container's hash + * table (and thus the probability of collision). The container automatically increases the number of buckets to + * keep the load factor below a specific threshold (its {@link max_load_factor}), causing a {@link rehash} each + * time the number of buckets needs to be increased. + * + * @return The current amount of buckets. + */ + bucket_count(): number; + /** + * Return bucket size. + * + * Returns the number of elements in bucket n. + * + * A bucket is a slot in the container's internal hash table to which elements are assigned based on the hash + * value of their key. + * + * The number of elements in a bucket influences the time it takes to access a particular element in the + * bucket. The container automatically increases the number of buckets to keep the {@link load_cator load factor} + * (which is the average bucket size) below its {@link max_load_factor}. + * + * @param n Bucket number. This shall be lower than {@link bucket_count}. + * + * @return The number of elements in bucket n. + */ + bucket_size(n: number): number; + /** + * Get maximum load factor. + * + * Returns the current maximum load factor for the {@link HashMultiMap} container. + * + * The load factor is the ratio between the number of elements in the container (its {@link size}) and the + * number of buckets ({@link bucket_count}). + * + * By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0. + * + * The load factor influences the probability of collision in the hash table (i.e., the probability of two + * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold + * that forces an increase in the number of buckets (and thus causing a {@link rehash}). + * + * Note though, that implementations may impose an upper limit on the number of buckets (see + * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}. + * + * @return The current load factor. + */ + max_load_factor(): number; + /** + * Set maximum load factor. + * + * Sets z as the cnew maximum load factor for the {@link HashMultiMap} container. + * + * The load factor is the ratio between the number of elements in the container (its {@link size}) and the + * number of buckets ({@link bucket_count}). + * + * By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0. + * + * The load factor influences the probability of collision in the hash table (i.e., the probability of two + * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold + * that forces an increase in the number of buckets (and thus causing a {@link rehash}). + * + * Note though, that implementations may impose an upper limit on the number of buckets (see + * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}. + * + * @param z The new maximum load factor. + */ + max_load_factor(z: number): void; + /** + * Locate element's bucket. + * + * Returns the bucket number where the element with key is located. + * + * A bucket is a slot in the container's internal hash table to which elements are assigned based on the + * hash value of their key. Buckets are numbered from 0 to ({@link bucket_count} - 1). + * + * Individual elements in a bucket can be accessed by means of the range iterators returned by + * {@link begin} and {@link end}. + * + * @param key Key whose bucket is to be located. + */ + bucket(key: Key): number; + /** + * Request a capacity change. + * + * Sets the number of buckets in the container ({@link bucket_count}) to the most appropriate to contain at + * least n elements. + * + * If n is greater than the current {@link bucket_count} multiplied by the {@link max_load_factor}, + * the container's {@link bucket_count} is increased and a {@link rehash} is forced. + * + * If n is lower than that, the function may have no effect. + * + * @param n The number of elements requested as minimum capacity. + */ + reserve(n: number): void; + /** + * Set number of buckets. + * + * Sets the number of buckets in the container to n or more. + * + * If n is greater than the current number of buckets in the container ({@link bucket_count}), a + * {@link HashBuckets.rehash rehash} is forced. The new {@link bucket_count bucket count} can either be equal or + * greater than n. + * + * If n is lower than the current number of buckets in the container ({@link bucket_count}), the + * function may have no effect on the {@link bucket_count bucket count} and may not force a + * {@link HashBuckets.rehash rehash}. + * + * A {@link HashBuckets.rehash rehash} is the reconstruction of the hash table: All the elements in the + * container are rearranged according to their hash value into the new set of buckets. This may alter the order + * of iteration of elements within the container. + * + * {@link HashBuckets.rehash Rehashes} are automatically performed by the container whenever its + * {@link load_factor load factor} is going to surpass its {@link max_load_factor} in an operation. + * + * Notice that this function expects the number of buckets as argument. A similar function exists, + * {@link reserve}, that expects the number of elements in the container as argument. + * + * @param n The minimum number of buckets for the container hash table. + */ + rehash(n: number): void; + } +} +declare namespace std.base { + /** + * A common interface for hash set. + * + * {@link IHashSet}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 IHashSet}, 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 IHashSet} cannot be + * modified once in the container - they can be inserted and removed, though. + * + * Internally, the elements in the {@link IHashSet} 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 IHashSet} 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.
    + *
    + * + * @param Type of the elements. + * Each element in an {@link IHashSet} is also uniquely identified by this value. + * + * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set + * @author Jeongho Nam + */ + interface IHashSet extends SetContainer { + /** + * Return number of buckets. + * + * Returns the number of buckets in the {@link IHashSet} container. + * + * A bucket is a slot in the container's internal hash table to which elements are assigned based on the + * hash value of their key. + * + * The number of buckets influences directly the {@link load_factor load factor} of the container's hash + * table (and thus the probability of collision). The container automatically increases the number of buckets to + * keep the load factor below a specific threshold (its {@link max_load_factor}), causing a {@link rehash} each + * time the number of buckets needs to be increased. + * + * @return The current amount of buckets. + */ + bucket_count(): number; + /** + * Return bucket size. + * + * Returns the number of elements in bucket n. + * + * A bucket is a slot in the container's internal hash table to which elements are assigned based on the hash + * value of their key. + * + * The number of elements in a bucket influences the time it takes to access a particular element in the + * bucket. The container automatically increases the number of buckets to keep the {@link load_cator load factor} + * (which is the average bucket size) below its {@link max_load_factor}. + * + * @param n Bucket number. This shall be lower than {@link bucket_count}. + * + * @return The number of elements in bucket n. + */ + bucket_size(n: number): number; + /** + * Get maximum load factor. + * + * Returns the current maximum load factor for the {@link HashMultiMap} container. + * + * The load factor is the ratio between the number of elements in the container (its {@link size}) and the + * number of buckets ({@link bucket_count}). + * + * By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0. + * + * The load factor influences the probability of collision in the hash table (i.e., the probability of two + * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold + * that forces an increase in the number of buckets (and thus causing a {@link rehash}). + * + * Note though, that implementations may impose an upper limit on the number of buckets (see + * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}. + * + * @return The current load factor. + */ + max_load_factor(): number; + /** + * Set maximum load factor. + * + * Sets z as the cnew maximum load factor for the {@link HashMultiMap} container. + * + * The load factor is the ratio between the number of elements in the container (its {@link size}) and the + * number of buckets ({@link bucket_count}). + * + * By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0. + * + * The load factor influences the probability of collision in the hash table (i.e., the probability of two + * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold + * that forces an increase in the number of buckets (and thus causing a {@link rehash}). + * + * Note though, that implementations may impose an upper limit on the number of buckets (see + * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}. + * + * @param z The new maximum load factor. + */ + max_load_factor(z: number): void; + /** + * Locate element's bucket. + * + * Returns the bucket number where the element with key is located. + * + * A bucket is a slot in the container's internal hash table to which elements are assigned based on the + * hash value of their key. Buckets are numbered from 0 to ({@link bucket_count} - 1). + * + * Individual elements in a bucket can be accessed by means of the range iterators returned by + * {@link begin} and {@link end}. + * + * @param key Key whose bucket is to be located. + */ + bucket(key: T): number; + /** + * Request a capacity change. + * + * Sets the number of buckets in the container ({@link bucket_count}) to the most appropriate to contain at + * least n elements. + * + * If n is greater than the current {@link bucket_count} multiplied by the {@link max_load_factor}, + * the container's {@link bucket_count} is increased and a {@link rehash} is forced. + * + * If n is lower than that, the function may have no effect. + * + * @param n The number of elements requested as minimum capacity. + */ + reserve(n: number): void; + /** + * Set number of buckets. + * + * Sets the number of buckets in the container to n or more. + * + * If n is greater than the current number of buckets in the container ({@link bucket_count}), a + * {@link HashBuckets.rehash rehash} is forced. The new {@link bucket_count bucket count} can either be equal or + * greater than n. + * + * If n is lower than the current number of buckets in the container ({@link bucket_count}), the + * function may have no effect on the {@link bucket_count bucket count} and may not force a + * {@link HashBuckets.rehash rehash}. + * + * A {@link HashBuckets.rehash rehash} is the reconstruction of the hash table: All the elements in the + * container are rearranged according to their hash value into the new set of buckets. This may alter the order + * of iteration of elements within the container. + * + * {@link HashBuckets.rehash Rehashes} are automatically performed by the container whenever its + * {@link load_factor load factor} is going to surpass its {@link max_load_factor} in an operation. + * + * Notice that this function expects the number of buckets as argument. A similar function exists, + * {@link reserve}, that expects the number of elements in the container as argument. + * + * @param n The minimum number of buckets for the container hash table. + */ + rehash(n: number): void; + } +} +declare namespace std.base { + /** + * An interface for linear containers. + * + * + * + * + * + * @author Jeonngho Nam + */ + interface ILinearContainer extends Container { + /** + * @inheritdoc + */ + assign>(begin: InputIterator, end: InputIterator): void; + /** + * Assign container content. + * + * Assigns new contents to the {@link IList container}, replacing its current contents, + * and modifying its {@link size} accordingly. + * + * @param n New size for the + * @param val Value to fill the container with. Each of the n elements in the container will + * be initialized to a copy of this value. + */ + assign(n: number, val: T): void; + /** + * Access first element. + * Returns a value of the first element in the {@link IList container}. + * + * Unlike member {@link end end()}, which returns an iterator just past this element, + * this function returns a direct value. + * + * Calling this function on an {@link empty} {@link IList container} causes undefined behavior. + * + * @return A value of the first element of the {@link IList container}. + */ + front(): T; + /** + * Access last element. + * Returns a value of the last element in the {@link IList container}. + * + * Unlike member {@link end end()}, which returns an iterator just past this element, + * this function returns a direct value. + * + * Calling this function on an {@link empty} {@link IList container} causes undefined behavior. + * + * @return A value of the last element of the {@link IList container}. + */ + back(): T; + /** + * Add element at the end. + * + * Adds a new element at the end of the {@link IList container}, after its current last element. + * This effectively increases the {@link IList container} {@link size} by one. + * + * @param val Value to be copied to the new element. + */ + push_back(val: T): void; + /** + * Delete last element. + * + * Removes the last element in the {@link IList container}, effectively reducing the + * {@link IList container} {@link size} by one. + */ + pop_back(): void; + /** + * Insert an element. + * + * The {@link IList conatiner} is extended by inserting new element before the element at the + * specified position, effectively increasing the {@link IList container} {@link size} by + * one. + * + * @param position Position in the {@link IList container} where the new elements are inserted. + * {@link iterator} is a member type, defined as a {@link iterator random access iterator} + * type that points to elements. + * @param val Value to be copied to the inserted element. + * + * @return An iterator that points to the newly inserted element. + */ + insert(position: Iterator, val: T): Iterator; + /** + * Insert elements by range iterators. + * + * The {@link IList container} is extended by inserting new elements before the element at the + * specified position, effectively increasing the {@link IList container} {@link size} by + * the number of repeating elements
    n
    . + * + * @param position Position in the {@link IList container} where the new elements are inserted. + * {@link iterator} is a member type, defined as a {@link iterator random access iterator} + * type that points to elements. + * @param n Number of elements to insert. Each element is initialized to a copy of val. + * @param val Value to be copied (or moved) to the inserted elements. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert(position: Iterator, n: number, val: T): Iterator; + /** + * Insert elements by range iterators. + * + * The {@link IList container} is extended by inserting new elements before the element at the + * specified position, effectively increasing the {@link IList container} {@link size} by + * the number of elements inserted by range iterators. + * + * @param position Position in the {@link IList container} where the new elements are inserted. + * {@link iterator} is a member type, defined as a {@link iterator random access iterator} + * type that points to elements. + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert>(position: Iterator, begin: InputIterator, end: InputIterator): Iterator; + } + /** + * An interface for iterators from linear containers. + * + * {@link ILieanerIterator} is an bi-directional iterator which is created from the related + * {@link ILinearContainer linear containers}. Not only accessing to {@link value} of the pointed element from + * this {@link ILieanerIterator}, but also modifying the {@link value} is possible. + * + * @author Jeongho Nam + */ + interface ILinearIterator extends Iterator { + /** + * @inheritdoc + */ + source(): ILinearContainer; + /** + * @inheritdoc + */ + value: T; + /** + * @inheritdoc + */ + prev(): ILinearIterator; + /** + * @inheritdoc + */ + next(): ILinearIterator; + } +} +declare namespace std.base { + /** + * Common interface for tree-structured map. + * + * {@link ITreeMap ITreeMaps} are associative containers that store elements formed by a combination of + * a key value and a mapped value, following a specific order. + * + * In a {@link ITreeMap}, the key values are generally used to sort and uniquely identify + * the elements, while the mapped values store the content associated to this key. The types of + * key and mapped value may differ, and are grouped together in member type + * value_type, which is a {@link Pair} type combining both: + * + * typedef Pair value_type; + * + * Internally, the elements in a {@link ITreeMap}are always sorted by its key following a + * strict weak ordering criterion indicated by its internal comparison method (of {@link less}). + * + * {@link ITreeMap}containers are generally slower than {@link IHashMap} containers + * to access individual elements by their key, but they allow the direct iteration on subsets based + * on their order. + * + * {@link ITreeMap TreeMultiMaps} 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.
    + * + *
    Map
    + *
    Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value.
    + *
    + * + * @param Type of the keys. Each element in a map is uniquely identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @reference http://www.cplusplus.com/reference/map + * @author Jeongho Nam + */ + interface ITreeMap extends MapContainer { + /** + * Return key comparison function. + * + * Returns a references of the comparison function used by the container to compare keys. + * + * The comparison object of a {@link ITreeMap tree-map object} is set on + * {@link TreeMap.constructor construction}. Its type (Key) is the last parameter of the + * {@link ITreeMap.constructor constructors}. By default, this is a {@link less} function, which returns the same + * as operator<. + * + * This function determines the order of the elements in the container: it is a function pointer that takes + * two arguments of the same type as the element keys, and returns true if the first argument + * is considered to go before the second in the strict weak ordering it defines, and false otherwise. + * + * + * Two keys are considered equivalent if {@link key_comp} returns false reflexively (i.e., no + * matter the order in which the keys are passed as arguments). + * + * @return The comparison function. + */ + key_comp(): (x: Key, y: Key) => boolean; + /** + * Return value comparison function. + * + * Returns a comparison function that can be used to compare two elements to get whether the key of the first + * one goes before the second. + * + * The arguments taken by this function object are of member type Pair (defined in + * {@link ITreeMap}), but the mapped type (T) part of the value is not taken into consideration in this + * comparison. + * + * This comparison class returns true if the {@link Pair.first key} of the first argument + * is considered to go before that of the second (according to the strict weak ordering specified by the + * container's comparison function, {@link key_comp}), and false otherwise. + * + * @return The comparison function for element values. + */ + value_comp(): (x: Pair, y: Pair) => boolean; + /** + * Return iterator to lower bound. + * + * Returns an iterator pointing to the first element in the container whose key is not considered to + * go before k (i.e., either it is equivalent or goes after). + * + * The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(k, element_key) would return false. + * + * If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), + * the function returns an iterator to the first element whose key is not less than k. + * + * A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except + * in the case that the {@link ITreeMap} contains an element with a key equivalent to k: In this + * case, {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} + * returns an iterator pointing to the next element. + * + * @param k Key to search for. + * + * @return An iterator to the the first element in the container whose key is not considered to go before + * k, or {@link ITreeMap.end} if all keys are considered to go before k. + */ + lower_bound(key: Key): MapIterator; + /** + * Return iterator to upper bound. + * + * Returns an iterator pointing to the first element in the container whose key is considered to + * go after k. + * + * The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(k, element_key) would return true. + * + * If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), + * the function returns an iterator to the first element whose key is greater than k. + * + * A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except + * in the case that the map contains an element with a key equivalent to k: In this case + * {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} returns an + * iterator pointing to the next element. + * + * @param k Key to search for. + * + * @return An iterator to the the first element in the container whose key is considered to go after + * k, or {@link TreeMap.end end} if no keys are considered to go after k. + */ + upper_bound(key: Key): MapIterator; + /** + * Get range of equal elements. + * + * Returns the bounds of a range that includes all the elements in the container which have a key + * equivalent to k. + * + * If no matches are found, the range returned has a length of zero, with both iterators pointing to + * the first element that has a key considered to go after k according to the container's internal + * comparison object (key_comp). + * + * Two keys are considered equivalent if the container's comparison object returns false reflexively + * (i.e., no matter the order in which the keys are passed as arguments). + * + * @param k Key to search for. + * + * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of + * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound + * (the same as {@link upper_bound}). + */ + equal_range(key: Key): Pair, MapIterator>; + } +} +declare namespace std.base { + /** + * A common interface for tree-structured set. + * + * {@link ITreeSet TreeMultiSets} are containers that store elements following a specific order. + * + * In a {@link ITreeSet}, the value of an element also identifies it (the value is itself + * the key, of type T). The value of the elements in a {@link ITreeSet} 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 ITreeSet TreeMultiSets} are always sorted following a strict + * weak ordering criterion indicated by its internal comparison method (of {@link IComparable.less less}). + * + * {@link ITreeSet} containers are generally slower than {@link IHashSet} containers + * to access individual elements by their key, but they allow the direct iteration on subsets based on + * their order. + * + * {@link ITreeSet TreeMultiSets} 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.
    + *
    + * + * @param Type of the elements. Each element in a {@link ITreeSet} container is also identified + * by this value (each value is itself also the element's key). + * + * @reference http://www.cplusplus.com/reference/set + * @author Jeongho Nam + */ + interface ITreeSet extends SetContainer { + /** + * Return comparison function. + * + * Returns a copy of the comparison function used by the container. + * + * By default, this is a {@link less} object, which returns the same as operator<. + * + * This object determines the order of the elements in the container: it is a function pointer or a function + * object that takes two arguments of the same type as the container elements, and returns true if + * the first argument is considered to go before the second in the strict weak ordering it + * defines, and false otherwise. + * + * Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false + * reflexively (i.e., no matter the order in which the elements are passed as arguments). + * + * In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, + * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent. + * + * @return The comparison function. + */ + key_comp(): (x: T, y: T) => boolean; + /** + * Return comparison function. + * + * Returns a copy of the comparison function used by the container. + * + * By default, this is a {@link less} object, which returns the same as operator<. + * + * This object determines the order of the elements in the container: it is a function pointer or a function + * object that takes two arguments of the same type as the container elements, and returns true if + * the first argument is considered to go before the second in the strict weak ordering it + * defines, and false otherwise. + * + * Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false + * reflexively (i.e., no matter the order in which the elements are passed as arguments). + * + * In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, + * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent. + * + * @return The comparison function. + */ + value_comp(): (x: T, y: T) => boolean; + /** + * Return iterator to lower bound. + * + * Returns an iterator pointing to the first element in the container which is not considered to + * go before val (i.e., either it is equivalent or goes after). + * + * The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(element,val) would return false. + * + * If the {@link ITreeSet} class is instantiated with the default comparison type ({@link less}), + * the function returns an iterator to the first element that is not less than val. + + * A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except + * in the case that the {@link ITreeSet} contains elements equivalent to val: In this case + * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas + * {@link upper_bound} returns an iterator pointing to the element following the last. + * + * @param val Value to compare. + * + * @return An iterator to the the first element in the container which is not considered to go before + * val, or {@link ITreeSet.end} if all elements are considered to go before val. + */ + lower_bound(val: T): SetIterator; + /** + * Return iterator to upper bound. + * + * Returns an iterator pointing to the first element in the container which is considered to go after + * val. + + * The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(val,element) would return true. + + * If the {@code ITreeSet} class is instantiated with the default comparison type (less), the + * function returns an iterator to the first element that is greater than val. + * + * A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except + * in the case that the {@ITreeSet} contains elements equivalent to val: In this case + * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas + * {@link upper_bound} returns an iterator pointing to the element following the last. + * + * @param val Value to compare. + * + * @return An iterator to the the first element in the container which is considered to go after + * val, or {@link TreeSet.end end} if no elements are considered to go after val. + */ + upper_bound(val: T): SetIterator; + /** + * Get range of equal elements. + * + * Returns the bounds of a range that includes all the elements in the container that are equivalent + * to val. + * + * If no matches are found, the range returned has a length of zero, with both iterators pointing to + * the first element that is considered to go after val according to the container's + * internal comparison object (key_comp). + * + * Two elements of a multiset are considered equivalent if the container's comparison object returns + * false reflexively (i.e., no matter the order in which the elements are passed as arguments). + * + * @param key Value to search for. + * + * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of + * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound + * (the same as {@link upper_bound}). + */ + equal_range(val: T): Pair, SetIterator>; + } +} +declare namespace std.base { + /** + * @hidden + */ + class _ArrayIterator extends Iterator { + private data_; + private index_; + constructor(data: Array, index: number); + source(): Container; + index(): number; + readonly value: T; + prev(): _ArrayIterator; + next(): _ArrayIterator; + advance(n: number): _ArrayIterator; + equals(obj: _ArrayIterator): boolean; + swap(obj: _ArrayIterator): void; + } +} +declare namespace std.base { + /** + * @hidden + */ + class _Repeater extends Iterator { + private index_; + private value_; + constructor(index: number, value?: T); + source(): base.Container; + index(): number; + readonly value: T; + prev(): _Repeater; + next(): _Repeater; + advance(n: number): _Repeater; + equals(obj: _Repeater): boolean; + swap(obj: _Repeater): void; + } +} +declare namespace std.base { + /** + * An abstract map. + * + * {@link MapContainer MapContainers} are associative containers that store elements formed by a combination + * of a key value (Key) and a mapped value (T), and which allows for fast retrieval + * of individual elements based on their keys. + * + * In a {@link MapContainer}, the key values are generally used to identify the elements, while the + * mapped values store the content associated to this key. The types of key and + * mapped value may differ, and are grouped together in member type value_type, which is a + * {@link Pair} type combining both: + * + * typedef pair value_type; + * + * {@link MapContainer} 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. + *
    + * + *
    Map
    + *
    + * Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value. + *
    + *
    + * + * @param Type of the keys. Each element in a map is identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @author Jeongho Nam + */ + abstract class MapContainer extends Container> { + /** + * @hidden + */ + private data_; + /** + * Default Constructor. + */ + protected constructor(); + /** + * @inheritdoc + */ + assign>>(first: InputIterator, last: InputIterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * Get iterator to element. + * + * Searches the container for an element with a identifier equivalent to key and returns an + * iterator to it if found, otherwise it returns an iterator to {@link end end()}. + * + * Two keys are considered equivalent if the container's comparison object returns false reflexively + * (i.e., no matter the order in which the elements are passed as arguments). + * + * Another member functions, {@link has has()} and {@link count count()}, can be used to just check + * whether a particular key exists. + * + * @param key Key to be searched for + * @return An iterator to the element, if an element with specified key is found, or + * {@link end end()} otherwise. + */ + abstract find(key: Key): MapIterator; + /** + * Return iterator to beginning. + * + * Returns an iterator referring the first element in the + * + * #### Note + * If the container is {@link empty}, the returned iterator is same with {@link end end()}. + * + * @return An iterator to the first element in the The iterator containes the first element's value. + */ + begin(): MapIterator; + /** + * Return iterator to end. + * Returns an iterator referring to the past-the-end element in the + * + * The past-the-end element is the theoretical element that would follow the last element in the + * It does not point to any element, and thus shall not be dereferenced. + * + * Because the ranges used by functions of the container do not include the element reference by their + * closing iterator, this function is often used in combination with {@link MapContainer}.{@link begin} to + * specify a range including all the elements in the + * + * #### Note + * Returned iterator from {@link MapContainer}.{@link end} does not refer any element. Trying to accessing + * element by the iterator will cause throwing exception ({@link OutOfRange}). + * + * If the container is {@link empty}, this function returns the same as {@link begin}. + * + * @return An iterator to the end element in the + */ + end(): MapIterator; + /** + * Return {@link MapReverseIterator reverse iterator} to reverse beginning. + * + * Returns a {@link MapReverseIterator reverse iterator} pointing to the last element in the container + * (i.e., its reverse beginning). + * + * {@link MapReverseIterator Reverse iterators} iterate backwards: increasing them moves them towards the + * beginning of the container. + * + * {@link rbegin} points to the element preceding the one that would be pointed to by member {@link end}. + *7 + * + * @return A {@link MapReverseIterator reverse iterator} to the reverse beginning of the sequence + * + */ + rbegin(): MapReverseIterator; + /** + * Return {@link MapReverseIterator reverse iterator} to reverse end. + * + * Returns a {@link MapReverseIterator reverse iterator} pointing to the theoretical element right before + * the first element in the {@link MapContainer map container} (which is considered its reverse end). + * + * + * The range between {@link MapContainer}.{@link rbegin} and {@link MapContainer}.{@link rend} contains + * all the elements of the container (in reverse order). + * + * @return A {@link MapReverseIterator reverse iterator} to the reverse end of the sequence + */ + rend(): MapReverseIterator; + /** + * Whether have the item or not. + * + * Indicates whether a map has an item having the specified identifier. + * + * @param key Key value of the element whose mapped value is accessed. + * + * @return Whether the map has an item having the specified identifier. + */ + has(key: Key): boolean; + /** + * Count elements with a specific key. + * + * Searches the container for elements whose key is key and returns the number of elements found. + * + * @param key Key value to be searched for. + * + * @return The number of elements in the container with a key. + */ + abstract count(key: Key): number; + /** + * Return the number of elements in the map. + */ + size(): number; + /** + * @inheritdoc + */ + push(...args: Pair[]): number; + /** + * @inheritdoc + */ + push(...args: [Key, T][]): number; + /** + * Construct and insert element with hint + * + * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in + * place using *args* as the arguments for the element's constructor. *hint* points to a location in the + * container suggested as a hint on where to start the search for its insertion point (the container may or + * may not use this suggestion to optimize the insertion operation). + * + * A similar member function exists, {@link insert}, which either copies or moves an existing object into + * the container, and may also take a position *hint*. + * + * @param hint Hint for the position where the element can be inserted. + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. + */ + emplace_hint(hint: MapIterator, key: Key, val: T): MapIterator; + /** + * Construct and insert element with hint + * + * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in + * place using *args* as the arguments for the element's constructor. *hint* points to a location in the + * container suggested as a hint on where to start the search for its insertion point (the container may or + * may not use this suggestion to optimize the insertion operation). + * + * A similar member function exists, {@link insert}, which either copies or moves an existing object into + * the container, and may also take a position *hint*. + * + * @param hint Hint for the position where the element can be inserted. + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return An {@link MapIterator iterator} pointing to either the newly inserted element or to the element + * that already had an equivalent key in the {@link MapContainer}. + */ + emplace_hint(hint: MapReverseIterator, key: Key, val: T): MapReverseIterator; + /** + * Construct and insert element with hint + * + * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in + * place using *args* as the arguments for the element's constructor. *hint* points to a location in the + * container suggested as a hint on where to start the search for its insertion point (the container may or + * may not use this suggestion to optimize the insertion operation). + * + * A similar member function exists, {@link insert}, which either copies or moves an existing object into + * the container, and may also take a position *hint*. + * + * @param hint Hint for the position where the element can be inserted. + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. + */ + emplace_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * Construct and insert element with hint + * + * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in + * place using *args* as the arguments for the element's constructor. *hint* points to a location in the + * container suggested as a hint on where to start the search for its insertion point (the container may or + * may not use this suggestion to optimize the insertion operation). + * + * A similar member function exists, {@link insert}, which either copies or moves an existing object into + * the container, and may also take a position *hint*. + * + * @param hint Hint for the position where the element can be inserted. + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return An {@link MapIterator iterator} pointing to either the newly inserted element or to the element + * that already had an equivalent key in the {@link MapContainer}. + */ + emplace_hint(hint: MapReverseIterator, pair: Pair): MapReverseIterator; + /** + * Insert an element. + * + * Extends the container by inserting a new element, effectively increasing the container {@link size} + * by the number of element inserted (zero or one). + * + * @param hint Hint for the position where the element can be inserted. + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. + */ + insert(hint: MapIterator, pair: Pair): MapIterator; + /** + * Insert an element. + * + * Extends the container by inserting a new element, effectively increasing the container {@link size} + * by the number of element inserted (zero or one). + * + * @param hint Hint for the position where the element can be inserted. + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. + */ + insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; + /** + * Insert an element. + * + * Extends the container by inserting new elements, effectively increasing the container {@link size} + * by the number of elements inserted. + * + * @param hint Hint for the position where the element can be inserted. + * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. + */ + insert(hint: MapIterator, tuple: [L, U]): MapIterator; + /** + * Insert an element. + * + * Extends the container by inserting new elements, effectively increasing the container {@link size} + * by the number of elements inserted. + * + * @param hint Hint for the position where the element can be inserted. + * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. + */ + insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; + /** + * Insert elements from range iterators. + * + * Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of elements inserted. + * + * @param begin Input iterator specifying initial position of a range of elements. + * @param end Input iterator specifying final position of a range of elements. + * Notice that the range includes all the elements between begin and end, + * including the element pointed by begin but not the one pointed by end. + */ + insert>>(first: InputIterator, last: InputIterator): void; + /** + * @hidden + */ + protected abstract _Insert_by_pair(pair: Pair): any; + /** + * @hidden + */ + private _Insert_by_tuple(tuple); + /** + * @hidden + */ + protected abstract _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * @hidden + */ + private _Insert_by_hint_with_tuple(hint, tuple); + /** + * @hidden + */ + protected abstract _Insert_by_range>>(first: InputIterator, last: InputIterator): void; + /** + * Erase an elemet by key. + * + * Removes from the {@link MapContainer map container} a single element. + * + * This effectively reduces the container {@link size} by the number of element removed (zero or one), + * which are destroyed. + * + * @param key Key of the element to be removed from the {@link MapContainer}. + */ + erase(key: Key): number; + /** + * Erase an elemet by iterator. + * + * Removes from the {@link MapContainer map container} a single element. + * + * This effectively reduces the container {@link size} by the number of element removed (zero or one), + * which are destroyed. + * + * @param it Iterator specifying position winthin the {@link MapContainer map contaier} to be removed. + */ + erase(it: MapIterator): MapIterator; + /** + * Erase elements by range iterators. + * + * Removes from the {@link MapContainer map container} a range of elements. + * + * This effectively reduces the container {@link size} by the number of elements removed, which are + * destroyed. + * + * @param begin An iterator specifying initial position of a range within {@link MApContainer map container} + * to be removed. + * @param end An iterator specifying initial position of a range within {@link MApContainer map container} + * to be removed. + * Notice that the range includes all the elements between begin and end, + * including the element pointed by begin but not the one pointed by end. + */ + erase(begin: MapIterator, end: MapIterator): MapIterator; + /** + * Erase an elemet by iterator. + * + * Removes from the {@link MapContainer map container} a single element. + * + * This effectively reduces the container {@link size} by the number of element removed (zero or one), + * which are destroyed. + * + * @param it Iterator specifying position winthin the {@link MapContainer map contaier} to be removed. + */ + erase(it: MapReverseIterator): MapReverseIterator; + /** + * Erase elements by range iterators. + * + * Removes from the {@link MapContainer map container} a range of elements. + * + * This effectively reduces the container {@link size} by the number of elements removed, which are + * destroyed. + * + * @param begin An iterator specifying initial position of a range within {@link MApContainer map container} + * to be removed. + * @param end An iterator specifying initial position of a range within {@link MApContainer map container} + * to be removed. + * Notice that the range includes all the elements between begin and end, + * including the element pointed by begin but not the one pointed by end. + */ + erase(begin: MapReverseIterator, end: MapReverseIterator): MapReverseIterator; + /** + * @hidden + */ + private _Erase_by_key(key); + /** + * @hidden + */ + private _Erase_by_iterator(first, last?); + /** + * @hidden + */ + private _Erase_by_range(first, last); + /** + * @hidden + */ + protected _Swap(obj: MapContainer): void; + /** + * Merge two maps. + * + * Extracts and transfers elements from *source* to this container. + * + * @param source A {@link MapContainer map container} to transfer the elements from. + */ + abstract merge(source: MapContainer): void; + /** + * @hidden + */ + protected abstract _Handle_insert(first: MapIterator, last: MapIterator): void; + /** + * @hidden + */ + protected abstract _Handle_erase(first: MapIterator, last: MapIterator): void; + } + /** + * @hidden + */ + class _MapElementList extends _ListContainer, MapIterator> { + private associative_; + private rend_; + constructor(associative: MapContainer); + protected _Create_iterator(prev: MapIterator, next: MapIterator, val: Pair): MapIterator; + protected _Set_begin(it: MapIterator): void; + associative(): MapContainer; + rbegin(): MapReverseIterator; + rend(): MapReverseIterator; + } +} +declare namespace std { + /** + * An iterator of {@link MapContainer map container}. + * + * + * + * + * @author Jeongho Nam + */ + class MapIterator extends base._ListIteratorBase> implements IComparable> { + /** + * Construct from the {@link MapContainer source map} and {@link ListIterator list iterator}. + * + * @param source The source {@link MapContainer}. + * @param list_iterator A {@link ListIterator} pointing {@link Pair} of key and value. + */ + constructor(source: base._MapElementList, prev: MapIterator, next: MapIterator, val: Pair); + /** + * Get iterator to previous element. + */ + prev(): MapIterator; + /** + * Get iterator to next element. + */ + next(): MapIterator; + /** + * Advances the Iterator by n element positions. + * + * @param step Number of element positions to advance. + * @return An advanced Iterator. + */ + advance(step: number): MapIterator; + /** + * @hidden + */ + source(): base.MapContainer; + /** + * Get first, key element. + */ + readonly first: Key; + /** + * Get second, value element. + */ + /** + * Set second value. + */ + second: T; + /** + * @inheritdoc + */ + less(obj: MapIterator): boolean; + /** + * @inheritdoc + */ + equals(obj: MapIterator): boolean; + /** + * @inheritdoc + */ + hashCode(): number; + /** + * @inheritdoc + */ + swap(obj: MapIterator): void; + } + /** + * A reverse-iterator of {@link MapContainer map container}. + * + * + * + * + * @author Jeongho Nam + */ + class MapReverseIterator extends ReverseIterator, base.MapContainer, 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(base: MapIterator): MapReverseIterator; + /** + * Get first, key element. + */ + readonly first: Key; + /** + * Get second, value element. + */ + /** + * Set second value. + */ + second: T; + } +} +declare namespace std.base { + /** + * An abstract multi-map. + * + * {@link MultiMap MultiMaps} are associative containers that store elements formed by a combination of a + * key value (Key) and a mapped value (T), and which allows for fast retrieval of + * individual elements based on their keys. + * + * In a {@link MapContainer}, the key values are generally used to identify the elements, while the + * mapped values store the content associated to this key. The types of key and + * mapped value may differ, and are grouped together in member type value_type, which is a + * {@link Pair} type combining both: + * + * typedef pair value_type; + * + * {@link UniqueMap} 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. + *
    + * + *
    Map
    + *
    + * Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value. + *
    + * + *
    Multiple equivalent keys
    + *
    Multiple elements in the container can have equivalent keys.
    + *
    + * + * @param Type of the keys. Each element in a map is identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @author Jeongho Nam + */ + abstract class MultiMap extends MapContainer { + /** + * Construct and insert element. + * + * Inserts a new element in the {@link MultiMap}. This new element is constructed in place using args + * as the arguments for the element's constructor. + * + * This effectively increases the container {@link size} by one. + * + * A similar member function exists, {@link insert}, which either copies or moves existing objects into the + * container. + * + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return An {@link MapIterator iterator} to the newly inserted element. + */ + emplace(key: Key, value: T): MapIterator; + /** + * Construct and insert element. + * + * Inserts a new element in the {@link MultiMap}. This new element is constructed in place using args + * as the arguments for the element's constructor. + * + * This effectively increases the container {@link size} by one. + * + * A similar member function exists, {@link insert}, which either copies or moves existing objects into the + * container. + * + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * @return An {@link MapIterator iterator} to the newly inserted element. + */ + emplace(pair: Pair): MapIterator; + /** + * Insert elements. + * + * Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of elements inserted. + * + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return An iterator pointing to the newly inserted element. + */ + insert(pair: Pair): MapIterator; + /** + * Insert elements. + * + * Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of elements inserted. + * + * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. + * + * @return An iterator pointing to the newly inserted element. + */ + insert(tuple: [L, U]): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapIterator, pair: Pair): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; + /** + * @inheritdoc + */ + insert(hint: MapIterator, tuple: [L, U]): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; + /** + * @inheritdoc + */ + insert>>(first: InputIterator, last: InputIterator): void; + /** + * @inheritdoc + */ + merge(source: MapContainer): void; + } +} +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 + * 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.
    + *
    + * + * @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 SetContainer extends Container { + /** + * {@link List} storing elements. + * + * Storing elements and keeping those sequence of the {@link SetContainer} are implemented by + * {@link data_ this list container}. Implementing index-table is also related with {@link data_ this list} + * by storing {@link ListIterator iterators} ({@link SetIterator} references {@link ListIterator}) who are + * created from {@link data_ here}. + */ + private data_; + /** + * Default Constructor. + */ + protected constructor(); + /** + * @inheritdoc + */ + assign>(begin: Iterator, end: Iterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * Get iterator to element. + * + * Searches the container for an element with key as value and returns an iterator to it if found, + * otherwise it returns an iterator to {@link end end()} (the element past the end of the container). + * + * Another member function, {@link count count()}, can be used to just check whether a particular element + * exists. + * + * @param key Key to be searched for. + * + * @return An iterator to the element, if the specified value is found, or {@link end end()} if it is not + * found in the + */ + abstract find(val: T): SetIterator; + /** + * @inheritdoc + */ + begin(): SetIterator; + /** + * @inheritdoc + */ + end(): SetIterator; + /** + * @inheritdoc + */ + rbegin(): SetReverseIterator; + /** + * @inheritdoc + */ + rend(): SetReverseIterator; + /** + * Whether have the item or not. + * + * Indicates whether a set has an item having the specified identifier. + * + * @param key Key value of the element whose mapped value is accessed. + * + * @return Whether the set has an item having the specified identifier. + */ + has(val: T): boolean; + /** + * Count elements with a specific key. + * + * Searches the container for elements with a value of k and returns the number of elements found. + * + * @param key Value of the elements to be counted. + * + * @return The number of elements in the container with a key. + */ + abstract count(val: T): number; + /** + * @inheritdoc + */ + size(): number; + /** + * @inheritdoc + */ + push(...items: T[]): number; + /** + * Insert an element with hint. + * + * Extends the container by inserting new elements, effectively increasing the container size by the + * number of elements inserted. + * + * @param hint Hint for the position where the element can be inserted. + * @param val Value to be inserted as an element. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had its + * same value in the {@link SetContainer}. + */ + insert(hint: SetIterator, val: T): SetIterator; + /** + * Insert an element with hint. + * + * Extends the container by inserting new elements, effectively increasing the container size by the + * number of elements inserted. + * + * @param hint Hint for the position where the element can be inserted. + * @param val Value to be inserted as an element. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had its + * same value in the {@link SetContainer}. + */ + insert(hint: SetReverseIterator, val: T): SetReverseIterator; + /** + * Insert elements with a range of a + * + * Extends the container by inserting new elements, effectively increasing the container size by the + * number of elements inserted. + * + * @param begin An iterator specifying range of the begining element. + * @param end An iterator specifying range of the ending element. + */ + insert>(begin: InputIterator, end: InputIterator): void; + /** + * @hidden + */ + protected abstract _Insert_by_val(val: T): any; + /** + * @hidden + */ + protected abstract _Insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected abstract _Insert_by_range>(begin: InputIterator, end: InputIterator): void; + /** + * Erase an element. + * Removes from the set container the elements whose value is key. + * + * This effectively reduces the container size by the number of elements removed. + * + * @param key Value of the elements to be erased. + * + * @return Number of elements erased. + */ + erase(val: T): number; + /** + * @inheritdoc + */ + erase(it: SetIterator): SetIterator; + /** + * Erase elements. + * Removes from the set container a range of elements.. + * + * This effectively reduces the container size by the number of elements removed. + * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + */ + erase(begin: SetIterator, end: SetIterator): SetIterator; + /** + * @inheritdoc + */ + erase(it: SetReverseIterator): SetReverseIterator; + /** + * Erase elements. + * Removes from the set container a range of elements.. + * + * This effectively reduces the container size by the number of elements removed. + * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + */ + erase(begin: SetReverseIterator, end: SetReverseIterator): SetReverseIterator; + /** + * @hidden + */ + private _Erase_by_iterator(first, last?); + /** + * @hidden + */ + private _Erase_by_val(val); + /** + * @hidden + */ + private _Erase_by_range(first, last); + /** + * @hidden + */ + protected _Swap(obj: SetContainer): void; + /** + * Merge two sets. + * + * Extracts and transfers elements from *source* to this container. + * + * @param source A {@link SetContainer set container} to transfer the elements from. + */ + abstract merge(source: SetContainer): void; + /** + * @hidden + */ + protected abstract _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @hidden + */ + protected abstract _Handle_erase(first: SetIterator, last: SetIterator): void; + } + /** + * @hidden + */ + class _SetElementList extends _ListContainer> { + private associative_; + private rend_; + constructor(associative: SetContainer); + protected _Create_iterator(prev: SetIterator, next: SetIterator, val: T): SetIterator; + protected _Set_begin(it: SetIterator): void; + associative(): SetContainer; + rbegin(): SetReverseIterator; + rend(): SetReverseIterator; + } +} +declare namespace std { + /** + * An iterator of a Set. + * + * + * + * + * @author Jeongho Nam + */ + class SetIterator extends base._ListIteratorBase implements IComparable> { + /** + * Construct from source and index number. + * + * #### Note + * Do not create iterator directly. + * + * Use begin(), find() or end() in Map instead. + * + * @param map The source Set to reference. + * @param index Sequence number of the element in the source Set. + */ + constructor(source: base._SetElementList, prev: SetIterator, next: SetIterator, val: T); + /** + * @inheritdoc + */ + source(): base.SetContainer; + /** + * @inheritdoc + */ + prev(): SetIterator; + /** + * @inheritdoc + */ + next(): SetIterator; + /** + * @inheritdoc + */ + advance(size: number): SetIterator; + /** + * @inheritdoc + */ + less(obj: SetIterator): boolean; + /** + * @inheritdoc + */ + equals(obj: SetIterator): boolean; + /** + * @inheritdoc + */ + hashCode(): number; + /** + * @inheritdoc + */ + swap(obj: SetIterator): void; + } + /** + * A reverse-iterator of Set. + * + * + * + * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class SetReverseIterator extends ReverseIterator, SetIterator, SetReverseIterator> { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ + constructor(base: SetIterator); + /** + * @hidden + */ + protected _Create_neighbor(base: SetIterator): 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 + * 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.
    + * + *
    Multiple equivalent keys
    + *
    Multiple 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 MultiSet extends SetContainer { + /** + * Insert an element. + * + * Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of elements inserted. + * + * @param key Value to be inserted as an element. + * + * @return An iterator to the newly inserted element. + */ + insert(val: T): SetIterator; + /** + * @inheritdoc + */ + insert(hint: SetIterator, val: T): SetIterator; + /** + * @inheritdoc + */ + insert(hint: SetReverseIterator, val: T): SetReverseIterator; + /** + * @inheritdoc + */ + insert>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + merge(source: SetContainer): void; + } +} +declare namespace std.base { + /** + * @hidden + */ + enum _Color { + BLACK = 0, + RED = 1, + } +} +declare namespace std.base { + /** + * @hidden + */ + abstract class _XTree { + protected root_: _XTreeNode; + protected constructor(); + clear(): void; + find(val: T): _XTreeNode; + protected _Fetch_maximum(node: _XTreeNode): _XTreeNode; + abstract is_less(left: T, right: T): boolean; + abstract is_equal_to(left: T, right: T): boolean; + insert(val: T): void; + private _Insert_case1(N); + private _Insert_case2(N); + private _Insert_case3(N); + private _Insert_case4(node); + private _Insert_case5(node); + erase(val: T): void; + private _Erase_case1(N); + private _Erase_case2(N); + private _Erase_case3(N); + private _Erase_case4(N); + private _Erase_case5(N); + private _Erase_case6(node); + protected _Rotate_left(node: _XTreeNode): void; + protected _Rotate_right(node: _XTreeNode): void; + protected _Replace_node(oldNode: _XTreeNode, newNode: _XTreeNode): void; + private _Fetch_color(node); + } +} +declare namespace std.base { + /** + * @hidden + */ + class _MapTree extends _XTree> { + private map_; + private compare_; + constructor(map: ITreeMap, compare?: (x: Key, y: Key) => boolean); + find(key: Key): _XTreeNode>; + find(it: MapIterator): _XTreeNode>; + private _Find_by_key(key); + lower_bound(key: Key): MapIterator; + upper_bound(key: Key): MapIterator; + equal_range(key: Key): Pair, MapIterator>; + key_comp(): (x: Key, y: Key) => boolean; + value_comp(): (x: Pair, y: Pair) => boolean; + is_equal_to(left: MapIterator, right: MapIterator): boolean; + is_less(left: MapIterator, right: MapIterator): boolean; + } +} +declare namespace std.base { + /** + * @hidden + */ + class _SetTree extends _XTree> { + private set_; + private compare_; + /** + * Default Constructor. + */ + constructor(set: ITreeSet, compare?: (x: T, y: T) => boolean); + find(val: T): _XTreeNode>; + find(it: SetIterator): _XTreeNode>; + private _Find_by_val(val); + lower_bound(val: T): SetIterator; + upper_bound(val: T): SetIterator; + equal_range(val: T): Pair, SetIterator>; + key_comp(): (x: T, y: T) => boolean; + value_comp(): (x: T, y: T) => boolean; + is_equal_to(left: SetIterator, right: SetIterator): boolean; + is_less(left: SetIterator, right: SetIterator): boolean; + } +} +declare namespace std.base { + /** + * @hidden + */ + class _XTreeNode { + parent: _XTreeNode; + left: _XTreeNode; + right: _XTreeNode; + value: T; + color: _Color; + constructor(value: T, color: _Color); + readonly grandParent: _XTreeNode; + readonly sibling: _XTreeNode; + readonly uncle: _XTreeNode; + } +} +declare namespace std.base { + /** + * An abstract unique-map. + * + * {@link UniqueMap UniqueMaps} are associative containers that store elements formed by a combination of a + * key value (Key) and a mapped value (T), and which allows for fast retrieval of + * individual elements based on their keys. + * + * In a {@link MapContainer}, the key values are generally used to uniquely identify the elements, + * while the mapped values store the content associated to this key. The types of key and + * mapped value may differ, and are grouped together in member type value_type, which is a + * {@link Pair} type combining both: + * + * typedef pair value_type; + * + * {@link UniqueMap} 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. + *
    + * + *
    Map
    + *
    + * Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value. + *
    + * + *
    Unique keys
    + *
    No two elements in the container can have equivalent keys.
    + *
    + * + * @param Type of the keys. Each element in a map is uniquely identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @author Jeongho Nam + */ + abstract class UniqueMap extends MapContainer { + /** + * @inheritdoc + */ + count(key: Key): number; + /** + * Get an element + * + * Returns a reference to the mapped value of the element identified with key. + * + * @param key Key value of the element whose mapped value is accessed. + * + * @throw exception out of range + * + * @return A reference object of the mapped value (_Ty) + */ + get(key: Key): T; + /** + * Set an item as the specified identifier. + * + * If the identifier is already in map, change value of the identifier. If not, then insert the object + * with the identifier. + * + * @param key Key value of the element whose mapped value is accessed. + * @param val Value, the item. + */ + set(key: Key, val: T): void; + /** + * Construct and insert element. + * + * Inserts a new element in the {@link UniqueMap} if its *key* is unique. This new element is constructed in + * place using args as the arguments for the construction of a *value_type* (which is an object of a + * {@link Pair} type). + * + * The insertion only takes place if no other element in the container has a *key equivalent* to the one + * being emplaced (*keys* in a {@link UniqueMap} container are unique). + * + * If inserted, this effectively increases the container {@link size} by one. + * + * A similar member function exists, {@link insert}, which either copies or moves existing objects into the + * container. + * + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return If the function successfully inserts the element (because no equivalent element existed already in + * the {@link UniqueMap}), the function returns a {@link Pair} of an {@link MapIterator iterator} to + * the newly inserted element and a value of true. Otherwise, it returns an + * {@link MapIterator iterator} to the equivalent element within the container and a value of false. + */ + emplace(key: Key, value: T): Pair, boolean>; + /** + * Construct and insert element. + * + * Inserts a new element in the {@link UniqueMap} if its *key* is unique. This new element is constructed in + * place using args as the arguments for the construction of a *value_type* (which is an object of a + * {@link Pair} type). + * + * The insertion only takes place if no other element in the container has a *key equivalent* to the one + * being emplaced (*keys* in a {@link UniqueMap} container are unique). + * + * If inserted, this effectively increases the container {@link size} by one. + * + * A similar member function exists, {@link insert}, which either copies or moves existing objects into the + * container. + * + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return If the function successfully inserts the element (because no equivalent element existed already in + * the {@link UniqueMap}), the function returns a {@link Pair} of an {@link MapIterator iterator} to + * the newly inserted element and a value of true. Otherwise, it returns an + * {@link MapIterator iterator} to the equivalent element within the container and a value of false. + */ + emplace(pair: Pair): Pair, boolean>; + /** + * Insert an element. + * + * Extends the container by inserting new elements, effectively increasing the container {@link size} by + * one. + * + * Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of 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 MultiMap}. + * + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly + * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The + * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or + * false if an equivalent key already existed. + */ + insert(pair: Pair): Pair, boolean>; + /** + * Insert an element. + * + * Extends the container by inserting a new element, effectively increasing the container size by the + * number of elements inserted. + * + * Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of 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 MultiMap}. + * + * @param tuple Tuple represensts the {@link Pair} 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 element with an equivalent key in the {@link UniqueMap}. The + * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or + * false if an equivalent key already existed. + */ + insert(tuple: [L, U]): Pair, boolean>; + /** + * @inheritdoc + */ + insert(hint: MapIterator, pair: Pair): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; + /** + * @inheritdoc + */ + insert(hint: MapIterator, tuple: [L, U]): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; + /** + * @inheritdoc + */ + insert>>(first: InputIterator, last: InputIterator): void; + /** + * Insert or assign an element. + * + * Inserts an element or assigns to the current element if the key already exists. + * + * Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of an element already in the container, and + * if so, the element is assigned, returning an iterator to this existing element (if the function returns a + * value). + * + * For a similar container allowing for duplicate elements, see {@link MultiMap}. + * + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly + * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The + * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or + * false if an equivalent key already existed so the value is assigned. + */ + insert_or_assign(key: Key, value: T): Pair, boolean>; + /** + * Insert or assign an element. + * + * Inserts an element or assigns to the current element if the key already exists. + * + * Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of an element already in the container, and + * if so, the element is assigned, returning an iterator to this existing element (if the function returns a + * value). + * + * For a similar container allowing for duplicate elements, see {@link MultiMap}. + * + * @param hint Hint for the position where the element can be inserted. + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link UniqueMap}. + */ + insert_or_assign(hint: MapIterator, key: Key, value: T): MapIterator; + /** + * Insert or assign an element. + * + * Inserts an element or assigns to the current element if the key already exists. + * + * Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of an element already in the container, and + * if so, the element is assigned, returning an iterator to this existing element (if the function returns a + * value). + * + * For a similar container allowing for duplicate elements, see {@link MultiMap}. + * + * @param hint Hint for the position where the element can be inserted. + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link UniqueMap}. + */ + insert_or_assign(hint: MapReverseIterator, key: Key, value: T): MapReverseIterator; + /** + * @hidden + */ + private _Insert_or_assign_with_key_value(key, value); + /** + * @hidden + */ + private _Insert_or_assign_with_hint(hint, key, value); + /** + * Extract an element. + * + * Extracts the element pointed to by key and erases it from the {@link UniqueMap}. + * + * @param key Key value of the element whose mapped value is accessed. + * + * @return A {@link Pair} containing the value pointed to by key. + */ + extract(key: Key): Pair; + /** + * 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: MapIterator): MapIterator; + /** + * 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: MapReverseIterator): MapReverseIterator; + /** + * @hidden + */ + private _Extract_by_key(key); + /** + * @hidden + */ + private _Extract_by_iterator(it); + /** + * @hidden + */ + private _Extract_by_reverse_iterator(it); + /** + * Merge two maps. + * + * Attempts to extract each element in *source* and insert it into this container. If there's an element in this + * container with key equivalent to the key of an element from *source*, tnen that element is not extracted from + * the *source*. Otherwise, no element with same key exists in this container, then that element will be + * transfered from the *source* to this container. + * + * @param source A {@link MapContainer map container} to transfer the elements from. + */ + merge(source: MapContainer): void; + } +} +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; + /** + * 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; + /** + * 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); + /** + * Merge two sets. + * + * Attempts to extract each element in *source* and insert it into this container. If there's an element in this + * container with key equivalent to the key of an element from *source*, tnen that element is not extracted from + * the *source*. Otherwise, no element with same key exists in this container, then that element will be + * transfered from the *source* to this container. + * + * @param source A {@link SetContainer set container} to transfer the elements from. + */ + merge(source: SetContainer): void; + } +} +declare namespace std.Deque { + type iterator = DequeIterator; + type reverse_iterator = DequeReverseIterator; +} +declare namespace std { + /** + * Double ended queue. + * + * {@link Deque} (usually pronounced like "deck") is an irregular acronym of + * double-ended queue. Double-ended queues are sequence containers with dynamic sizes that can be + * expanded or contracted on both ends (either its front or its back). + * + * Specific libraries may implement deques in different ways, generally as some form of dynamic array. But in any + * case, they allow for the individual elements to be accessed directly through random access iterators, with storage + * handled automatically by expanding and contracting the container as needed. + * + * Therefore, they provide a functionality similar to vectors, but with efficient insertion and deletion of + * elements also at the beginning of the sequence, and not only at its end. But, unlike {@link Vector Vectors}, + * {@link Deque Deques} are not guaranteed to store all its elements in contiguous storage locations: accessing + * elements in a deque by offsetting a pointer to another element causes undefined behavior. + * + * Both {@link Vector}s and {@link Deque}s provide a very similar interface and can be used for similar purposes, + * but internally both work in quite different ways: While {@link Vector}s use a single array that needs to be + * occasionally reallocated for growth, the elements of a {@link Deque} can be scattered in different chunks of + * storage, with the container keeping the necessary information internally to provide direct access to any of its + * elements in constant time and with a uniform sequential interface (through iterators). Therefore, + * {@link Deque Deques} are a little more complex internally than {@link Vector}s, but this allows them to grow more + * efficiently under certain circumstances, especially with very long sequences, where reallocations become more + * expensive. + * + * For operations that involve frequent insertion or removals of elements at positions other than the beginning or + * the end, {@link Deque Deques} perform worse and have less consistent iterators and references than + * {@link List Lists}. + * + * + * + * + * + * ### Container properties + *
    + *
    Sequence
    + *
    Elements in sequence containers are ordered in a strict linear sequence. Individual elements + * are accessed by their position in this sequence.
    + * + *
    Dynamic array
    + *
    Generally implemented as a dynamic array, it allows direct access to any element in the + * sequence and provides relatively fast addition/removal of elements at the beginning or the end + * of the sequence.
    + *
    + * + * @param Type of the elements. + * + * @reference http://www.cplusplus.com/reference/deque/deque/ + * @author Jeongho Nam + */ + class Deque extends base.Container implements base.IArrayContainer, base.IDequeContainer { + /** + * @hidden + */ + private matrix_; + /** + * @hidden + */ + private size_; + /** + * @hidden + */ + private capacity_; + /** + * @hidden + */ + private begin_; + /** + * @hidden + */ + private end_; + /** + * @hidden + */ + private rend_; + /** + * Default Constructor. + * + * Constructs an empty container, with no elements. + */ + constructor(); + /** + * Initializer list Constructor. + * + * Constructs a container with a copy of each of the elements in array, in the same order. + * + * @param array An array containing elements to be copied and contained. + */ + constructor(items: Array); + /** + * Fill Constructor. + * + * Constructs a container with n elements. Each element is a copy of val (if provided). + * + * @param n Initial container size (i.e., the number of elements in the container at construction). + * @param val Value to fill the container with. Each of the n elements in the container is + * initialized to a copy of this value. + */ + constructor(size: number, val: T); + /** + * Copy Constructor. + * + * Constructs a container with a copy of each of the elements in container, in the same order. + * + * @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: Deque); + /** + * Range Constructor. + * + * Constructs a container with as many elements as the range (begin, end), with each + * element emplace-constructed from its corresponding element in that range, in the same order. + * + * @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); + /** + * @inheritdoc + */ + assign>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + assign(n: number, val: T): void; + /** + * Request a change in capacity. + * + * Requests that the {@link Deque container} {@link capacity} be at least enough to contain + * n elements. + * + * If n is greater than the current {@link Deque container} {@link capacity}, the + * function causes the {@link Deque container} to reallocate its storage increasing its + * {@link capacity} to n (or greater). + * + * In all other cases, the function call does not cause a reallocation and the + * {@link Deque container} {@link capacity} is not affected. + * + * This function has no effect on the {@link Deque container} {@link size} and cannot alter + * its elements. + * + * @param n Minimum {@link capacity} for the {@link Deque container}. + * Note that the resulting {@link capacity} may be equal or greater than n. + */ + reserve(capacity: number): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + size(): number; + /** + * @inheritdoc + */ + empty(): boolean; + /** + * Return size of allocated storage capacity. + * + * Returns the size of the storage space currently allocated for the {@link Deque container}, + * expressed in terms of elements. + * + * This {@link 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} 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} of a {@link Deque container} can be explicitly altered by calling member + * {@link Deque.reserve}. + * + * @return The size of the currently allocated storage capacity in the {@link Deque container}, + * measured in terms of the number elements it can hold. + */ + capacity(): number; + /** + * @inheritdoc + */ + front(): T; + /** + * @inheritdoc + */ + back(): T; + /** + * @inheritdoc + */ + begin(): DequeIterator; + /** + * @inheritdoc + */ + end(): DequeIterator; + /** + * @inheritdoc + */ + rbegin(): DequeReverseIterator; + /** + * @inheritdoc + */ + rend(): DequeReverseIterator; + /** + * @inheritdoc + */ + at(index: number): T; + /** + * @inheritdoc + */ + set(index: number, val: T): void; + /** + * @hidden + */ + private _Fetch_index(index); + /** + * @hidden + */ + private _Compute_col_size(capacity?); + /** + * @inheritdoc + */ + push(...items: T[]): number; + /** + * @inheritdoc + */ + push_front(val: T): void; + /** + * @inheritdoc + */ + push_back(val: T): void; + /** + * @inheritdoc + */ + pop_front(): void; + /** + * @inheritdoc + */ + pop_back(): void; + /** + * @inheritdoc + */ + insert(position: DequeIterator, val: T): DequeIterator; + /** + * @inheritdoc + */ + insert(position: DequeIterator, n: number, val: T): DequeIterator; + /** + * @inheritdoc + */ + insert>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; + /** + * @inheritdoc + */ + insert(position: DequeReverseIterator, val: T): DequeReverseIterator; + /** + * @inheritdoc + */ + insert(position: DequeReverseIterator, n: number, val: T): DequeReverseIterator; + /** + * @inheritdoc + */ + insert>(position: DequeReverseIterator, begin: InputIterator, end: InputIterator): DequeReverseIterator; + /** + * @hidden + */ + private _Insert_by_val(position, val); + /** + * @hidden + */ + private _Insert_by_repeating_val(position, n, val); + /** + * @hidden + */ + protected _Insert_by_range>(pos: DequeIterator, first: InputIterator, last: InputIterator): DequeIterator; + /** + * @hidden + */ + private _Insert_to_middle(pos, first, last); + /** + * @hidden + */ + private _Insert_to_end(first, last); + /** + * @hidden + */ + private _Try_expand_capacity(size); + /** + * @hidden + */ + private _Try_add_row_at_front(); + /** + * @hidden + */ + private _Try_add_row_at_back(); + /** + * @inheritdoc + */ + erase(position: DequeIterator): DequeIterator; + /** + * @inheritdoc + */ + erase(first: DequeIterator, last: DequeIterator): DequeIterator; + /** + * @inheritdoc + */ + erase(position: DequeReverseIterator): DequeReverseIterator; + /** + * @inheritdoc + */ + erase(first: DequeReverseIterator, last: DequeReverseIterator): DequeReverseIterator; + /** + * @hidden + */ + 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 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 Deque container}. + */ + swap(obj: Deque): void; + /** + * @inheritdoc + */ + swap(obj: base.Container): void; + /** + * @hidden + */ + private static readonly ROW_SIZE; + /** + * @hidden + */ + private static readonly MIN_CAPACITY; + /** + * @hidden + */ + private static readonly MAGNIFIER; + } +} +declare namespace std { + /** + * An iterator of {@link Deque}. + * + * + * + * + * @author Jeongho Nam + */ + class DequeIterator extends Iterator implements base.IArrayIterator { + /** + * @hidden + */ + private index_; + /** + * Construct from the source {@link Deque container}. + * + * #### Note + * Do not create the iterator directly, by yourself. + * + * Use {@link Deque.begin begin()}, {@link Deque.end end()} in {@link Deque container} instead. + * + * @param source The source {@link Deque container} to reference. + * @param index Sequence number of the element in the source {@link Deque}. + */ + constructor(source: Deque, index: number); + /** + * @inheritdoc + */ + source(): Deque; + /** + * @inheritdoc + */ + index(): number; + /** + * @inheritdoc + */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ + value: T; + /** + * @inheritdoc + */ + prev(): DequeIterator; + /** + * @inheritdoc + */ + next(): DequeIterator; + /** + * @inheritdoc + */ + advance(n: number): DequeIterator; + /** + * @inheritdoc + */ + equals(obj: DequeIterator): boolean; + /** + * @inheritdoc + */ + swap(obj: DequeIterator): void; + } +} +declare namespace std { + /** + * A reverse-iterator of Deque. + * + * + * + * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class DequeReverseIterator extends ReverseIterator, DequeIterator, 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); + /** + * @hidden + */ + protected _Create_neighbor(base: DequeIterator): DequeReverseIterator; + /** + * @inheritdoc + */ + index(): number; + /** + * @inheritdoc + */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ + value: T; + } +} +declare namespace std { + /** + * Function handling termination on exception + * + * Calls the current terminate handler. + * + * By default, the terminate handler calls abort. But this behavior can be redefined by calling + * {@link set_terminate}. + * + * This function is automatically called when no catch handler can be found for a thrown exception, + * or for some other exceptional circumstance that makes impossible to continue the exception handling process. + * + * This function is provided so that the terminate handler can be explicitly called by a program that needs to + * abnormally terminate, and works even if {@link set_terminate} has not been used to set a custom terminate handler + * (calling abort in this case). + */ + function terminate(): void; + /** + * Set terminate handler function. + * + * A terminate handler function is a function automatically called when the exception handling process has + * to be abandoned for some reason. This happens when no catch handler can be found for a thrown exception, or for + * some other exceptional circumstance that makes impossible to continue the exception handling process. + * + * Before this function is called by the program for the first time, the default behavior is to call abort. + * + * A program may explicitly call the current terminate handler function by calling {@link terminate}. + * + * @param f Function that takes no parameters and returns no value (void). + */ + function set_terminate(f: () => void): void; + /** + * Get terminate handler function. + * + * The terminate handler function is automatically called when no catch handler can be found + * for a thrown exception, or for some other exceptional circumstance that makes impossible to continue the exception + * handling process. + * + * If no such function has been set by a previous call to {@link set_terminate}, the function returns a + * null-pointer. + * + * @return If {@link set_terminate} has previously been called by the program, the function returns the current + * terminate handler function. Otherwise, it returns a null-pointer. + */ + function get_terminate(): () => void; + /** + * Standard exception class. + * + * Base class for standard exceptions. + * + * 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 + */ + class Exception { + /** + * @hidden + */ + private message_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + /** + * Get string identifying exception. + * + * Returns a string that may be used to identify the exception. + * + * The particular representation pointed by the returned value is implementation-defined. + * As a virtual function, derived classes may redefine this function so that specify value are + * returned. + */ + what(): string; + } + /** + * Logic error exception. + * + * This class defines the type of objects thrown as exceptions to report errors in the internal + * logical of the program, such as violation of logical preconditions or class invariants. + * + * These errors are presumably detectable before the program executes. + * + * It is used as a base class for several logical error exceptions. + * + * + * + * + * @reference http://www.cplusplus.com/reference/stdexcept/logic_error + * @author Jeongho Nam + */ + class LogicError extends Exception { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } + /** + * Domain error exception. + * + * This class defines the type of objects thrown as exceptions to report domain errors. + * + * Generally, the domain of a mathematical function is the subset of values that it is defined for. + * For example, the square root function is only defined for non-negative numbers. Thus, a negative number + * for such a function would qualify as a domain error. + * + * 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 + */ + class DomainError extends LogicError { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } + /** + * Invalid argument exception. + * + * This class defines the type of objects thrown as exceptions to report an invalid argument. + * + * 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 + */ + class InvalidArgument extends LogicError { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } + /** + * Length error exception. + * + * This class defines the type of objects thrown as exceptions to report a length error. + * + * 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 + */ + class LengthError extends LogicError { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } + /** + * Out-of-range exception. + * + * This class defines the type of objects thrown as exceptions to report an out-of-range error. + * + * It is a standard exception that can be thrown by programs. Some components of the standard library, + * 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 + */ + class OutOfRange extends LogicError { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } + /** + * Runtime error exception. + * + * This class defines the type of objects thrown as exceptions to report errors that can only be + * detected during runtime. + * + * It is used as a base class for several runtime error exceptions. + * + * + * + * + * @reference http://www.cplusplus.com/reference/stdexcept/runtime_error + * @author Jeongho Nam + */ + class RuntimeError extends Exception { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } + /** + * Overflow error exception. + * + * This class defines the type of objects thrown as exceptions to arithmetic overflow errors. + * + * 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 + */ + class OverflowError extends RuntimeError { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } + /** + * Underflow error exception. + * + * This class defines the type of objects thrown as exceptions to arithmetic underflow errors. + * + * 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 + */ + class UnderflowError extends RuntimeError { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } + /** + * Range error exception. + * + * This class defines the type of objects thrown as exceptions to report range errors in internal + * computations. + * + * 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 + */ + class RangeError extends RuntimeError { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } +} +declare namespace std { + /** + * Function object class for equality comparison. + * + * Binary function object class whose call returns whether its two arguments compare equal (as returned by + * operator ==). + * + * Generically, function objects are instances of a class with member function {@link IComparable.equal_to equal_to} + * defined. This member function allows the object to be used with the same syntax as a function call. + * + * @param x First element to compare. + * @param y Second element to compare. + * + * @return Whether the arguments are equal. + */ + function equal_to(x: T, y: T): boolean; + /** + * Function object class for non-equality comparison. + * + * Binary function object class whose call returns whether its two arguments compare not equal (as returned + * by operator operator!=). + * + * Generically, function objects are instances of a class with member function {@link IComparable.equal_to equal_to} + * defined. This member function allows the object to be used with the same syntax as a function call. + * + * @param x First element to compare. + * @param y Second element to compare. + * + * @return Whether the arguments are not equal. + */ + function not_equal_to(x: T, y: T): boolean; + /** + * Function for less-than inequality comparison. + * + * Binary function returns whether the its first argument compares less than the second. + * + * Generically, function objects are instances of a class with member function {@link IComparable.less less} + * defined. If an object doesn't have the method, then its own uid will be used to compare insteadly. + * This member function allows the object to be used with the same syntax as a function call. + * + * Objects of this class can be used on standard algorithms such as {@link sort sort()}, + * {@link merge merge()} or {@link TreeMap.lower_bound lower_bound()}. + * + * @param Type of arguments to compare by the function call. The type shall supporrt the operation + * operator<() or method {@link IComparable.less less}. + * + * @param x First element, the standard of comparison. + * @param y Second element compare with the first. + * + * @return Whether the first parameter is less than the second. + */ + function less(x: T, y: T): boolean; + /** + * Function object class for less-than-or-equal-to comparison. + * + * Binary function object class whose call returns whether the its first argument compares {@link less less than} or + * {@link equal_to equal to} the second (as returned by operator <=). + * + * Generically, function objects are instances of a class with member function {@link IComparable.less less} + * and {@link IComparable.equal_to equal_to} defined. This member function allows the object to be used with the same + * syntax as a function call. + * + * @param x First element, the standard of comparison. + * @param y Second element compare with the first. + * + * @return Whether the x is {@link less less than} or {@link equal_to equal to} the y. + */ + function less_equal(x: T, y: T): boolean; + /** + * Function for greater-than inequality comparison. + * + * Binary function returns whether the its first argument compares greater than the second. + * + * Generically, function objects are instances of a class with member function {@link less} and + * {@link equal_to equal_to()} defined. If an object doesn't have those methods, then its own uid will be used + * to compare insteadly. This member function allows the object to be used with the same syntax as a function + * call. + * + * Objects of this class can be used on standard algorithms such as {@link sort sort()}, + * {@link merge merge()} or {@link TreeMap.lower_bound lower_bound()}. + * + * @param Type of arguments to compare by the function call. The type shall supporrt the operation + * operator>() or method {@link IComparable.greater greater}. + * + * @return Whether the x is greater than the y. + */ + function greater(x: T, y: T): boolean; + /** + * Function object class for greater-than-or-equal-to comparison. + * + * Binary function object class whose call returns whether the its first argument compares + * {@link greater greater than} or {@link equal_to equal to} the second (as returned by operator >=). + * + * Generically, function objects are instances of a class with member function {@link IComparable.less less} + * defined. If an object doesn't have the method, then its own uid will be used to compare insteadly. + * This member function allows the object to be used with the same syntax as a function call. + * + * @param x First element, the standard of comparison. + * @param y Second element compare with the first. + * + * @return Whether the x is {@link greater greater than} or {@link equal_to equal to} the y. + */ + function greater_equal(x: T, y: T): boolean; + /** + * Logical AND function object class. + * + * Binary function object class whose call returns the result of the logical "and" operation between its two + * arguments (as returned by operator &&). + * + * Generically, function objects are instances of a class with member function operator() defined. This member + * function allows the object to be used with the same syntax as a function call. + * + * @param x First element. + * @param y Second element. + * + * @return Result of logical AND operation. + */ + function logical_and(x: T, y: T): boolean; + /** + * Logical OR function object class. + * + * Binary function object class whose call returns the result of the logical "or" operation between its two + * arguments (as returned by operator ||). + * + * Generically, function objects are instances of a class with member function operator() defined. This member + * function allows the object to be used with the same syntax as a function call. + * + * @param x First element. + * @param y Second element. + * + * @return Result of logical OR operation. + */ + function logical_or(x: T, y: T): boolean; + /** + * Logical NOT function object class. + * + * Unary function object class whose call returns the result of the logical "not" operation on its argument + * (as returned by operator !). + * + * Generically, function objects are instances of a class with member function operator() defined. This member + * function allows the object to be used with the same syntax as a function call. + * + * @param x Target element. + * + * @return Result of logical NOT operation. + */ + function logical_not(x: T): boolean; + /** + * Bitwise AND function object class. + * + * Binary function object class whose call returns the result of applying the bitwise "and" operation between + * its two arguments (as returned by operator &). + * + * @param x First element. + * @param y Second element. + * + * @return Result of bitwise AND operation. + */ + function bit_and(x: number, y: number): number; + /** + * Bitwise OR function object class. + * + * Binary function object class whose call returns the result of applying the bitwise "and" operation between + * its two arguments (as returned by operator &). + * + * @param x First element. + * @param y Second element. + * + * @return Result of bitwise OR operation. + */ + function bit_or(x: number, y: number): number; + /** + * Bitwise XOR function object class. + * + * Binary function object class whose call returns the result of applying the bitwise "exclusive or" + * operation between its two arguments (as returned by operator ^). + * + * @param x First element. + * @param y Second element. + * + * @return Result of bitwise XOR operation. + */ + function bit_xor(x: number, y: number): number; + /** + * Default hash function for number. + * + * Unary function that defines the default hash function used by the standard library. + * + * The functional call returns a hash value of its argument: A hash value is a value that depends solely on + * its argument, returning always the same value for the same argument (for a given execution of a program). The + * value returned shall have a small likelihood of being the same as the one returned for a different argument. + * + * + * @param val Value to be hashed. + * + * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. + */ + function hash(val: number): number; + /** + * Default hash function for string. + * + * Unary function that defines the default hash function used by the standard library. + * + * The functional call returns a hash value of its argument: A hash value is a value that depends solely on + * its argument, returning always the same value for the same argument (for a given execution of a program). The + * value returned shall have a small likelihood of being the same as the one returned for a different argument. + * + * @param str A string to be hashed. + * + * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. + */ + function hash(str: string): number; + /** + * Default hash function for Object. + * + * Unary function that defines the default hash function used by the standard library. + * + * The functional call returns a hash value of its argument: A hash value is a value that depends solely on + * its argument, returning always the same value for the same argument (for a given execution of a program). The + * value returned shall have a small likelihood of being the same as the one returned for a different argument. + * + * + * The default {@link hash} function of Object returns a value returned from {@link hash hash(number)} with + * an unique id of each Object. If you want to specify {@link hash} function of a specific class, then + * define a member function public hashCode(): number in the class. + * + * @param obj Object to be hashed. + * + * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. + */ + function hash(obj: Object): number; + /** + * Exchange contents of {@link IContainers containers}. + * + * The contents of container left are exchanged with those of right. Both container objects must have + * same type of elements (same template parameters), although sizes may differ. + * + * After the call to this member function, the elements in left are those which were in right before + * the call, and the elements of right are those which were in left. All iterators, references and + * pointers remain valid for the swapped objects. + * + * This is an overload of the generic algorithm swap that improves its performance by mutually transferring + * ownership over their assets to the other container (i.e., the containers exchange references to their data, without + * actually performing any element copy or movement): It behaves as if left. + * {@link Container.swap swap}(right) was called. + * + * @param left A {@link Container container} to swap its contents. + * @param right A {@link Container container} to swap its contents. + */ + function swap(left: base.Container, right: base.Container): void; + /** + * Exchange contents of queues. + * + * Exchanges the contents of left and right. + * + * @param left A {@link Queue} container of the same type. Size may differ. + * @param right A {@link Queue} container of the same type. Size may differ. + */ + function swap(left: Queue, right: Queue): void; + /** + * Exchange contents of {@link PriorityQueue PriorityQueues}. + * + * Exchanges the contents of left and right. + * + * @param left A {@link PriorityQueue} container of the same type. Size may differ. + * @param right A {@link PriorityQueue} container of the same type. Size may differ. + */ + function swap(left: PriorityQueue, right: PriorityQueue): void; + /** + * Exchange contents of {@link Stack Stacks}. + * + * Exchanges the contents of left and right. + * + * @param left A {@link Stack} container of the same type. Size may differ. + * @param right A {@link Stack} container of the same type. Size may differ. + */ + function swap(left: Stack, right: Stack): void; + /** + * Exchanges the contents of two {@link UniqueMap unique maps}. + * + * The contents of container left are exchanged with those of right. Both container objects must + * be of the same type (same template parameters), although sizes may differ. + * + * After the call to this member function, the elements in left are those which were in right + * before the call, and the elements of right are those which were in left. All iterators, references + * and pointers remain valid for the swapped objects. + * + * This is an overload of the generic algorithm swap that improves its performance by mutually transferring + * ownership over their assets to the other container (i.e., the containers exchange references to their data, + * without actually performing any element copy or movement): It behaves as if + * left.{@link UniqueMap.swap swap}(right) was called. + * + * @param left An {@link UniqueMap unique map} to swap its conents. + * @param right An {@link UniqueMap unique map} to swap its conents. + */ + function swap(left: base.UniqueMap, right: base.UniqueMap): void; + /** + * Exchanges the contents of two {@link MultiMap multi maps}. + * + * The contents of container left are exchanged with those of right. Both container objects must + * be of the same type (same template parameters), although sizes may differ. + * + * After the call to this member function, the elements in left are those which were in right + * before the call, and the elements of right are those which were in left. All iterators, references + * and pointers remain valid for the swapped objects. + * + * This is an overload of the generic algorithm swap that improves its performance by mutually transferring + * ownership over their assets to the other container (i.e., the containers exchange references to their data, + * without actually performing any element copy or movement): It behaves as if + * left.{@link MultiMap.swap swap}(right) was called. + * + * @param left A {@link MultiMap multi map} to swap its conents. + * @param right A {@link MultiMap multi map} to swap its conents. + */ + function swap(left: base.MultiMap, right: base.MultiMap): void; +} +declare namespace std { + /** + * Bind function arguments. + * + * Returns a function object based on fn, but with its arguments bound to args. + * + * Each argument may either be bound to a value or be a {@link placeholders placeholder}: + *
      + *
    • If bound to a value, calling the returned function object will always use that value as argument.
    • + *
    • + * If a {@link placeholders placeholder}, calling the returned function object forwards an argument passed to the + * call (the one whose order number is specified by the placeholder). + *
    • + *
    + * + * Calling the returned object returns the same type as fn. + * + * @param fn A function object, pointer to function or pointer to member. + * @param args List of arguments to bind: either values, or {@link placeholders}. + * + * @return A function object that, when called, calls fn with its arguments bound to args. If fn is + * a pointer to member, the first argument expected by the returned function is an object of the class fn + * is a member. + */ + function bind(fn: (...args: any[]) => Ret, ...args: any[]): (...args: any[]) => Ret; + /** + * Bind function arguments. + * + * Returns a function object based on fn, but with its arguments bound to args. + * + * Each argument may either be bound to a value or be a {@link placeholders placeholder}: + *
      + *
    • If bound to a value, calling the returned function object will always use that value as argument.
    • + *
    • + * If a {@link placeholders placeholder}, calling the returned function object forwards an argument passed to the + * call (the one whose order number is specified by the placeholder). + *
    • + *
    + * + * Calling the returned object returns the same type as fn. + * + * @param fn A function object, pointer to function or pointer to member. + * @param thisArg This argument, owner object of the member method fn. + * @param args List of arguments to bind: either values, or {@link placeholders}. + * + * @return A function object that, when called, calls fn with its arguments bound to args. If fn is + * a pointer to member, the first argument expected by the returned function is an object of the class fn + * is a member. + */ + function bind(fn: (...args: any[]) => Ret, thisArg: T, ...args: any[]): (...args: any[]) => Ret; +} +/** + * Bind argument placeholders. + * + * This namespace declares an unspecified number of objects: _1, _2, _3, ...
    , which are + * used to specify placeholders in calls to function {@link bind}. + * + * When the function object returned by bind is called, an argument with placeholder {@link _1} is replaced by the + * first argument in the call, {@link _2} is replaced by the second argument in the call, and so on... For example: + * + * + * let vec: Vector = new Vector(); + * + * let bind = bind(Vector.insert, _1, vec.end(), _2, _3); + * bind.apply(vec, 5, 1); // vec.insert(vec.end(), 5, 1); + * // [1, 1, 1, 1, 1] + * + * + * When a call to {@link bind} is used as a subexpression in another call to bind, the {@link placeholders} + * are relative to the outermost {@link bind} expression. + * + * @reference http://www.cplusplus.com/reference/functional/placeholders/ + * @author Jeongho Nam + */ +declare namespace std.placeholders { + /** + * @hidden + */ + class PlaceHolder { + private index_; + constructor(index: number); + index(): number; + } + /** + * Replaced by the first argument in the function call. + */ + const _1: PlaceHolder; + /** + * Replaced by the second argument in the function call. + */ + const _2: PlaceHolder; + /** + * Replaced by the third argument in the function call. + */ + const _3: PlaceHolder; + const _4: PlaceHolder; + const _5: PlaceHolder; + const _6: PlaceHolder; + const _7: PlaceHolder; + const _8: PlaceHolder; + const _9: PlaceHolder; + const _10: PlaceHolder; + const _11: PlaceHolder; + const _12: PlaceHolder; + const _13: PlaceHolder; + const _14: PlaceHolder; + const _15: PlaceHolder; + const _16: PlaceHolder; + const _17: PlaceHolder; + const _18: PlaceHolder; + const _19: PlaceHolder; + const _20: PlaceHolder; +} +declare namespace std.HashMap { + type iterator = MapIterator; + type reverse_iterator = MapReverseIterator; +} +declare namespace std { + /** + * Hashed, unordered map. + * + * {@link HashMap}s are associative containers that store elements formed by the combination of a key value + * and a mapped value, and which allows for fast retrieval of individual elements based on their keys. + * + * In an {@link HashMap}, 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 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). + * + * {@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 + *
    + *
    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.
    + * + *
    Map
    + *
    Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value.
    + * + *
    Unique keys
    + *
    No two elements in the container can have equivalent keys.
    + *
    + * + * @param Type of the key values. + * Each element in an {@link HashMap} is uniquely identified by its key value. + * @param Type of the mapped value. + * Each element in an {@link HashMap} is used to store some data as its mapped value. + * + * @reference http://www.cplusplus.com/reference/unordered_map/unordered_map + * @author Jeongho Nam + */ + class HashMap extends base.UniqueMap implements base.IHashMap { + /** + * @hidden + */ + private hash_buckets_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + 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 + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: Key): MapIterator; + /** + * @inheritdoc + */ + begin(): MapIterator; + /** + * @inheritdoc + */ + begin(index: number): MapIterator; + /** + * @inheritdoc + */ + end(): MapIterator; + /** + * @inheritdoc + */ + end(index: number): MapIterator; + /** + * @inheritdoc + */ + rbegin(): MapReverseIterator; + /** + * @inheritdoc + */ + rbegin(index: number): MapReverseIterator; + /** + * @inheritdoc + */ + rend(): MapReverseIterator; + /** + * @inheritdoc + */ + rend(index: number): MapReverseIterator; + /** + * @inheritdoc + */ + bucket_count(): number; + /** + * @inheritdoc + */ + bucket_size(index: number): number; + /** + * @inheritdoc + */ + max_load_factor(): number; + /** + * @inheritdoc + */ + max_load_factor(z: number): void; + /** + * @inheritdoc + */ + bucket(key: Key): number; + /** + * @inheritdoc + */ + reserve(n: number): void; + /** + * @inheritdoc + */ + rehash(n: number): void; + /** + * @hidden + */ + protected _Insert_by_pair(pair: Pair): any; + /** + * @hidden + */ + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * @hidden + */ + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; + /** + * @hidden + */ + protected _Handle_insert(first: MapIterator, last: MapIterator): void; + /** + * @hidden + */ + 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 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.Container>): void; + } +} +declare namespace std.HashMultiMap { + type iterator = MapIterator; + type reverse_iterator = MapReverseIterator; +} +declare namespace std { + /** + * Hashed, unordered Multimap. + * + * {@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 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 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). + * + * 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 + *
    + *
    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.
    + * + *
    Map
    + *
    Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value.
    + * + *
    Multiple equivalent keys
    + *
    The container can hold multiple elements with equivalent keys.
    + *
    + * + * @param Type of the key values. + * Each element in an {@link HashMultiMap} is identified by a key value. + * @param Type of the 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 + */ + class HashMultiMap extends base.MultiMap { + /** + * @hidden + */ + private hash_buckets_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + 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 + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: Key): MapIterator; + /** + * @inheritdoc + */ + count(key: Key): number; + /** + * @inheritdoc + */ + begin(): MapIterator; + /** + * @inheritdoc + */ + begin(index: number): MapIterator; + /** + * @inheritdoc + */ + end(): MapIterator; + /** + * @inheritdoc + */ + end(index: number): MapIterator; + /** + * @inheritdoc + */ + rbegin(): MapReverseIterator; + /** + * @inheritdoc + */ + rbegin(index: number): MapReverseIterator; + /** + * @inheritdoc + */ + rend(): MapReverseIterator; + /** + * @inheritdoc + */ + rend(index: number): MapReverseIterator; + /** + * @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: Key): number; + /** + * @inheritdoc + */ + reserve(n: number): void; + /** + * @inheritdoc + */ + rehash(n: number): void; + /** + * @hidden + */ + protected _Insert_by_pair(pair: Pair): any; + /** + * @hidden + */ + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * @hidden + */ + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; + /** + * @hidden + */ + protected _Handle_insert(first: MapIterator, last: MapIterator): void; + /** + * @hidden + */ + 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 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.Container>): void; + } +} +declare namespace std.HashMultiSet { + type iterator = SetIterator; + type reverse_iterator = SetReverseIterator; +} +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 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 + * identify it. Keys are immutable, therefore, the elements in an {@link HashMultiSet} cannot be + * modified once in the container - they can be inserted and removed, though. + * + * Internally, the elements in the {@link HashMultiSet} are not sorted in any particular, 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). + * + * 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 + *
    + *
    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.
    + * + *
    Multiple equivalent keys
    + *
    The container can hold multiple elements with equivalent keys.
    + *
    + * + * @param Type of the elements. + * Each element in an {@link UnorderedMultiSet} is also identified by this value.. + * + * @reference http://www.cplusplus.com/reference/unordered_set/unordered_multiset + * @author Jeongho Nam + */ + class HashMultiSet extends base.MultiSet { + /** + * @hidden + */ + private hash_buckets_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + constructor(items: T[]); + /** + * Copy Constructor. + */ + constructor(container: HashMultiSet); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator, end: Iterator); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: T): SetIterator; + /** + * @inheritdoc + */ + count(key: T): number; + /** + * @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; + /** + * @hidden + */ + protected _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @hidden + */ + 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 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.Container): void; + } +} +declare namespace std.HashSet { + type iterator = SetIterator; + type reverse_iterator = 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 implements base.IHashSet { + /** + * @hidden + */ + private hash_buckets_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + constructor(items: T[]); + /** + * Copy Constructor. + */ + constructor(container: HashSet); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator, end: Iterator); + /** + * @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; + /** + * @hidden + */ + protected _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @hidden + */ + 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 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.Container): void; + } +} +declare namespace std { + /** + * Comparable instance. + * + * {@link IComparable} is a common interface for objects who can compare each other. + * + * @reference https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html + * @author Jeongho Nam + */ + interface IComparable extends Object { + /** + * Indicates whether some other object is "equal to" this one. + * + * The {@link equal_to} method implements an equivalence relation on non-null object references: + * + *
      + *
    • + * It is reflexive: for any non-null reference value x, x.equal_to(x) + * should return true. + *
    • + *
    • + * It is symmetric: for any non-null reference values x and y, + * x.equal_to(y) should return true if and only if y.equal_to(x) + * returns true.
    • + *
    • + * It is transitive: for any non-null reference values x, y, and + * z, if x.equal_to(y) returns true and y.equal_to(z) + * returns true, then x.equal_to(z) should return true. + *
    • + *
    • + * It is consistent: for any non-null reference values x and y, multiple + * invocations of x.equal_to(y) consistently return true or consistently return + * false, provided no information used in equal_to comparisons on the objects is modified. + *
    • + *
    • + * For any non-null reference value x, x.equal_to(null) should return + * false. + *
    • + *
    + * + * The {@link equal_to} method for interface {@link IComparable} implements the most discriminating possible + * equivalence relation on objects; that is, for any non-null reference values x and + * y, this method returns true if and only if x and y + * refer to the same object (x == y has the value true). + * + * Note that it is generally necessary to override the {@link hash_code} method whenever this method is + * overridden, so as to maintain the general contract for the {@link hash_code} method, which states that + * equal objects must have equal hash codes. + * + * - {@link IComparable.equal_to} is called by {@link equal_to}. + * + * @param obj the reference object with which to compare. + * + * @return true if this object is the same as the obj argument; false otherwise. + */ + equals(obj: T): boolean; + /** + * Less-than inequality comparison. + * + * Binary method returns whether the the instance compares less than the obj. + * + *
      + *
    • + * {@link IComparable.less} is called by {@link less}. Also, this method can be used on standard + * algorithms such as {@link sort sort()}, {@link merge merge()} or + * {@link TreeMap.lower_bound lower_bound()}. + *
    • + *
    + * + * @param obj the reference object with which to compare. + * + * @return Whether the first parameter is less than the second. + */ + less(obj: T): boolean; + /** + * Issue a hash code. + * + * Returns a hash code value for the object. This method is supported for the benefit of hash tables such + * as those provided by hash containers; {@link HashSet}, {@link HashMap}, {@link MultiHashSet} and + * {@link MultiHashMap}. + * + * As much as is reasonably practical, the {@link hash_code} method defined by interface + * {@link IComparable} does return distinct integers for distinct objects. (This is typically implemented by + * converting the internal address of the object into an integer, but this implementation technique is not + * required by the JavaScript programming language.) + * + *
      + *
    • + * {@link IComparable.hash_code} is called by {@link hash_code}. If you want to keep basically + * provided hash function, then returns {@link Hash.code}; return Hash.code(this); + *
    • + *
    + * + * @return An hash code who represents the object. + */ + hashCode?(): number; + } +} +declare namespace std.List { + type iterator = ListIterator; + type reverse_iterator = ListReverseIterator; +} +declare namespace std { + /** + * Doubly linked list. + * + * {@link List}s are sequence containers that allow constant time insert and erase operations anywhere within the + * sequence, and iteration in both directions. + * + * List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they + * contain in different and unrelated storage locations. The ordering is kept internally by the association to each + * element of a link to the element preceding it and a link to the element following it. + * + * Compared to other base standard sequence containers (array, vector and deque), lists perform generally better + * in inserting, extracting and moving elements in any position within the container for which an iterator has already + * been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms. + * + * The main drawback of lists and forward_lists compared to these other sequence containers is that they lack + * direct access to the elements by their position; For example, to access the sixth element in a list, one has to + * iterate from a known position (like the beginning or the end) to that position, which takes linear time in the + * 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 + *
    + *
    Sequence
    + *
    Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by + * their position in this sequence.
    + * + *
    Doubly-linked list
    + *
    Each element keeps information on how to locate the next and the previous elements, allowing constant time + * insert and erase operations before or after a specific element (even of entire ranges), but no direct random + * access.
    + *
    + * + * @param Type of the elements. + * + * @reference http://www.cplusplus.com/reference/list/list/ + * @author Jeongho Nam + */ + class List extends base._ListContainer> { + private rend_; + /** + * Default Constructor. + * + * Constructs an empty container, with no elements. + */ + constructor(); + /** + * Initializer list Constructor. + * + * Constructs a container with a copy of each of the elements in array, in the same order. + * + * @param array An array containing elements to be copied and contained. + */ + constructor(items: Array); + /** + * Fill Constructor. + * + * Constructs a container with n elements. Each element is a copy of val (if provided). + * + * @param n Initial container size (i.e., the number of elements in the container at construction). + * @param val Value to fill the container with. Each of the n elements in the container is + * initialized to a copy of this value. + */ + constructor(size: number, val: T); + /** + * Copy Constructor. + * + * Constructs a container with a copy of each of the elements in container, in the same order. + * + * @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: List); + /** + * Range Constructor. + * + * Constructs a container with as many elements as the range (begin, end), with each + * element emplace-constructed from its corresponding element in that range, in the same order. + * + * @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); + /** + * @hidden + */ + protected _Create_iterator(prev: ListIterator, next: ListIterator, val: T): ListIterator; + /** + * @hidden + */ + protected _Set_begin(it: ListIterator): void; + /** + * @inheritdoc + */ + assign(n: number, val: T): void; + /** + * @inheritdoc + */ + assign>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + rbegin(): ListReverseIterator; + /** + * @inheritdoc + */ + rend(): ListReverseIterator; + /** + * @inheritdoc + */ + front(): T; + /** + * @inheritdoc + */ + back(): T; + /** + * Insert an element. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new element is inserted. + * {@link iterator}> is a member type, defined as a + * {@link ListIterator bidirectional iterator} type that points to elements. + * @param val Value to be inserted as an element. + * + * @return An iterator that points to the newly inserted element; val. + */ + insert(position: ListIterator, val: T): ListIterator; + /** + * Insert elements by repeated filling. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new elements are inserted. The {@link iterator} is a + * member type, defined as a {@link ListIterator bidirectional iterator} type that points to + * elements. + * @param size Number of elements to insert. + * @param val Value to be inserted as an element. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert(position: ListIterator, size: number, val: T): ListIterator; + /** + * Insert elements by range iterators. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new elements are inserted. The {@link iterator} is a + * member type, defined as a {@link ListIterator bidirectional iterator} type that points to + * elements. + * @param begin An iterator specifying range of the begining element. + * @param end An iterator specifying range of the ending element. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert>(position: ListIterator, begin: InputIterator, end: InputIterator): ListIterator; + /** + * Insert an element. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new element is inserted. + * {@link iterator}> is a member type, defined as a + * {@link ListReverseIterator bidirectional iterator} type that points to elements. + * @param val Value to be inserted as an element. + * + * @return An iterator that points to the newly inserted element; val. + */ + insert(position: ListReverseIterator, val: T): ListReverseIterator; + /** + * Insert elements by repeated filling. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new elements are inserted. The {@link iterator} is a + * member type, defined as a {@link ListReverseIterator bidirectional iterator} type that points to + * elements. + * @param size Number of elements to insert. + * @param val Value to be inserted as an element. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert(position: ListReverseIterator, size: number, val: T): ListReverseIterator; + /** + * Insert elements by range iterators. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new elements are inserted. The {@link iterator} is a + * member type, defined as a {@link ListReverseIterator bidirectional iterator} type that points to + * elements. + * @param begin An iterator specifying range of the begining element. + * @param end An iterator specifying range of the ending element. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert>(position: ListReverseIterator, begin: InputIterator, end: InputIterator): ListReverseIterator; + /** + * Erase an element. + * + * Removes from the {@link List} either a single element; position. + * + * This effectively reduces the container size by the number of element removed. + * + * Unlike other standard sequence containers, {@link List} objects are specifically designed to be + * efficient inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Iterator pointing to a single element to be removed from the {@link List}. + * + * @return An iterator pointing to the element that followed the last element erased by the function call. + * This is the {@link end end()} if the operation erased the last element in the sequence. + */ + erase(position: ListIterator): ListIterator; + /** + * Erase elements. + * + * Removes from the {@link List} container a range of elements. + * + * This effectively reduces the container {@link size} by the number of elements removed. + * + * Unlike other standard sequence containers, {@link List} objects are specifically designed to be + * efficient inserting and removing elements in any position, even in the middle of the sequence. + * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + * + * @return An iterator pointing to the element that followed the last element erased by the function call. + * This is the {@link end end()} if the operation erased the last element in the sequence. + */ + erase(begin: ListIterator, end: ListIterator): ListIterator; + /** + * Erase an element. + * + * Removes from the {@link List} either a single element; position. + * + * This effectively reduces the container size by the number of element removed. + * + * Unlike other standard sequence containers, {@link List} objects are specifically designed to be + * efficient inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Iterator pointing to a single element to be removed from the {@link List}. + * + * @return An iterator pointing to the element that followed the last element erased by the function call. + * This is the {@link rend rend()} if the operation erased the last element in the sequence. + */ + erase(position: ListReverseIterator): ListReverseIterator; + /** + * Erase elements. + * + * Removes from the {@link List} container a range of elements. + * + * This effectively reduces the container {@link size} by the number of elements removed. + * + * Unlike other standard sequence containers, {@link List} objects are specifically designed to be + * efficient inserting and removing elements in any position, even in the middle of the sequence. + * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + * + * @return An iterator pointing to the element that followed the last element erased by the function call. + * This is the {@link rend rend()} if the operation erased the last element in the sequence. + */ + erase(begin: ListReverseIterator, end: ListReverseIterator): ListReverseIterator; + /** + * Remove duplicate values. + * + * Removes all but the first element from every consecutive group of equal elements in the + * + * Notice that an element is only removed from the {@link List} container if it compares equal to the + * element immediately preceding it. Thus, this function is especially useful for sorted lists. + */ + unique(): void; + /** + * Remove duplicate values. + * + * Removes all but the first element from every consecutive group of equal elements in the + * + * The argument binary_pred is a specific comparison function that determine the uniqueness + * of an element. In fact, any behavior can be implemented (and not only an equality comparison), but notice + * that the function will call binary_pred(it.value, it.prev().value) for all pairs of elements + * (where it is an iterator to an element, starting from the second) and remove it + * from the {@link List} if the predicate returns true. + * + * Notice that an element is only removed from the {@link List} container if it compares equal to the + * element immediately preceding it. Thus, this function is especially useful for sorted lists. + * + * @param binary_pred Binary predicate that, taking two values of the same type than those contained in the + * {@link List}, returns true to remove the element passed as first argument + * from the container, and false otherwise. This shall be a function pointer + * or a function object. + */ + unique(binary_pred: (left: T, right: T) => boolean): void; + /** + * Remove elements with specific value. + * + * Removes from the container all the elements that compare equal to val. This calls the + * destructor of these objects and reduces the container {@link size} by the number of elements removed. + * + * Unlike member function {@link List.erase}, which erases elements by their position (using an + * iterator), this function ({@link List.remove}) removes elements by their value. + * + * A similar function, {@link List.remove_if}, exists, which allows for a condition other than an + * equality comparison to determine whether an element is removed. + * + * @param val Value of the elements to be removed. + */ + remove(val: T): void; + /** + * Remove elements fulfilling condition. + * + * Removes from the container all the elements for which pred returns true. This + * calls the destructor of these objects and reduces the container {@link size} by the number of elements + * removed. + * + * The function calls pred(it.value) for each element (where it is an iterator + * to that element). Any of the elements in the list for which this returns true, are removed + * from the + * + * @param pred Unary predicate that, taking a value of the same type as those contained in the forward_list + * object, returns true for those values to be removed from the container, and + * false for those remaining. This can either be a function pointer or a function + * object. + */ + remove_if(pred: (val: T) => boolean): void; + /** + * Merge sorted {@link List Lists}. + * + * Merges obj into the {@link List} by transferring all of its elements at their respective + * ordered positions into the container (both containers shall already be ordered). + * + * + * This effectively removes all the elements in obj (which becomes {@link empty}), and inserts + * them into their ordered position within container (which expands in {@link size} by the number of elements + * transferred). The operation is performed without constructing nor destroying any element: they are + * transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type supports + * move-construction or not. + * + * This function requires that the {@link List} containers have their elements already ordered by value + * ({@link less}) before the call. For an alternative on unordered {@link List Lists}, see + * {@link List.splice}. + * + * Assuming such ordering, each element of obj is inserted at the position that corresponds to its + * value according to the strict weak ordering defined by {@link less}. The resulting order of equivalent + * elements is stable (i.e., equivalent elements preserve the relative order they had before the call, and + * existing elements precede those equivalent inserted from obj). + * + * The function does nothing if this == obj. + * + * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). + * Note that this function modifies obj no matter whether an lvalue or rvalue reference is + * passed. + */ + merge(obj: List): void; + /** + * Merge sorted {@link List Lists}. + * + * Merges obj into the {@link List} by transferring all of its elements at their respective + * ordered positions into the container (both containers shall already be ordered). + * + * + * This effectively removes all the elements in obj (which becomes {@link empty}), and inserts + * them into their ordered position within container (which expands in {@link size} by the number of elements + * transferred). The operation is performed without constructing nor destroying any element: they are + * transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type supports + * move-construction or not. + * + * The argument compare is a specific predicate to perform the comparison operation between + * elements. This comparison shall produce a strict weak ordering of the elements (i.e., a consistent + * transitive comparison, without considering its reflexiveness). + * + * This function requires that the {@link List} containers have their elements already ordered by + * compare before the call. For an alternative on unordered {@link List Lists}, see + * {@link List.splice}. + * + * Assuming such ordering, each element of obj is inserted at the position that corresponds to its + * value according to the strict weak ordering defined by compare. The resulting order of equivalent + * elements is stable (i.e., equivalent elements preserve the relative order they had before the call, and + * existing elements precede those equivalent inserted from obj). + * + * The function does nothing if this == obj. + * + * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). + * Note that this function modifies obj no matter whether an lvalue or rvalue reference is + * passed. + * @param compare Binary predicate that, taking two values of the same type than those contained in the + * {@link list}, returns true if the first argument is considered to go before + * the second in the strict weak ordering it defines, and false otherwise. + * This shall be a function pointer or a function object. + */ + merge(obj: List, compare: (left: T, right: T) => boolean): void; + /** + * Transfer elements from {@link List} to {@link List}. + * + * Transfers elements from obj into the container, inserting them at position. + * + * This effectively inserts all elements into the container and removes them from obj, altering + * the sizes of both containers. The operation does not involve the construction or destruction of any + * element. They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the + * value_type supports move-construction or not. + * + * This first version (1) transfers all the elements of obj into the + * + * @param position Position within the container where the elements of obj are inserted. + * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). + */ + splice(position: ListIterator, obj: List): void; + /** + * Transfer an element from {@link List} to {@link List}. + * + * Transfers an element from obj, which is pointed by an {@link ListIterator iterator} it, + * into the container, inserting the element at specified position. + * + * This effectively inserts an element into the container and removes it from obj, altering the + * sizes of both containers. The operation does not involve the construction or destruction of any element. + * They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type + * supports move-construction or not. + * + * This second version (2) transfers only the element pointed by it from obj into the + * + * + * @param position Position within the container where the element of obj is inserted. + * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). + * This parameter may be this if position points to an element not actually + * being spliced. + * @param it {@link ListIterator Iterator} to an element in obj. Only this single element is + * transferred. + */ + splice(position: ListIterator, obj: List, it: ListIterator): void; + /** + * Transfer elements from {@link List} to {@link List}. + * + * Transfers elements from obj into the container, inserting them at position. + * + * This effectively inserts those elements into the container and removes them from obj, altering + * the sizes of both containers. The operation does not involve the construction or destruction of any + * element. They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the + * value_type supports move-construction or not. + * + * This third version (3) transfers the range [begin, end) from obj into the + * + * + * @param position Position within the container where the elements of obj are inserted. + * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). + * This parameter may be this if position points to an element not actually + * being spliced. + * @param begin {@link ListIterator An Iterator} specifying initial position of a range of elements in + * obj. Transfers the elements in the range [begin, end) to + * position. + * @param end {@link ListIterator An Iterator} specifying final position of a range of elements in + * obj. Transfers the elements in the range [begin, end) to + * position. Notice that the range includes all the elements between begin and + * end, including the element pointed by begin but not the one pointed by end. + */ + splice(position: ListIterator, obj: List, begin: ListIterator, end: ListIterator): void; + /** + * Sort elements in + * + * Sorts the elements in the {@link List}, altering their position within the + * + * The sorting is performed by applying an algorithm that uses {@link less}. This comparison shall + * produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without + * considering its reflexiveness). + * + * The resulting order of equivalent elements is stable: i.e., equivalent elements preserve the relative + * order they had before the call. + * + * The entire operation does not involve the construction, destruction or copy of any element object. + * Elements are moved within the + */ + sort(): void; + /** + * Sort elements in + * + * Sorts the elements in the {@link List}, altering their position within the + * + * The sorting is performed by applying an algorithm that uses compare. This comparison shall + * produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without + * considering its reflexiveness). + * + * The resulting order of equivalent elements is stable: i.e., equivalent elements preserve the relative + * order they had before the call. + * + * The entire operation does not involve the construction, destruction or copy of any element object. + * Elements are moved within the + * + * @param compare Binary predicate that, taking two values of the same type of those contained in the + * {@link List}, returns true if the first argument goes before the second + * argument in the strict weak ordering it defines, and false otherwise. This + * shall be a function pointer or a function object. + */ + sort(compare: (left: T, right: T) => boolean): void; + /** + * @hidden + */ + private _Quick_sort(first, last, compare); + /** + * @hidden + */ + private _Quick_sort_partition(first, last, compare); + /** + * Reverse the order of elements. + * + * Reverses the order of the elements in the list container. + */ + reverse(): void; + /** + * 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 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 List container}. + */ + swap(obj: List): void; + /** + * @inheritdoc + */ + swap(obj: base.Container): void; + } +} +declare namespace std { + /** + * An iterator, node of a List. + * + * + * + * + * @author Jeongho Nam + */ + class ListIterator extends base._ListIteratorBase { + /** + * Initializer Constructor. + * + * #### Note + * Do not create the iterator directly, by yourself. + * + * Use {@link List.begin begin()}, {@link List.end end()} in {@link List container} instead. + * + * @param source The source {@link List container} to reference. + * @param prev A refenrece of previous node ({@link ListIterator iterator}). + * @param next A refenrece of next node ({@link ListIterator iterator}). + * @param value Value to be stored in the node (iterator). + */ + constructor(source: List, prev: ListIterator, next: ListIterator, value: T); + /** + * @inheritdoc + */ + source(): List; + /** + * @inheritdoc + */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ + value: T; + /** + * @inheritdoc + */ + prev(): ListIterator; + /** + * @inheritdoc + */ + next(): ListIterator; + /** + * @inheritdoc + */ + advance(step: number): ListIterator; + /** + * @inheritdoc + */ + equals(obj: ListIterator): boolean; + /** + * @inheritdoc + */ + swap(obj: ListIterator): void; + } +} +declare namespace std { + /** + * A reverse-iterator of List. + * + * + * + * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class ListReverseIterator extends ReverseIterator, ListIterator, ListReverseIterator> implements base.ILinearIterator { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ + constructor(base: ListIterator); + /** + * @hidden + */ + protected _Create_neighbor(base: ListIterator): ListReverseIterator; + /** + * @inheritdoc + */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ + value: T; + } +} +declare namespace std.Vector { + type iterator = VectorIterator; + type reverse_iterator = VectorReverseIterator; +} +declare namespace std { + /** + * Vector, the dynamic array. + * + * {@link Vector}s are sequence containers representing arrays that can change in size. + * + * Just like arrays, {@link Vector}s use contiguous storage locations for their elements, which means that + * their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently + * as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled + * automatically by the container. + * + * Internally, {@link Vector}s use a dynamically allocated array to store their elements. This array may need + * to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new + * array and moving all elements to it. This is a relatively expensive task in terms of processing time, and + * thus, {@link Vector}s do not reallocate each time an element is added to the container. + * + * Compared to the other dynamic sequence containers ({@link Deque}s, {@link List}s), {@link Vector Vectors} + * are very efficient accessing its elements (just like arrays) and relatively efficient adding or removing + * elements from its end. For operations that involve inserting or removing elements at positions other than the + * end, they perform worse than the others, and have less consistent iterators and references than {@link List}s. + * + * + * + * + * + * ### Container properties + *
    + *
    Sequence
    + *
    + * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are + * accessed by their position in this sequence. + *
    + * + *
    Dynamic array
    + *
    + * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides + * relatively fast addition/removal of elements at the end of the sequence. + *
    + *
    + * + * @param Type of the elements. + * + * @reference http://www.cplusplus.com/reference/vector/vector + * @author Jeongho Nam + */ + class Vector extends base.Container implements base.IArrayContainer { + /** + * @hidden + */ + private data_; + /** + * @hidden + */ + private begin_; + /** + * @hidden + */ + private end_; + /** + * @hidden + */ + private rend_; + /** + * Default Constructor. + * + * Constructs an empty container, with no elements. + */ + constructor(); + /** + * @inheritdoc + */ + constructor(array: Array); + /** + * Initializer list Constructor. + * + * Constructs a container with a copy of each of the elements in array, in the same order. + * + * @param array An array containing elements to be copied and contained. + */ + constructor(n: number); + /** + * Fill Constructor. + * + * Constructs a container with n elements. Each element is a copy of val (if provided). + * + * @param n Initial container size (i.e., the number of elements in the container at construction). + * @param val Value to fill the container with. Each of the n elements in the container is + * initialized to a copy of this value. + */ + constructor(n: number, val: T); + /** + * Copy Constructor. + * + * Constructs a container with a copy of each of the elements in container, in the same order. + * + * @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: Vector); + /** + * Range Constructor. + * + * Constructs a container with as many elements as the range (begin, end), with each + * element emplace-constructed from its corresponding element in that range, in the same order. + * + * @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); + /** + * @inheritdoc + */ + assign>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + assign(n: number, val: T): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + begin(): VectorIterator; + /** + * @inheritdoc + */ + end(): VectorIterator; + /** + * @inheritdoc + */ + rbegin(): VectorReverseIterator; + /** + * @inheritdoc + */ + rend(): VectorReverseIterator; + /** + * @inheritdoc + */ + size(): number; + /** + * @inheritdoc + */ + empty(): boolean; + /** + * @inheritdoc + */ + at(index: number): T; + /** + * @inheritdoc + */ + set(index: number, val: T): T; + /** + * @inheritdoc + */ + front(): T; + /** + * @inheritdoc + */ + back(): T; + /** + * Access data. + * + * Returns a direct array which is used internally by the {@link vector} to store its owned elements. + * + * @returns An array. + */ + data(): Array; + /** + * @inheritdoc + */ + push(...items: T[]): number; + /** + * @inheritdoc + */ + push_back(val: T): void; + /** + * Insert an element. + * + * The {@link Vector} is extended by inserting new element before the element at the specified + * position, effectively increasing the container size by one. + * + * Because {@link Vector}s use an Array as their underlying storage, inserting element in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to its new position. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Position in the {@link Vector} where the new element is inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param val Value to be copied to the inserted element. + * + * @return An iterator that points to the newly inserted element. + */ + insert(position: VectorIterator, val: T): VectorIterator; + /** + * Insert elements by repeated filling. + * + * The {@link Vector} is extended by inserting new elements before the element at the specified + * position, effectively increasing the container size by the number of elements inserted. + * + * Because {@link Vector}s use an Array as their underlying storage, inserting elements in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to their new positions. This is generally an inefficient operation compared to the + * one performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Position in the {@link Vector} where the new elements are inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param n Number of elements to insert. Each element is initialized to a copy of val. + * @param val Value to be copied (or moved) to the inserted elements. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert(position: VectorIterator, n: number, val: T): VectorIterator; + /** + * Insert elements by range iterators. + * + * The {@link Vector} is extended by inserting new elements before the element at the specified + * position, effectively increasing the container size by the number of elements inserted by range + * iterators. + * + * Because {@link Vector}s use an Array as their underlying storage, inserting elements in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to their new positions. This is generally an inefficient operation compared to the + * one performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Position in the {@link Vector} where the new elements are inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert>(position: VectorIterator, begin: InputIterator, end: InputIterator): VectorIterator; + /** + * Insert an element. + * + * The {@link Vector} is extended by inserting new element before the element at the specified + * position, effectively increasing the container size by one. + * + * Because {@link Vector}s use an Array as their underlying storage, inserting element in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to its new position. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Position in the {@link Vector} where the new element is inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param val Value to be copied to the inserted element. + * + * @return An iterator that points to the newly inserted element. + */ + insert(position: VectorReverseIterator, val: T): VectorReverseIterator; + /** + * Insert elements by repeated filling. + * + * The {@link Vector} is extended by inserting new elements before the element at the specified + * position, effectively increasing the container size by the number of elements inserted. + * + * Because {@link Vector}s use an Array as their underlying storage, inserting elements in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to their new positions. This is generally an inefficient operation compared to the + * one performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Position in the {@link Vector} where the new elements are inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param n Number of elements to insert. Each element is initialized to a copy of val. + * @param val Value to be copied (or moved) to the inserted elements. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert(position: VectorReverseIterator, n: number, val: T): VectorReverseIterator; + /** + * Insert elements by range iterators. + * + * The {@link Vector} is extended by inserting new elements before the element at the specified + * position, effectively increasing the container size by the number of elements inserted by range + * iterators. + * + * Because {@link Vector}s use an Array as their underlying storage, inserting elements in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to their new positions. This is generally an inefficient operation compared to the + * one performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Position in the {@link Vector} where the new elements are inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert>(position: VectorReverseIterator, begin: InputIterator, end: InputIterator): VectorReverseIterator; + /** + * @hidden + */ + private _Insert_by_val(position, val); + /** + * @hidden + */ + private _Insert_by_repeating_val(position, n, val); + /** + * @hidden + */ + protected _Insert_by_range>(position: VectorIterator, first: InputIterator, last: InputIterator): VectorIterator; + /** + * @inheritdoc + */ + pop_back(): void; + /** + * Erase element. + * + * Removes from the {@link Vector} either a single element; position. + * + * This effectively reduces the container size by the number of element removed. + * + * Because {@link Vector}s use an Array as their underlying storage, erasing an element in + * position other than the {@link end end()} causes the container to relocate all the elements after the + * segment erased to their new positions. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Iterator pointing to a single element to be removed from the {@link Vector}. + * + * @return An iterator pointing to the new location of the element that followed the last element erased by + * the function call. This is the {@link end end()} if the operation erased the last element in the + * sequence. + */ + erase(position: VectorIterator): VectorIterator; + /** + * Erase element. + * + * Removes from the Vector either a single element; position. + * + * This effectively reduces the container size by the number of elements removed. + * + * Because {@link Vector}s use an Array as their underlying storage, erasing elements in + * position other than the {@link end end()} causes the container to relocate all the elements after the + * segment erased to their new positions. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + * + * @return An iterator pointing to the new location of the element that followed the last element erased by + * the function call. This is the {@link rend rend()} if the operation erased the last element in the + * sequence. + */ + erase(first: VectorIterator, last: VectorIterator): VectorIterator; + /** + * Erase element. + * + * Removes from the {@link Vector} either a single element; position. + * + * This effectively reduces the container size by the number of element removed. + * + * Because {@link Vector}s use an Array as their underlying storage, erasing an element in + * position other than the {@link end end()} causes the container to relocate all the elements after the + * segment erased to their new positions. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Iterator pointing to a single element to be removed from the {@link Vector}. + * + * @return An iterator pointing to the new location of the element that followed the last element erased by + * the function call. This is the {@link rend rend()} if the operation erased the last element in the + * sequence. + */ + erase(position: VectorReverseIterator): VectorReverseIterator; + /** + * Erase element. + * + * Removes from the Vector either a single element; position. + * + * This effectively reduces the container size by the number of elements removed. + * + * Because {@link Vector}s use an Array as their underlying storage, erasing elements in + * position other than the {@link end end()} causes the container to relocate all the elements after the + * segment erased to their new positions. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + * + * @return An iterator pointing to the new location of the element that followed the last element erased by + * the function call. This is the {@link end end()} if the operation erased the last element in the + * sequence. + */ + erase(first: VectorReverseIterator, last: VectorReverseIterator): VectorReverseIterator; + /** + * @hidden + */ + 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 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 Vector container}. + */ + swap(obj: Vector): void; + /** + * @inheritdoc + */ + swap(obj: base.Container): void; + } +} +declare namespace std { + /** + * An iterator of Vector. + * + * + * + * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class VectorIterator extends Iterator implements base.IArrayIterator { + /** + * @hidden + */ + private index_; + /** + * Construct from the source {@link Vector container}. + * + * #### Note + * Do not create the iterator directly, by yourself. + * + * Use {@link Vector.begin begin()}, {@link Vector.end end()} in {@link Vector container} instead. + * + * @param source The source {@link Vector container} to reference. + * @param index Sequence number of the element in the source {@link Vector}. + */ + constructor(source: Vector, index: number); + /** + * @inheritdoc + */ + source(): Vector; + /** + * @inheritdoc + */ + index(): number; + /** + * @inheritdoc + */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ + value: T; + /** + * @inheritdoc + */ + prev(): VectorIterator; + /** + * @inheritdoc + */ + next(): VectorIterator; + /** + * @inheritdoc + */ + advance(n: number): VectorIterator; + /** + * @inheritdoc + */ + equals(obj: VectorIterator): boolean; + /** + * @inheritdoc + */ + swap(obj: VectorIterator): void; + } +} +declare namespace std { + /** + * A reverse-iterator of Vector. + * + * + * + * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class VectorReverseIterator extends ReverseIterator, VectorIterator, 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); + /** + * @hidden + */ + protected _Create_neighbor(base: VectorIterator): VectorReverseIterator; + /** + * @inheritdoc + */ + index(): number; + /** + * @inheritdoc + */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ + value: T; + } +} +declare namespace std { + /** + * FIFO queue. + * + * {@link Queue}s are a type of container adaptor, specifically designed to operate in a FIFO context + * (first-in first-out), where elements are inserted into one end of the container and extracted from the other. + * + * {@link Queue}s are implemented as containers adaptors, which are classes that use an encapsulated object of + * a specific container class as its underlying container, providing a specific set of member functions to access + * its elements. Elements are pushed into the {@link IDeque.back back()} of the specific container and popped from + * its {@link IDeque.front front()}. + * + * {@link container_ The underlying container} may be one of the standard container class template or some + * other specifically designed container class. This underlying container shall support at least the following + * operations: + * + * - {@link IDequeContainer.empty empty} + * - {@link IDequeContainer.size size} + * - {@link IDequeContainer.front front} + * - {@link IDequeContainer.back back} + * - {@link IDequeContainer.push_back push_back} + * - {@link IDequeContainer.pop_front pop_front} + * + * The standard container classes {@link Deque} and {@link List} fulfill these requirements. + * 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. + * + * @reference http://www.cplusplus.com/reference/queue/queue + * @author Jeongho Nam + */ + class Queue { + /** + * The underlying object for implementing the FIFO + */ + private container_; + /** + * Default Constructor. + */ + constructor(); + /** + * Copy Constructor. + */ + constructor(container: Queue); + /** + * Return size. + * + * Returns the number of elements in the {@link Queue}. + * + * This member function effectively calls member {@link IDeque.size size()} of the + * {@link container_ underlying container} object. + * + * @return The number of elements in the {@link container_ underlying container}. + */ + size(): number; + /** + * Test whether container is empty. + * + * returns whether the {@link Queue} is empty: i.e. whether its size is zero. + * + * This member function efeectively calls member {@link IDeque.empty empty()} of the + * {@link container_ underlying container} object. + * + * @return true if the {@link container_ underlying container}'s size is 0, + * false otherwise. + */ + empty(): boolean; + /** + * Access next element. + * + * Returns a value of the next element in the {@link Queue}. + * + * The next element is the "oldest" element in the {@link Queue} and the same element that is popped out + * from the queue when {@link pop Queue.pop()} is called. + * + * This member function effectively calls member {@link IDeque.front front()} of the + * {@link container_ underlying container} object. + * + * @return A value of the next element in the {@link Queue}. + */ + front(): T; + /** + * Access last element. + * + * Returns a vaue of the last element in the queue. This is the "newest" element in the queue (i.e. the + * last element pushed into the queue). + * + * This member function effectively calls the member function {@link IDeque.back back()} of the + * {@link container_ underlying container} object. + * + * @return A value of the last element in the {@link Queue}. + */ + back(): T; + /** + * Insert element. + * + * Inserts a new element at the end of the {@link Queue}, after its current last element. + * The content of this new element is initialized to val. + * + * This member function effectively calls the member function {@link IDeque.push_back push_back()} of the + * {@link container_ underlying container} object. + * + * @param val Value to which the inserted element is initialized. + */ + push(val: T): void; + /** + * Remove next element. + * + * Removes the next element in the {@link Queue}, effectively reducing its size by one. + * + * The element removed is the "oldest" element in the {@link Queue} whose value can be retrieved by calling + * member {@link front Queue.front()}. + * + * This member function effectively calls the member function {@link IDeque.pop_front pop_front()} of the + * {@link container_ underlying container} object. + */ + pop(): void; + /** + * Swap contents. + * + * Exchanges the contents of the container adaptor (this) by those of obj. + * + * This member function calls the non-member function {@link Container.swap swap} (unqualified) to swap + * the {@link container_ underlying containers}. + * + * @param obj Another {@link Queue} container adaptor of the same type (i.e., instantiated with the same + * template parameter, T). Sizes may differ. + */ + 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: + * + * - {@link IArrayContainer.empty empty()} + * - {@link IArrayContainer.size size()} + * - {@link IArrayContainer.front front()} + * - {@link IArrayContainer.push_back push_back()} + * - {@link IArrayContainer.pop_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 { + /** + * @hidden + */ + 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); + /** + * Return size. + * + * Returns the number of elements in the {@link PriorityQueue}. + * + * This member function effectively calls member {@link IArrayContainer.size size} of the + * {@link IArrayContainer 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 IArrayContainer 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 IArrayContainer.front front} of the + * {@link IArrayContainer 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 IArrayContainer.push_back push_back} of the + * {@link IArrayContainer 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 IArrayContainer.pop_back pop_back} of + * the {@link IArrayContainer 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 IArrayContainer underlying container} value and their comparison function using the corresponding + * {@link swap swap} non-member functions (unqualified). + * + * This member function has a noexcept specifier that matches the combined noexcept of the + * {@link IArrayContainer.swap swap} operations on the {@link IArrayContainer 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. + * + * {@link Stack}s are a type of container adaptor, specifically designed to operate in a LIFO context + * (last-in first-out), where elements are inserted and extracted only from one end of the + * + * {@link Stack}s are implemented as containers adaptors, which are classes that use an encapsulated object of + * a specific container class as its underlying container, providing a specific set of member functions to + * access its elements. Elements are pushed/popped from the {@link ILinearContainer.back back()} of the + * {@link ILinearContainer specific container}, which is known as the top of the {@link Stack}. + * + * {@link container_ The underlying container} may be any of the standard container class templates or some + * other specifically designed container class. The container shall support the following operations: + * + * - {@link ILinearContainer.empty empty} + * - {@link ILinearContainer.size size} + * - {@link ILinearContainer.front front} + * - {@link ILinearContainer.back back} + * - {@link ILinearContainer.push_back push_back} + * - {@link ILinearContainer.pop_back pop_back} + * + * The standard container classes {@link Vector}, {@link Deque} and {@link List} fulfill these requirements. + * 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. + * + * @reference http://www.cplusplus.com/reference/stack/stack + * @author Jeongho Nam + */ + class Stack { + /** + * The underlying object for implementing the LIFO + */ + private container_; + /** + * Default Constructor. + */ + constructor(); + /** + * Copy Constructor. + */ + constructor(stack: Stack); + /** + * Return size. + * + * Returns the number of elements in the {@link Stack}. + * + * This member function effectively calls member {@link ILinearContainer.size size()} of the + * {@link container_ underlying container} object. + * + * @return The number of elements in the {@link container_ underlying container}. + */ + size(): number; + /** + * Test whether container is empty. + * + * returns whether the {@link Stack} is empty: i.e. whether its size is zero. + * + * This member function effectively calls member {@link ILinearContainer.empty empty()} of the + * {@link container_ underlying container} object. + * + * @return true if the underlying container's size is 0, + * false otherwise. + */ + empty(): boolean; + /** + * Access next element. + * + * Returns a value of the top element in the {@link Stack}. + * + * Since {@link Stack}s are last-in first-out containers, the top element is the last element inserted into + * the {@link Stack}. + * + * This member function effectively calls member {@link ILinearContainer.back back()} of the + * {@link container_ underlying container} object. + * + * @return A value of the top element in the {@link Stack}. + */ + top(): T; + /** + * Insert element. + * + * Inserts a new element at the top of the {@link Stack}, above its current top element. + * + * This member function effectively calls the member function + * {@link ILinearContainer.push_back push_back()} of the {@link container_ underlying container} object. + * + * @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 Stack}, effectively reducing its size by one. + * + * The element removed is the latest element inserted into the {@link Stack}, whose value can be retrieved + * by calling member {@link top Stack.top()}. + * + * This member function effectively calls the member function {@link ILinearContainer.pop_back pop_back()} + * of the {@link container_ underlying container} object. + */ + pop(): void; + /** + * Swap contents. + * + * Exchanges the contents of the container adaptor (this) by those of obj. + * + * This member function calls the non-member function {@link Container.swap swap} (unqualified) to swap + * the {@link container_ underlying containers}. + * + * @param obj Another {@link Stack} container adaptor of the same type (i.e., instantiated with the same + * template parameter, T). Sizes may differ. + */ + swap(obj: Stack): void; + } +} +declare namespace std.TreeSet { + type iterator = SetIterator; + type reverse_iterator = 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 container. + * + * 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: TreeMultiSet); + /** + * Copy Constructor with compare. + * + * @param container A container to be copied. + * @param compare A binary predicate determines order of elements. + */ + constructor(container: TreeMultiSet, 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); + /** + * 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. + * @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; + /** + * @hidden + */ + protected _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @hidden + */ + 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 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.Container): void; + } +} +declare namespace std.TreeMap { + type iterator = MapIterator; + type reverse_iterator = MapReverseIterator; +} +declare namespace std { + /** + * Tree-structured map, std::map of STL. + * + * {@link TreeMap TreeMaps} are associative containers that store elements formed by a combination of a + * key value (Key) and a mapped value (T), following order. + * + * In a {@link TreeMap}, the key values are generally used to sort and uniquely identify the elements, + * while the mapped values store the content associated to this key. The types of key and + * mapped value may differ, and are grouped together in member type value_type, which is a {@link Pair} + * type combining both: + * + * typedef Pair value_type; + * + * Internally, the elements in a {@link TreeMap} are always sorted by its key following a + * strict weak ordering criterion indicated by its internal comparison method {@link less}. + * + * {@link TreeMap} containers are generally slower than {@link HashMap HashMap} containers to access individual + * elements by their key, but they allow the direct iteration on subsets based on their order. + * + * {@link TreeMap}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.
    + * + *
    Map
    + *
    Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value.
    + * + *
    Unique keys
    + *
    No two elements in the container can have equivalent keys.
    + *
    + * + * @param Type of the keys. Each element in a map is uniquely identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @reference http://www.cplusplus.com/reference/map/map + * @author Jeongho Nam + */ + class TreeMap extends base.UniqueMap implements base.ITreeMap { + /** + * @hidden + */ + private tree_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. + */ + constructor(compare: (x: Key, y: Key) => boolean); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + */ + constructor(array: Array>); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array>, compare: (x: Key, y: Key) => boolean); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: Array<[Key, T]>); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array<[Key, T]>, compare: (x: Key, y: Key) => boolean); + /** + * Copy Constructor. + * + * @param container Another map to copy. + */ + constructor(container: TreeMap); + /** + * Copy Constructor. + * + * @param container Another map to copy. + * @param compare A binary predicate determines order of elements. + */ + constructor(container: TreeMap, compare: (x: Key, y: Key) => boolean); + /** + * Range Constructor. + * + * @param begin nput 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. + * + * @param begin nput 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: Key, y: Key) => boolean); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: Key): MapIterator; + /** + * @inheritdoc + */ + key_comp(): (x: Key, y: Key) => boolean; + /** + * @inheritdoc + */ + value_comp(): (x: Pair, y: Pair) => boolean; + /** + * @inheritdoc + */ + lower_bound(key: Key): MapIterator; + /** + * @inheritdoc + */ + upper_bound(key: Key): MapIterator; + /** + * @inheritdoc + */ + equal_range(key: Key): Pair, MapIterator>; + /** + * @hidden + */ + protected _Insert_by_pair(pair: Pair): any; + /** + * @hidden + */ + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * @hidden + */ + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; + /** + * @hidden + */ + protected _Handle_insert(first: MapIterator, last: MapIterator): void; + /** + * @hidden + */ + 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 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.Container>): void; + } +} +declare namespace std.TreeMultiSet { + type iterator = SetIterator; + type reverse_iterator = SetReverseIterator; +} +declare namespace std { + /** + * Tree-structured multiple-key set. + * + * {@link TreeMultiSet TreeMultiSets} are containers that store elements following a specific order, and + * where multiple elements can have equivalent values. + * + * In a {@link TreeMultiSet}, the value of an element also identifies it (the value is itself + * the key, of type T). The value of the elements in a {@link TreeMultiSet} cannot + * be modified once in the container (the elements are always const), but they can be inserted or removed + * from the container. + * + * Internally, the elements in a {@link TreeMultiSet TreeMultiSets} are always sorted following a strict + * weak ordering criterion indicated by its internal comparison method (of {@link IComparable.less less}). + * + * {@link TreeMultiSet} containers are generally slower than {@link HashMultiSet} containers + * to access individual elements by their key, but they allow the direct iteration on subsets based on + * their order. + * + * {@link TreeMultiSet TreeMultiSets} 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.
    + * + *
    Multiple equivalent keys
    + *
    Multiple elements in the container can have equivalent keys.
    + *
    + * + * @param Type of the elements. Each element in a {@link TreeMultiSet} container is also identified + * by this value (each value is itself also the element's key). + * + * @reference http://www.cplusplus.com/reference/set/multiset + * @author Jeongho Nam + */ + class TreeMultiSet extends base.MultiSet 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: TreeMultiSet); + /** + * Copy Constructor with compare. + * + * @param container A container to be copied. + * @param compare A binary predicate determines order of elements. + */ + constructor(container: TreeMultiSet, 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); + /** + * 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. + * @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 + */ + count(val: T): number; + /** + * @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; + /** + * @hidden + */ + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; + /** + * @hidden + */ + protected _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @hidden + */ + 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 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.Container): void; + } +} +declare namespace std.TreeMultiMap { + type iterator = MapIterator; + type reverse_iterator = MapReverseIterator; +} +declare namespace std { + /** + * Tree-structured multiple-key map. + * + * {@link TreeMultiMap TreeMultiMaps} are associative containers that store elements formed by a combination of + * a key value and a mapped value, following a specific order, and where multiple elements can + * have equivalent keys. + * + * In a {@link TreeMultiMap}, the key values are generally used to sort and uniquely identify + * the elements, while the mapped values store the content associated to this key. The types of + * key and mapped value may differ, and are grouped together in member type + * value_type, which is a {@link Pair} type combining both: + * + * typedef Pair value_type; + * + * Internally, the elements in a {@link TreeMultiMap}are always sorted by its key following a + * strict weak ordering criterion indicated by its internal comparison method (of {@link less}). + * + * {@link TreeMultiMap}containers are generally slower than {@link HashMap} containers + * to access individual elements by their key, but they allow the direct iteration on subsets based + * on their order. + * + * {@link TreeMultiMap TreeMultiMaps} are typically implemented as binary search trees. + * + * < + * img src="http://samchon.github.io/tstl/images/design/class_diagram/map_containers.png" style="max-width: 100%" />

    + * + * ### 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. + *
    + * + *
    Map
    + *
    + * Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value. + *
    + * + *
    Multiple equivalent keys
    + *
    Multiple elements in the container can have equivalent keys.
    + *
    + * + * @param Type of the keys. Each element in a map is uniquely identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @reference http://www.cplusplus.com/reference/map/multimap + * @author Jeongho Nam + */ + class TreeMultiMap extends base.MultiMap implements base.ITreeMap { + /** + * @hidden + */ + private tree_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. + */ + constructor(compare: (x: Key, y: Key) => boolean); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + */ + constructor(array: Array>); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array>, compare: (x: Key, y: Key) => boolean); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: Array<[Key, T]>); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array<[Key, T]>, compare: (x: Key, y: Key) => boolean); + /** + * Copy Constructor. + * + * @param container Another map to copy. + */ + constructor(container: TreeMultiMap); + /** + * Copy Constructor. + * + * @param container Another map to copy. + * @param compare A binary predicate determines order of elements. + */ + constructor(container: TreeMultiMap, compare: (x: Key, y: Key) => boolean); + /** + * Range Constructor. + * + * @param begin nput 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. + * + * @param begin nput 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: Key, y: Key) => boolean); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: Key): MapIterator; + /** + * @inheritdoc + */ + count(key: Key): number; + /** + * @inheritdoc + */ + key_comp(): (x: Key, y: Key) => boolean; + /** + * @inheritdoc + */ + value_comp(): (x: Pair, y: Pair) => boolean; + /** + * @inheritdoc + */ + lower_bound(key: Key): MapIterator; + /** + * @inheritdoc + */ + upper_bound(key: Key): MapIterator; + /** + * @inheritdoc + */ + equal_range(key: Key): Pair, MapIterator>; + /** + * @hidden + */ + protected _Insert_by_pair(pair: Pair): any; + /** + * @hidden + */ + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * @hidden + */ + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; + /** + * @hidden + */ + protected _Handle_insert(first: MapIterator, last: MapIterator): void; + /** + * @hidden + */ + 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 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.Container>): void; + } +} +declare namespace std { + /** + * System error exception. + * + * This class defines the type of objects thrown as exceptions to report conditions originating during + * runtime from the operating system or other low-level application program interfaces which have an + * associated {@link ErrorCode}. + * + * 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 { + /** + * @hidden + */ + protected code_: ErrorCode; + /** + * Construct from an error code. + * + * @param code An {@link ErrorCode} object. + */ + constructor(code: ErrorCode); + /** + * Construct from an error code and message. + * + * @param code An {@link ErrorCode} object. + * @param message A message incorporated in the string returned by member {@link what what()}. + */ + constructor(code: ErrorCode, message: string); + /** + * Construct from a numeric value and error category. + * + * @param val A numerical value identifying an error code. + * @param category A reference to an {@link ErrorCode} object. + */ + constructor(val: number, category: ErrorCategory); + /** + * Construct from a numeric value, error category and message. + * + * @param val A numerical value identifying an error code. + * @param category A reference to an {@link ErrorCode} object. + * @param message A message incorporated in the string returned by member {@link what what()}. + */ + constructor(val: number, category: ErrorCategory, message: string); + /** + * Get error code. + * + * Returns the {@link ErrorCode} object associated with the exception. + * + * This value is either the {@link ErrorCode} passed to the construction or its equivalent + * (if constructed with a value and a {@link category}. + * + * @return The {@link ErrorCode} associated with the object. + */ + code(): ErrorCode; + } +} +declare namespace std { + /** + * Error category. + * + * This type serves as a base class for specific category types. + * + * Category types are used to identify the source of an error. They also define the relation between + * {@link ErrorCode} and {@link ErrorCondition}objects of its category, as well as the message set for {@link ErrorCode} + * objects. + * + * Objects of these types have no distinct values and are not-copyable and not-assignable, and thus can only be + * 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 + */ + abstract class ErrorCategory { + /** + * Default Constructor. + */ + constructor(); + /** + * Return category name. + * + * In derived classes, the function returns a string naming the category. + * + * In {@link ErrorCategory}, it is a pure virtual member function. + * + *
      + *
    • In the {@link GenericCategory} object, it returns "generic".
    • + *
    • In the {@link SystemCategory} object, it returns "system".
    • + *
    • In the {@link IOStreamCategory} object, it returns "iostream".
    • + *
    + * + * @return The category name. + */ + abstract name(): string; + /** + * Error message. + * + * In derived classes, the function returns a string object with a message describing the error condition + * denoted by val. + * + * In {@link ErrorCategory}, it is a pure virtual member function. + * + * This function is called both by {@link ErrorCode.message ErrorCode.message()} and + * {@link ErrorCondition.message ErrorCondition.message()} to obtain the corresponding message in the + * {@link category}. Therefore, numerical values used by custom error codes and + * {@link ErrorCondition error conditions} should only match for a category if they describe the same error. + * + * @param val A numerical value identifying an error condition. + * If the {@link ErrorCategory} object is the {@link GenericCategory}, this argument is equivalent to an + * {@link errno} value. + * + * @return A string object with the message. + */ + abstract message(val: number): string; + /** + * Default error condition. + * + * Returns the default {@link ErrorCondition}object of this category that is associated with the + * {@link ErrorCode} identified by a value of val. + * + * Its definition in the base class {@link ErrorCategory} returns the same as constructing an + * {@link ErrorCondition} object with: + * + * new ErrorCondition(val, *this); + * + * As a virtual member function, this behavior can be overriden in derived classes. + * + * This function is called by the default definition of member {@link equivalent equivalent()}, which is used to + * compare {@link ErrorCondition error conditions} with error codes. + * + * @param val A numerical value identifying an error condition. + * + * @return The default {@link ErrorCondition}object associated with condition value val for this category. + */ + default_error_condition(val: number): ErrorCondition; + /** + * Check error code equivalence. + * + * Checks whether, for the category, an {@link ErrorCode error code} is equivalent to an + * {@link ErrorCondition error condition. + * + * This function is called by the overloads of comparison operators when an {@link ErrorCondition} object is + * compared to an {@link ErrorCode} object to check for equality or inequality. If either one of those objects' + * {@link ErrorCategory categories} considers the other equivalent using this function, they are considered + * equivalent by the operator. + * + * As a virtual member function, this behavior can be overridden in derived classes to define a different + * correspondence mechanism for each {@link ErrorCategory} type. + * + * @param val_code A numerical value identifying an error code. + * @param cond An object of an {@link ErrorCondition} type. + * + * @return true if the arguments are considered equivalent. false otherwise. + */ + equivalent(val_code: number, cond: ErrorCondition): boolean; + /** + * Check error code equivalence. + * + * Checks whether, for the category, an {@link ErrorCode error code} is equivalent to an + * {@link ErrorCondition error condition. + * + * This function is called by the overloads of comparison operators when an {@link ErrorCondition} object is + * compared to an {@link ErrorCode} object to check for equality or inequality. If either one of those objects' + * {@link ErrorCategory categories} considers the other equivalent using this function, they are considered + * equivalent by the operator. + * + * As a virtual member function, this behavior can be overridden in derived classes to define a different + * correspondence mechanism for each {@link ErrorCategory} type. + * + * @param code An object of an {@link ErrorCode} type. + * @param val_cond A numerical value identifying an error code. + * + * @return true if the arguments are considered equivalent. false otherwise. + */ + equivalent(code: ErrorCode, val_cond: number): boolean; + } +} +declare namespace std { + /** + * Error condition. + * + * Objects of this type hold a condition {@link value} associated with a {@link category}. + * + * Objects of this type describe errors in a generic way so that they may be portable across different + * systems. This is in contrast with {@link ErrorCode} objects, that may contain system-specific + * information. + * + * Because {@link ErrorCondition}objects can be compared with error_code objects directly by using + * relational operators, {@link ErrorCondition}objects are generally used to check whether + * a particular {@link ErrorCode} obtained from the system matches a specific error condition no matter + * the system. + * + * 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 + */ + class ErrorCondition extends base.ErrorInstance { + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from a numeric value and error category. + * + * @param val A numerical value identifying an error condition. + * @param category A reference to an {@link ErrorCategory} object. + */ + constructor(val: number, category: ErrorCategory); + } +} +declare namespace std { + /** + * Error code. + * + * Objects of this type hold an error code {@link value} associated with a {@link category}. + * + * The operating system and other low-level applications and libraries generate numerical error codes to + * represent possible results. These numerical values may carry essential information for a specific platform, + * but be non-portable from one platform to another. + * + * 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 + */ + class ErrorCode extends base.ErrorInstance { + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from a numeric value and error category. + * + * @param val A numerical value identifying an error code. + * @param category A reference to an {@link ErrorCategory} object. + */ + constructor(val: number, category: ErrorCategory); + } +} +declare namespace std { + /** + * 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; + /** + * Pair of values. + * + * This class couples together a pair of values, which may be of different types (T1 and + * T2). The individual values can be accessed through its public members {@link first} and + * {@link second}. + * + * @param Type of member {@link first}. + * @param Type of member {@link second}. + * + * @reference http://www.cplusplus.com/reference/utility/pair + * @author Jeongho Nam + */ + class Pair implements IComparable> { + /** + * A first value in the Pair. + */ + first: T1; + /** + * A second value in the Pair. + */ + second: T2; + /** + * Construct from pair values. + * + * @param first The first value of the Pair + * @param second The second value of the Pair + */ + constructor(first: T1, second: T2); + /** + * Whether a Pair is equal with the Pair. + * + * Compare each first and second value of two Pair(s) and returns whether they are equal or not. + * + * If stored key and value in a Pair are not number or string but an object like a class or struct, + * the comparison will be executed by a member method (SomeObject)::equals(). If the object does not have + * the member method equal_to(), only address of pointer will be compared. + * + * @param obj A Map to compare + * @return Indicates whether equal or not. + */ + equals(pair: Pair): boolean; + /** + * @inheritdoc + */ + less(pair: Pair): boolean; + } + /** + * Construct {@link Pair} object. + * + * Constructs a {@link Pair} object with its {@link Pair.first first} element set to x and its + * {@link Pair.second second} element set to y. + * + * The template types can be implicitly deduced from the arguments passed to {@link make_pair}. + * + * {@link Pair} objects can be constructed from other {@link Pair} objects containing different types, if the + * respective types are implicitly convertible. + * + * @param x Value for member {@link Pair.first first}. + * @param y Value for member {@link Pair.second second}. + * + * @return A {@link Pair} object whose elements {@link Pair.first first} and {@link Pair.second second} are set to + * x and y respectivelly. + */ + function make_pair(x: T1, y: T2): Pair; +} +declare namespace std { + /** + * Type definition of {@link Vector} and it's the original name used in C++. + */ + export import vector = Vector; + /** + * Type definition of {@link List} and it's the original name used in C++. + */ + export import list = List; + /** + * Type definition of {@link Deque} and it's the original name used in C++. + */ + export import deque = Deque; + /** + * Type definition of {@link Stack} and it's the original name used in C++. + */ + type stack = Stack; + /** + * Type definition of {@link Queue} and it's the original name used in C++. + */ + type queue = Queue; + /** + * Type definition of {@link PriorityQueue} and it's the original name used in C++. + */ + type priority_queue = PriorityQueue; + var stack: typeof Stack; + var queue: typeof Queue; + var priority_queue: typeof PriorityQueue; + /** + * Type definition of {@link TreeSet} and it's the original name used in C++. + */ + export import set = TreeSet; + /** + * Type definition of {@link TreeMultiSet} and it's the original name used in C++. + */ + export import multiset = TreeMultiSet; + /** + * Type definition of {@link HashSet} and it's the original name used in C++. + */ + export import unordered_set = HashSet; + /** + * Type definition of {@link HashMultiSet} and it's the original name used in C++. + */ + export import unordered_multiset = HashMultiSet; + /** + * Type definition of {@link TreeMap} and it's the original name used in C++. + */ + export import map = TreeMap; + /** + * Type definition of {@link TreeMultiMap} and it's the original name used in C++. + */ + export import multimap = TreeMultiMap; + /** + * Type definition of {@link HashMap} and it's the original name used in C++. + */ + export import unordered_map = HashMap; + /** + * Type definition of {@link HashMultiMap} and it's the original name used in C++. + */ + export import unordered_multimap = HashMultiMap; + type exception = Exception; + type logic_error = LogicError; + type domain_error = DomainError; + type invalid_argument = InvalidArgument; + type length_error = LengthError; + type out_of_range = OutOfRange; + type runtime_error = RuntimeError; + type overflow_error = OverflowError; + type underflow_error = UnderflowError; + type range_error = RangeError; + type system_error = SystemError; + type error_category = ErrorCategory; + type error_condition = ErrorCondition; + type error_code = ErrorCode; + var exception: typeof Exception; + var logic_error: typeof LogicError; + var domain_error: typeof DomainError; + var invalid_argument: typeof InvalidArgument; + var length_error: typeof LengthError; + var out_of_range: typeof OutOfRange; + var runtime_error: typeof RuntimeError; + var overflow_error: typeof OverflowError; + var underflow_error: typeof UnderflowError; + var range_error: typeof RangeError; + var system_error: typeof SystemError; + var error_category: typeof ErrorCategory; + var error_condition: typeof ErrorCondition; + var error_code: typeof ErrorCode; +} diff --git a/raven-js/tsconfig.json b/tstl/tsconfig.json similarity index 94% rename from raven-js/tsconfig.json rename to tstl/tsconfig.json index 9b2f3354cf..b5f47406d8 100644 --- a/raven-js/tsconfig.json +++ b/tstl/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "raven-js-tests.ts" + "tstl-tests.ts" ] } \ No newline at end of file diff --git a/tstl/tstl-tests.ts b/tstl/tstl-tests.ts new file mode 100644 index 0000000000..ec42d087b4 --- /dev/null +++ b/tstl/tstl-tests.ts @@ -0,0 +1,2 @@ +import std = require("tstl"); +console.log(std); \ No newline at end of file diff --git a/typescript-stl/index.d.ts b/typescript-stl/index.d.ts index bd6886deed..bbd6c5ca57 100644 --- a/typescript-stl/index.d.ts +++ b/typescript-stl/index.d.ts @@ -1,12485 +1,13 @@ -// Type definitions for TypeScript-STL v1.2.4 -// Project: https://github.com/samchon/typescript-stl +// Type definitions for TSTL v1.3.x +// Project: https://github.com/samchon/tstl // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// +// TypeScript-STL is renamed to TSTL + declare module "typescript-stl" { + import std = require("tstl"); export = std; -} - -/** - *

    TypeScript-STL

    - *

    - *

    - * - *

    STL (Standard Template Library) Containers and Algorithms for TypeScript.

    - * - *

    TypeScript-STL is a TypeScript's Standard Template Library who is migrated from C++ STL. Most of classes - * and functions of STL have implemented. Just enjoy it.

    - * - * @git https://github.com/samchon/typescript-stl - * @author Jeongho Nam - */ -declare namespace std { -} -/** - * Base classes composing STL in background. - * - * @author Jeongho Nam - */ -declare namespace std.base { -} -declare namespace std { - /** - *

    Apply function to range.

    - * - *

    Applies function fn to each of the elements in the range [first, last).

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * @param fn Unary function that accepts an element in the range as argument. This can either be a function p - * ointer or a move constructible function object. Its return value, if any, is ignored. - */ - function for_each, Func extends (val: T) => any>(first: InputIterator, last: InputIterator, fn: Func): Func; - /** - * Apply function to range. - * - * Applies function *fn* to each of the elements in the range [*first*, *first + n*). - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param n the number of elements to apply the function to - * @param fn Unary function that accepts an element in the range as argument. This can either be a function p - * ointer or a move constructible function object. Its return value, if any, is ignored. - * - * @return first + n - */ - function for_each_n>(first: InputIterator, n: number, fn: (val: T) => any): InputIterator; - /** - *

    Test condition on all elements in range.

    - * - *

    Returns true if pred returns true for all the elements in the range - * [first, last) or if the range is {@link IContainer.empty empty}, and false otherwise. - *

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * @param pred Unary function that accepts an element in the range as argument and returns a value convertible to - * boolean. The value returned indicates whether the element fulfills the condition - * checked by this function. The function shall not modify its argument. - * - * @return true if pred returns true for all the elements in the range or if the range is - * {@link IContainer.empty empty}, and false otherwise. - */ - function all_of>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): boolean; - /** - *

    Test if any element in range fulfills condition.

    - * - *

    Returns true if pred returns true for any of the elements in the range - * [first, last), and false otherwise.

    - * - *

    If [first, last) is an {@link IContainer.empty empty} range, the function returns - * false.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * @param pred Unary function that accepts an element in the range as argument and returns a value convertible to - * boolean. The value returned indicates whether the element fulfills the condition - * checked by this function. The function shall not modify its argument. - * - * @return true if pred returns true for any of the elements in the range - * [first, last), and false otherwise. If [first, last) is an - * {@link IContainer.empty empty} range, the function returns false. - */ - function any_of>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): boolean; - /** - *

    Test if no elements fulfill condition.

    - * - *

    Returns true if pred returns false for all the elements in the range - * [first, last) or if the range is {@link IContainer.empty empty}, and false otherwise. - *

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * @param pred Unary function that accepts an element in the range as argument and returns a value convertible to - * boolean. The value returned indicates whether the element fulfills the condition - * checked by this function. The function shall not modify its argument. - * - * @return true if pred returns false for all the elements in the range - * [first, last) or if the range is {@link IContainer.empty empty}, and false - * otherwise. - */ - function none_of>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): boolean; - /** - *

    Test whether the elements in two ranges are equal.

    - * - *

    Compares the elements in the range [first1, last1) with those in the range beginning at - * first2, and returns true if all of the elements in both ranges match.

    - * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to - * as many elements of this sequence as those in the range [first1, last1). - * - * @return true if all the elements in the range [first1, last1) compare equal to those - * of the range starting at first2, and false otherwise. - */ - function equal>(first1: InputIterator, last1: InputIterator, first2: Iterator): boolean; - /** - *

    Test whether the elements in two ranges are equal.

    - * - *

    Compares the elements in the range [first1, last1) with those in the range beginning at - * first2, and returns true if all of the elements in both ranges match.

    - * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to - * as many elements of this sequence as those in the range [first1, last1). - * @param pred Binary function that accepts two elements as argument (one of each of the two sequences, in the same - * order), and returns a value convertible to bool. The value returned indicates whether - * the elements are considered to match in the context of this function. - * - * @return true if all the elements in the range [first1, last1) compare equal to those - * of the range starting at first2, and false otherwise. - */ - function equal>(first1: InputIterator, last1: InputIterator, first2: Iterator, pred: (x: T, y: T) => boolean): boolean; - /** - *

    Lexicographical less-than comparison.

    - * - *

    Returns true if the range [first1, last1) compares lexicographically less - * than the range [first2, last2).

    - * - *

    A lexicographical comparison is the kind of comparison generally used to sort words alphabetically in - * dictionaries; It involves comparing sequentially the elements that have the same position in both ranges against - * each other until one element is not equivalent to the other. The result of comparing these first non-matching - * elements is the result of the lexicographical comparison.

    - * - *

    If both sequences compare equal until one of them ends, the shorter sequence is lexicographically less - * than the longer one.

    - * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the second sequence. - * @param last2 An {@link Iterator} to the final position of the second sequence. The ranged used is - * [first2, last2). - * - * @return true if the first range compares lexicographically less than than the second. - * false otherwise (including when all the elements of both ranges are equivalent). - */ - function lexicographical_compare, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): boolean; - /** - *

    Lexicographical comparison.

    - * - *

    Returns true if the range [first1, last1) compares lexicographically - * relationship than the range [first2, last2).

    - * - *

    A lexicographical comparison is the kind of comparison generally used to sort words alphabetically in - * dictionaries; It involves comparing sequentially the elements that have the same position in both ranges against - * each other until one element is not equivalent to the other. The result of comparing these first non-matching - * elements is the result of the lexicographical comparison.

    - * - *

    If both sequences compare equal until one of them ends, the shorter sequence is lexicographically - * relationship than the longer one.

    - * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the second sequence. - * @param last2 An {@link Iterator} to the final position of the second sequence. The ranged used is - * [first2, last2). - * @param compare Binary function that accepts two arguments of the types pointed by the iterators, and returns a - * value convertible to bool. The value returned indicates whether the first argument is - * considered to go before the second in the specific strict weak ordering it defines. - * - * @return true if the first range compares lexicographically relationship than than the - * second. false otherwise (including when all the elements of both ranges are equivalent). - */ - function lexicographical_compare, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, compare: (x: T, y: T) => boolean): boolean; - /** - *

    Find value in range.

    - * - *

    Returns an iterator to the first element in the range [first, last) that compares equal to - * val. If no such element is found, the function returns last.

    - * - *

    The function uses {@link equal_to equal_to} to compare the individual elements to val.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * @param val Value to search for in the range. - * - * @return An {@link Iterator} to the first element in the range that compares equal to val. If no elements - * match, the function returns last. - */ - function find>(first: InputIterator, last: InputIterator, val: T): InputIterator; - /** - *

    Find element in range.

    - * - *

    Returns an iterator to the first element in the range [first, last) for which pred returns - * true. If no such element is found, the function returns last.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * @param pred Unary function that accepts an element in the range as argument and returns a value convertible - * to bool. The value returned indicates whether the element is considered a match in - * the context of this function. The function shall not modify its argument. - * - * @return An {@link Iterator} to the first element in the range for which pred does not return - * false. If pred is false for all elements, the function returns - * last. - */ - function find_if>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): InputIterator; - /** - *

    Find element in range.

    - * - *

    Returns an iterator to the first element in the range [first, last) for which pred returns - * true. If no such element is found, the function returns last.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * @param pred Unary function that accepts an element in the range as argument and returns a value convertible - * to bool. The value returned indicates whether the element is considered a match in - * the context of this function. The function shall not modify its argument. - * - * @return An {@link Iterator} to the first element in the range for which pred returns false. - * If pred is true for all elements, the function returns last. - */ - function find_if_not>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): InputIterator; - /** - *

    Find last subsequence in range.

    - * - *

    Searches the range [first1, last1) for the last occurrence of the sequence defined by - * [first2, last2), and returns an {@link Iterator} to its first element, or last1,/i> if no - * occurrences are found.

    - * - *

    The elements in both ranges are compared sequentially using {@link equal_to}: A subsequence of - * [first1, last1) is considered a match only when this is true for all the elements of - * [first2, last2).

    - * - *

    This function returns the last of such occurrences. For an algorithm that returns the first instead, see - * {@link search}.

    - * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the element values to be searched for. - * @param last2 An {@link Iterator} to the final position of the element values to be searched for. The range used - * is [first2, last2). - * @param pred Binary function that accepts two elements as arguments (one of each of the two sequences, in the - * same order), and returns a value convertible to bool. The value returned indicates - * whether the elements are considered to match in the context of this function. - * - * @return An {@link Iterator} to the first element of the last occurrence of [first2, last2) in - * [first1, last1). If the sequence is not found, the function returns ,i>last1
    . Otherwise - * [first2, last2) is an empty range, the function returns last1. - */ - function find_end, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): Iterator1; - /** - *

    Find last subsequence in range.

    - * - *

    Searches the range [first1, last1) for the last occurrence of the sequence defined by - * [first2, last2), and returns an {@link Iterator} to its first element, or last1,/i> if no - * occurrences are found.

    - * - *

    The elements in both ranges are compared sequentially using pred: A subsequence of - * [first1, last1) is considered a match only when this is true for all the elements of - * [first2, last2).

    - * - *

    This function returns the last of such occurrences. For an algorithm that returns the first instead, see - * {@link search}.

    - * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the element values to be searched for. - * @param last2 An {@link Iterator} to the final position of the element values to be searched for. The range used - * is [first2, last2). - * @param pred Binary function that accepts two elements as arguments (one of each of the two sequences, in the - * same order), and returns a value convertible to bool. The value returned indicates - * whether the elements are considered to match in the context of this function. - * - * @return An {@link Iterator} to the first element of the last occurrence of [first2, last2) in - * [first1, last1). If the sequence is not found, the function returns ,i>last1
    . Otherwise - * [first2, last2) is an empty range, the function returns last1. - */ - function find_end, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, pred: (x: T, y: T) => boolean): Iterator1; - /** - *

    Find element from set in range.

    - * - *

    Returns an iterator to the first element in the range [first1, last1) that matches any of the - * elements in [first2, last2). If no such element is found, the function returns last1.

    - * - *

    The elements in [first1, last1) are sequentially compared to each of the values in - * [first2, last2) using {@link equal_to}, until a pair matches.

    - * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the element values to be searched for. - * @param last2 An {@link Iterator} to the final position of the element values to be searched for. The range used - * is [first2, last2). - * - * @return An {@link Iterator} to the first element in [first1, last1) that is part of - * [first2, last2). If no matches are found, the function returns last1. - */ - function find_first_of, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): Iterator1; - /** - *

    Find element from set in range.

    - * - *

    Returns an iterator to the first element in the range [first1, last1) that matches any of the - * elements in [first2, last2). If no such element is found, the function returns last1.

    - * - *

    The elements in [first1, last1) are sequentially compared to each of the values in - * [first2, last2) using pred, until a pair matches.

    - * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the element values to be searched for. - * @param last2 An {@link Iterator} to the final position of the element values to be searched for. The range used - * is [first2, last2). - * @param pred Binary function that accepts two elements as arguments (one of each of the two sequences, in the - * same order), and returns a value convertible to bool. The value returned indicates - * whether the elements are considered to match in the context of this function. - * - * @return An {@link Iterator} to the first element in [first1, last1) that is part of - * [first2, last2). If no matches are found, the function returns last1. - */ - function find_first_of, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, pred: (x: T, y: T) => boolean): Iterator1; - /** - *

    Find equal adjacent elements in range.

    - * - *

    Searches the range [first, last) for the first occurrence of two consecutive elements that match, - * and returns an {@link Iterator} to the first of these two elements, or last if no such pair is found.

    - * - *

    Two elements match if they compare equal using {@link equal_to}.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * - * @return An {@link Iterator} to the first element of the first pair of matching consecutive elements in the range - * [first, last). If no such pair is found, the function returns last. - */ - function adjacent_find>(first: InputIterator, last: InputIterator): InputIterator; - /** - *

    Find equal adjacent elements in range.

    - * - *

    Searches the range [first, last) for the first occurrence of two consecutive elements that match, - * and returns an {@link Iterator} to the first of these two elements, or last if no such pair is found.

    - * - *

    Two elements match if they compare equal using pred.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * @param pred Unary function that accepts an element in the range as argument and returns a value convertible to - * bool. The value returned indicates whether the element is considered a match in the - * context of this function. The function shall not modify its argument. - * - * @return An {@link Iterator} to the first element of the first pair of matching consecutive elements in the range - * [first, last). If no such pair is found, the function returns last. - */ - function adjacent_find>(first: InputIterator, last: InputIterator, pred: (x: T, y: T) => boolean): InputIterator; - /** - *

    Search range for subsequence.

    - * - *

    Searches the range [first1, last1) for the first occurrence of the sequence defined by - * [first2, last2), and returns an iterator to its first element, or last1 if no occurrences are - * found.

    - * - *

    The elements in both ranges are compared sequentially using {@link equal_to}: A subsequence of - * [first1, last1) is considered a match only when this is true for all the elements of - * [first2, last2).

    - * - *

    This function returns the first of such occurrences. For an algorithm that returns the last instead, see - * {@link find_end}.

    - * - * @param first1 {@link Iterator Forward iterator} to the initial position of the searched sequence. - * @param last1 {@link Iterator Forward iterator} to the final position of the searched sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Forward iterator} to the initial position of the sequence to be searched for. - * @param last2 {@link Iterator Forward iterator} to the final position of the sequence to be searched for. The range - * used is [first2, last2). - * - * @return An iterator to the first element of the first occurrence of [first2, last2) in first1 - * and last1. If the sequence is not found, the function returns last1. Otherwise - * [first2, last2) is an empty range, the function returns first1. - */ - function search, ForwardIterator2 extends Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2, last2: ForwardIterator2): ForwardIterator1; - /** - *

    Search range for subsequence.

    - * - *

    Searches the range [first1, last1) for the first occurrence of the sequence defined by - * [first2, last2), and returns an iterator to its first element, or last1 if no occurrences are - * found.

    - * - *

    The elements in both ranges are compared sequentially using pred: A subsequence of - * [first1, last1) is considered a match only when this is true for all the elements of - * [first2, last2).

    - * - *

    This function returns the first of such occurrences. For an algorithm that returns the last instead, see - * {@link find_end}.

    - * - * @param first1 {@link Iterator Forward iterator} to the initial position of the searched sequence. - * @param last1 {@link Iterator Forward iterator} to the final position of the searched sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Forward iterator} to the initial position of the sequence to be searched for. - * @param last2 {@link Iterator Forward iterator} to the final position of the sequence to be searched for. The range - * used is [first2, last2). - * @param pred Binary function that accepts two elements as arguments (one of each of the two sequences, in the same - * order), and returns a value convertible to bool. The returned value indicates whether the elements are - * considered to match in the context of this function. The function shall not modify any of its - * arguments. - * - * @return An iterator to the first element of the first occurrence of [first2, last2) in - * [first1, last1). If the sequence is not found, the function returns last1. Otherwise - * [first2, last2) is an empty range, the function returns first1. - */ - function search, ForwardIterator2 extends Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2, last2: ForwardIterator2, pred: (x: T, y: T) => boolean): ForwardIterator1; - /** - *

    Search range for elements.

    - * - *

    Searches the range [first, last) for a sequence of count elements, each comparing equal to - * val.

    - * - *

    The function returns an iterator to the first of such elements, or last if no such sequence is found. - *

    - * - * @param first {@link Iterator Forward iterator} to the initial position of the searched sequence. - * @param last {@link Iterator Forward iterator} to the final position of the searched sequence. 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. - * @param count Minimum number of successive elements to match. - * @param val Individual value to be compared, or to be used as argument for {@link equal_to}. - * - * @return An iterator to the first element of the sequence. If no such sequence is found, the function returns - * last. - */ - function search_n>(first: ForwardIterator, last: ForwardIterator, count: number, val: T): ForwardIterator; - /** - *

    Search range for elements.

    - * - *

    Searches the range [first, last) for a sequence of count elements, each comparing equal to - * val.

    - * - *

    The function returns an iterator to the first of such elements, or last if no such sequence is found. - *

    - * - * @param first {@link Iterator Forward iterator} to the initial position of the searched sequence. - * @param last {@link Iterator Forward iterator} to the final position of the searched sequence. 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. - * @param count Minimum number of successive elements to match. - * @param val Individual value to be compared, or to be used as argument for pred. - * @param pred Binary function that accepts two arguments (one element from the sequence as first, and val as - * second), and returns a value convertible to bool. The value returned indicates whether the - * element is considered a match in the context of this function. The function shall not modify any of its - * arguments. - * - * @return An {@link Iterator} to the first element of the sequence. If no such sequence is found, the function - * returns last. - */ - function search_n>(first: ForwardIterator, last: ForwardIterator, count: number, val: T, pred: (x: T, y: T) => boolean): ForwardIterator; - /** - *

    Return first position where two ranges differ.

    - * - *

    Compares the elements in the range [first1, last1) with those in the range beginning at - * first2, and returns the first element of both sequences that does not match.

    - * - *

    The function returns a {@link Pair} of {@link iterators Iterator} to the first element in each range that - * does not match.

    - * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to - * as many elements of this sequence as those in the range [first1, last1). - * - * @return A {@link Pair}, where its members {@link Pair.first first} and {@link Pair.second second} point to the - * first element in both sequences that did not compare equal to each other. If the elements compared in - * both sequences have all matched, the function returns a {@link Pair} with {@link Pair.first first} set - * to last1 and {@link Pair.second second} set to the element in that same relative position in the - * second sequence. If none matched, it returns {@link make_pair}(first1, first2). - */ - function mismatch, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2): Pair; - /** - *

    Return first position where two ranges differ.

    - * - *

    Compares the elements in the range [first1, last1) with those in the range beginning at - * first2, and returns the first element of both sequences that does not match.

    - * - *

    The function returns a {@link Pair} of {@link iterators Iterator} to the first element in each range that - * does not match.

    - * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to - * as many elements of this sequence as those in the range [first1, last1). - * @param pred Binary function that accepts two elements as argument (one of each of the two sequences, in the same - * order), and returns a value convertible to bool. The value returned indicates whether - * the elements are considered to match in the context of this function. - * - * @return A {@link Pair}, where its members {@link Pair.first first} and {@link Pair.second second} point to the - * first element in both sequences that did not compare equal to each other. If the elements compared in - * both sequences have all matched, the function returns a {@link Pair} with {@link Pair.first first} set - * to last1 and {@link Pair.second second} set to the element in that same relative position in the - * second sequence. If none matched, it returns {@link make_pair}(first1, first2). - */ - function mismatch, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, compare: (x: T, y: T) => boolean): Pair; - /** - *

    Count appearances of value in range.

    - * - *

    Returns the number of elements in the range [first, last) that compare equal to val.

    - * - *

    The function uses {@link equal_to} to compare the individual elements to val.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * @param val Value to match. - * - * @return The number of elements in the range [first, last) that compare equal to val. - */ - function count>(first: InputIterator, last: InputIterator, val: T): number; - /** - *

    Return number of elements in range satisfying condition.

    - * - *

    Returns the number of elements in the range [first, last) for which pred is true. - *

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible - * to bool. The value returned indicates whether the element is counted by this function. - * The function shall not modify its argument. This can either be a function pointer or a function - * object. - */ - function count_if>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): number; -} -declare namespace std { - /** - *

    Copy range of elements.

    - * - *

    Copies the elements in the range [first, last) into the range beginning at result.

    - * - *

    The function returns an iterator to the end of the destination range (which points to the element following the - * last element copied).

    - * - *

    The ranges shall not overlap in such a way that result points to an element in the range - * [first, last). For such cases, see {@link copy_backward}.

    - * - * @param first {@link Iterator Input iterator} to the initial position in a sequence to be copied. - * @param last {@link Iterator Input iterator} to the initial position in a sequence to be copied. 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. - * @param result {@link Iterator Output iterator} to the initial position in the destination sequence. This shall not - * point to any element in the range [first, last). - * - * @return An iterator to the end of the destination range where elements have been copied. - */ - function copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator): OutputIterator; - /** - *

    Copy elements.

    - * - *

    Copies the first n elements from the range beginning at first into the range beginning at - * result.

    - * - *

    The function returns an iterator to the end of the destination range (which points to one past the last element - * copied).

    - * - *

    If n is negative, the function does nothing.

    - * - *

    If the ranges overlap, some of the elements in the range pointed by result may have undefined but valid values. - *

    - * - * @param first {@link Iterator Input iterator} to the initial position in a sequence of at least n elements to - * be copied. InputIterator shall point to a type assignable to the elements pointed by - * OutputIterator. - * @param n Number of elements to copy. If this value is negative, the function does nothing. - * @param result {@link Iterator Output iterator} to the initial position in the destination sequence of at least - * n elements. This shall not point to any element in the range [first, last]. - * - * @return An iterator to the end of the destination range where elements have been copied. - */ - function copy_n, OutputIterator extends base.ILinearIterator>(first: InputIterator, n: number, result: OutputIterator): OutputIterator; - /** - *

    Copy certain elements of range.

    - * - *

    Copies the elements in the range [first, last) for which pred returns true to the - * range beginning at result.

    - * - * @param first {@link Iterator Input iterator} to the initial position in a sequence to be copied. - * @param last {@link Iterator Input iterator} to the initial position in a sequence to be copied. 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. - * @param result {@link Iterator Output iterator} to the initial position in the destination sequence. This shall not - * point to any element in the range [first, last). - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element is to be copied (if - * true, it is copied). The function shall not modify any of its arguments. - * - * @return An iterator to the end of the destination range where elements have been copied. - */ - function copy_if, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (x: T) => boolean): OutputIterator; - /** - *

    Copy range of elements backward.

    - * - *

    Copies the elements in the range [first, last) starting from the end into the range terminating - * at result.

    - * - *

    The function returns an iterator to the first element in the destination range.

    - * - *

    The resulting range has the elements in the exact same order as [first, last). To reverse their - * order, see {@link reverse_copy}.

    - * - *

    The function begins by copying *(last-1) into *(result-1), and then follows backward - * by the elements preceding these, until first is reached (and including it).

    - * - *

    The ranges shall not overlap in such a way that result (which is the past-the-end element in the - * destination range) points to an element in the range (first,last]. For such cases, see {@link copy}.

    - * - * @param first {@link Iterator Bidirectional iterator} to the initial position in a sequence to be copied. - * @param last {@link Iterator Bidirectional iterator} to the initial position in a sequence to be copied. 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. - * @param result {@link Iterator Bidirectional iterator} to the initial position in the destination sequence. This - * shall not point to any element in the range [first, last). - * - * @return An iterator to the first element of the destination sequence where elements have been copied. - */ - function copy_backward, BidirectionalIterator2 extends base.ILinearIterator>(first: BidirectionalIterator1, last: BidirectionalIterator1, result: BidirectionalIterator2): BidirectionalIterator2; - /** - *

    Fill range with value.

    - * - *

    Assigns val to all the elements in the range [first, last).

    - * - * @param first {@link Iterator Forward iterator} to the initial position in a sequence of elements that support being - * assigned a value of type T. - * @param last {@link Iterator Forward iterator} to the final position in a sequence of elements that support being - * assigned a value of type T.. The range filled 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. - * @param val Value to assign to the elements in the filled range. - */ - function fill>(first: ForwardIterator, last: ForwardIterator, val: T): void; - /** - *

    Fill sequence with value.

    - * - *

    Assigns val to the first n elements of the sequence pointed by first.

    - * - * @param first {@link Iterator Output iterator} to the initial position in a sequence of elements that support being - * assigned a value of type T. - * @param n Number of elements to fill. If negative, the function does nothing. - * @param val Value to be used to fill the range. - * - * @return An iterator pointing to the element that follows the last element filled. - */ - function fill_n>(first: OutputIterator, n: number, val: T): OutputIterator; - /** - *

    Transform range.

    - * - *

    Applies op to each of the elements in the range [first, last) and stores the value returned - * by each operation in the range that begins at result.

    - * - * @param first {@link Iterator Input iterator} to the initial position in a sequence to be transformed. - * @param last {@link Iterator Input iterator} to the initial position in a sequence to be transformed. 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. - * @param result {@link Iterator Output} iterator to the initial position of the range where the operation results are - * stored. The range includes as many elements as [first, last). - * @param op Unary function that accepts one element of the type pointed to by InputIterator as argument, and - * returns some result value convertible to the type pointed to by OutputIterator. - * - * @return An iterator pointing to the element that follows the last element written in the result sequence. - */ - function transform, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, op: (val: T) => T): OutputIterator; - /** - *

    Transform range.

    - * - *

    Calls binary_op using each of the elements in the range [first1, last1) as first argument, - * and the respective argument in the range that begins at first2 as second argument. The value returned by - * each call is stored in the range that begins at result.

    - * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second range. The range includes as - * many elements as [first1, last1). - * @param result {@link Iterator Output} iterator to the initial position of the range where the operation results are - * stored. The range includes as many elements as [first1, last1). - * @param binary_op Binary function that accepts two elements as argument (one of each of the two sequences), and - * returns some result value convertible to the type pointed to by OutputIterator. - * - * @return An iterator pointing to the element that follows the last element written in the result sequence. - */ - function transform, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, result: OutputIterator, binary_op: (x: T, y: T) => T): OutputIterator; - /** - *

    Generate values for range with function.

    - * - *

    Assigns the value returned by successive calls to gen to the elements in the range [first, last). - *

    - * - * @param first {@link Iterator Forward iterator} to the initial position in a sequence. - * @param last {@link Iterator Forward iterator} to the final position in a sequence. The range affected 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. - * @param gen Generator function that is called with no arguments and returns some value of a type convertible to - * those pointed by the iterators. - */ - function generate>(first: ForwardIterator, last: ForwardIterator, gen: () => T): void; - /** - *

    Generate values for sequence with function.

    - * - *

    Assigns the value returned by successive calls to gen to the first n elements of the sequence - * pointed by first.

    - * - * @param first {@link Iterator Output iterator} to the initial position in a sequence of at least n elements - * that support being assigned a value of the type returned by gen. - * @param n Number of values to generate. If negative, the function does nothing. - * @param gen Generator function that is called with no arguments and returns some value of a type convertible to - * those pointed by the iterators. - * - * @return An iterator pointing to the element that follows the last element whose value has been generated. - */ - function generate_n>(first: ForwardIterator, n: number, gen: () => T): ForwardIterator; - /** - *

    Remove consecutive duplicates in range.

    - * - *

    Removes all but the first element from every consecutive group of equivalent elements in the range - * [first, last).

    - * - *

    The function cannot alter the properties of the object containing the range of elements (i.e., it cannot - * alter the size of an array or a container): The removal is done by replacing the duplicate elements by the next - * element that is not a duplicate, and signaling the new size of the shortened range by returning an iterator to - * the element that should be considered its new past-the-last element.

    - * - *

    The relative order of the elements not removed is preserved, while the elements between the returned - * iterator and last are left in a valid but unspecified state.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * - * @return An iterator to the element that follows the last element not removed. The range between first and - * this iterator includes all the elements in the sequence that were not considered duplicates. - */ - function unique>(first: InputIterator, last: InputIterator): InputIterator; - /** - *

    Remove consecutive duplicates in range.

    - * - *

    Removes all but the first element from every consecutive group of equivalent elements in the range - * [first, last).

    - * - *

    The function cannot alter the properties of the object containing the range of elements (i.e., it cannot - * alter the size of an array or a container): The removal is done by replacing the duplicate elements by the next - * element that is not a duplicate, and signaling the new size of the shortened range by returning an iterator to - * the element that should be considered its new past-the-last element.

    - * - *

    The relative order of the elements not removed is preserved, while the elements between the returned - * iterator and last are left in a valid but unspecified state.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * @param pred Binary function that accepts two elements in the range as argument, and returns a value convertible - * to bool. The value returned indicates whether both arguments are considered equivalent - * (if true, they are equivalent and one of them is removed). The function shall not modify - * any of its arguments. - * - * @return An iterator to the element that follows the last element not removed. The range between first and - * this iterator includes all the elements in the sequence that were not considered duplicates. - */ - function unique>(first: InputIterator, last: InputIterator, pred: (left: t, right: t) => boolean): InputIterator; - /** - *

    Copy range removing duplicates.

    - * - *

    Copies the elements in the range [first, last) to the range beginning at result, except - * consecutive duplicates (elements that compare equal to the element preceding).

    - * - *

    Only the first element from every consecutive group of equivalent elements in the range - * [first, last) is copied.

    - * - *

    The comparison between elements is performed by applying {@lnk equal_to}.

    - * - * @param first {@link Iterator Forward iterator} to the initial position in a sequence. - * @param last {@link Iterator Forward iterator} to the final position in a sequence. 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. - * @param result Output iterator to the initial position of the range where the resulting range of values is stored. - * The pointed type shall support being assigned the value of an element in the range - * [first, last). - * - * @return An iterator pointing to the end of the copied range, which contains no consecutive duplicates. - */ - function unique_copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator): OutputIterator; - /** - *

    Copy range removing duplicates.

    - * - *

    Copies the elements in the range [first, last) to the range beginning at result, except - * consecutive duplicates (elements that compare equal to the element preceding).

    - * - *

    Only the first element from every consecutive group of equivalent elements in the range - * [first, last) is copied.

    - * - *

    The comparison between elements is performed by applying pred.

    - * - * @param first {@link Iterator Forward iterator} to the initial position in a sequence. - * @param last {@link Iterator Forward iterator} to the final position in a sequence. 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. - * @param result Output iterator to the initial position of the range where the resulting range of values is stored. - * The pointed type shall support being assigned the value of an element in the range - * [first, last). - * @param pred Binary function that accepts two elements in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether both arguments are considered equivalent (if - * true, they are equivalent and one of them is removed). The function shall not modify any - * of its arguments. - * - * @return An iterator pointing to the end of the copied range, which contains no consecutive duplicates. - */ - function unique_copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (x: T, y: T) => boolean): OutputIterator; - /** - *

    Remove value from range.

    - * - *

    Transforms the range [first, last) into a range with all the elements that compare equal to - * val removed, and returns an iterator to the new last of that range.

    - * - *

    The function cannot alter the properties of the object containing the range of elements (i.e., it cannot alter - * the size of an array or a container): The removal is done by replacing the elements that compare equal to - * val by the next element that does not, and signaling the new size of the shortened range by returning an - * iterator to the element that should be considered its new past-the-last element.

    - * - *

    The relative order of the elements not removed is preserved, while the elements between the returned iterator - * and last are left in a valid but unspecified state.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * @param val Value to be removed. - */ - function remove>(first: InputIterator, last: InputIterator, val: T): InputIterator; - /** - *

    Remove elements from range.

    - * - *

    Transforms the range [first, last) into a range with all the elements for which pred returns - * true removed, and returns an iterator to the new last of that range.

    - * - *

    The function cannot alter the properties of the object containing the range of elements (i.e., it cannot - * alter the size of an array or a container): The removal is done by replacing the elements for which pred returns - * true by the next element for which it does not, and signaling the new size of the shortened range - * by returning an iterator to the element that should be considered its new past-the-last element.

    - * - *

    The relative order of the elements not removed is preserved, while the elements between the returned - * iterator and last are left in a valid but unspecified state.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element is to be removed (if - * true, it is removed). The function shall not modify its argument. - */ - function remove_if>(first: InputIterator, last: InputIterator, pred: (left: T) => boolean): InputIterator; - /** - *

    Copy range removing value.

    - * - *

    Copies the elements in the range [first, last) to the range beginning at result, except - * those elements that compare equal to val.

    - * - *

    The resulting range is shorter than [first, last) by as many elements as matches in the sequence, - * which are "removed".

    - * - *

    The function uses {@link equal_to} to compare the individual elements to val.

    - * - * @param first {@link Iterator InputIterator} to the initial position in a sequence. - * @param last {@link Iterator InputIterator} to the final position in a sequence. 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. - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element in the range - * [first, last). - * @param val Value to be removed. - * - * @return An iterator pointing to the end of the copied range, which includes all the elements in - * [first, last) except those that compare equal to val. - */ - function remove_copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, val: T): OutputIterator; - /** - *

    Copy range removing values.

    - * - *

    Copies the elements in the range [first, last) to the range beginning at result, except - * those elements for which pred returns true.

    - * - *

    The resulting range is shorter than [first, last) by as many elements as matches, which are - * "removed".

    - * - * @param first {@link Iterator InputIterator} to the initial position in a sequence. - * @param last {@link Iterator InputIterator} to the final position in a sequence. 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. - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element in the range - * [first, last). - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element is to be removed from the copy (if - * true, it is not copied). The function shall not modify its argument. - * - * @return An iterator pointing to the end of the copied range, which includes all the elements in - * [first, last) except those for which pred returns true. - */ - function remove_copy_if, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (val: T) => boolean): OutputIterator; - /** - *

    Replace value in range.

    - * - *

    Assigns new_val to all the elements in the range [first, last) that compare equal to - * old_val.

    - * - *

    The function uses {@link equal_to} to compare the individual elements to old_val.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * @param old_val Value to be replaced. - * @param new_val Replacement value. - */ - function replace>(first: InputIterator, last: InputIterator, old_val: T, new_val: T): void; - /** - *

    Replace value in range.

    - * - *

    Assigns new_val to all the elements in the range [first, last) for which pred returns - * true.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element is to be replaced (if - * true, it is replaced). The function shall not modify its argument. - * @param new_val Value to assign to replaced elements. - */ - function replace_if>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean, new_val: T): void; - /** - *

    Copy range replacing value.

    - * - *

    Copies the elements in the range [first, last) to the range beginning at result, replacing - * the appearances of old_value by new_value.

    - * - *

    The function uses {@link std.equal_to} to compare the individual elements to old_value.

    - * - *

    The ranges shall not overlap in such a way that result points to an element in the range - * [first, last).

    - * - * @param first {@link Iterator InputIterator} to the initial position in a sequence. - * @param last {@link Iterator InputIterator} to the final position in a sequence. 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. - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element in the range - * [first, last). - * @param old_val Value to be replaced. - * @param new_val Replacement value. - * - * @return An iterator pointing to the element that follows the last element written in the result sequence. - */ - function replace_copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, old_val: T, new_val: T): OutputIterator; - /** - *

    Copy range replacing value.

    - * - *

    Copies the elements in the range [first, last) to the range beginning at result, replacing - * those for which pred returns true by new_value.

    - * - * @param first {@link Iterator InputIterator} to the initial position in a sequence. - * @param last {@link Iterator InputIterator} to the final position in a sequence. 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. - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element in the range - * [first, last). - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element is to be removed from the copy (if - * true, it is not copied). The function shall not modify its argument. - * @param new_val Value to assign to replaced values. - * - * @return An iterator pointing to the element that follows the last element written in the result sequence. - */ - function replace_copy_if, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (val: T) => boolean, new_val: T): OutputIterator; - /** - *

    Exchange values of objects pointed to by two iterators.

    - * - *

    Swaps the elements pointed to by x and y.

    - * - *

    The function calls {@link Iterator.swap} to exchange the elements.

    - * - * @param x {@link Iterator Forward iterator} to the objects to swap. - * @param y {@link Iterator Forward iterator} to the objects to swap. - */ - function iter_swap(x: Iterator, y: Iterator): void; - /** - *

    Exchange values of two ranges.

    - * - *

    Exchanges the values of each of the elements in the range [first1, last1) with those of their - * respective elements in the range beginning at first2.

    - * - *

    The function calls {@link Iterator.swap} to exchange the elements.

    - * - * @param first1 {@link Iterator Forward iterator} to the initial position of the first sequence. - * @param last1 {@link Iterator Forward iterator} to the final position of the first sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 {@link Iterator Forward iterator} to the initial position of the second range. The range includes as - * many elements as [first1, last1). The two ranges shall not overlap. - * - * @return An iterator to the last element swapped in the second sequence. - */ - function swap_ranges, ForwardIterator2 extends Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2): ForwardIterator2; - /** - *

    Reverse range.

    - * - *

    Reverses the order of the elements in the range [first, last).

    - * - *

    The function calls {@link iter_swap} to swap the elements to their new locations.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - */ - function reverse>(first: InputIterator, last: InputIterator): void; - /** - *

    Copy range reversed.

    - * - *

    Copies the elements in the range [first, last) to the range beginning at result, but in - * reverse order.

    - * - * @param first {@link Iterator Bidirectional iterator} to the initial position in a sequence to be copied. - * @param last {@link Iterator Bidirectional iterator} to the initial position in a sequence to be copied. 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. - * @param result {@link Iterator Output iterator} to the initial position of the range where the reserved range is - * stored. The pointed type shall support being assigned the value of an element in the range - * [first, last). - * - * @return An output iterator pointing to the end of the copied range, which contains the same elements in reverse - * order. - */ - function reverse_copy, OutputIterator extends base.ILinearIterator>(first: BidirectionalIterator, last: BidirectionalIterator, result: OutputIterator): OutputIterator; - /** - *

    Rotate left the elements in range.

    - * - *

    Rotates the order of the elements in the range [first, last), in such a way that the element - * pointed by middle becomes the new first element.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param middle An {@link Iterator} pointing to the element within the range [first, last) that is - * moved to the first position in the range. - * @param last An {@link Iterator} to the final position in a sequence. 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. - * - * @return An iterator pointing to the element that now contains the value previously pointed by first. - */ - function rotate>(first: InputIterator, middle: InputIterator, last: InputIterator): InputIterator; - /** - *

    Copy range rotated left.

    - * - *

    Copies the elements in the range [first, last) to the range beginning at result, but - * rotating the order of the elements in such a way that the element pointed by middle becomes the first - * element in the resulting range.

    - * - * @param first {@link Iterator Forward iterator} to the initial position of the range to be copy-rotated. - * @param middle Forward iterator pointing to the element within the range [first, last) that is copied as the first element in the resulting range. - * @param last {@link Iterator Forward iterator} to the final positions of the range to be copy-rotated. 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. - * Notice that in this function, these are not consecutive parameters, but the first and third ones. - * @param result {@link Iterator Output iterator} to the initial position of the range where the reserved range is - * stored. The pointed type shall support being assigned the value of an element in the range - * [first, last). - * - * @return An output iterator pointing to the end of the copied range. - */ - function rotate_copy, OutputIterator extends base.ILinearIterator>(first: ForwardIterator, middle: ForwardIterator, last: ForwardIterator, result: OutputIterator): OutputIterator; - /** - *

    Randomly rearrange elements in range.

    - * - *

    Rearranges the elements in the range [first, last) randomly.

    - * - *

    The function swaps the value of each element with that of some other randomly picked element. When provided, - * the function gen determines which element is picked in every case. Otherwise, the function uses some unspecified - * source of randomness.

    - * - *

    To specify a uniform random generator, see {@link shuffle}.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - */ - function random_shuffle>(first: RandomAccessIterator, last: RandomAccessIterator): void; - /** - *

    Randomly rearrange elements in range using generator.

    - * - *

    Rearranges the elements in the range [first, last) randomly, using g as uniform random - * number generator.

    - * - *

    The function swaps the value of each element with that of some other randomly picked element. The function - * determines the element picked by calling g().

    - * - *

    To shuffle the elements of the range without such a generator, see {@link random_shuffle} instead.

    - * - *
    Note
    - *

    Using random generator engine is not implemented yet.

    - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. 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. - */ - function shuffle>(first: RandomAccessIterator, last: RandomAccessIterator): void; -} -declare namespace std { - /** - *

    Sort elements in range.

    - * - *

    Sorts the elements in the range [first, last) into ascending order. The elements are compared - * using {@link less}.

    - * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be sorted. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. - * 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. {@link IArrayIterator RandomAccessIterator} shall point to a type for which - * {@link Iterator.swap swap} is properly defined. - */ - function sort>(first: RandomAccessIterator, last: RandomAccessIterator): void; - /** - *

    Sort elements in range.

    - * - *

    Sorts the elements in the range [first, last) into specific order. The elements are compared - * using compare.

    - * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be sorted. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. - * 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. {@link IArrayIterator RandomAccessIterator} shall point to a type for which - * {@link Iterator.swap swap} is properly defined. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value - * convertible to boolean. The value returned indicates whether the element passed as first - * argument is considered to go before the second in the specific strict weak ordering it defines. The - * function shall not modify any of its arguments. This can either be a function pointer or a function - * object. - */ - function sort>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (left: T, right: T) => boolean): void; - /** - *

    Partially sort elements in range.

    - * - *

    Rearranges the elements in the range [first, last), in such a way that the elements before - * middle are the smallest elements in the entire range and are sorted in ascending order, while the remaining - * elements are left without any specific order.

    - * - *

    The elements are compared using {@link less}.

    - * - * @param last {@link IArrayIterator Random-access iterator} to the first position of the sequence to be sorted. - * @param middle {@link IArrayIterator Random-access iterator} pointing to the element within the range [first, last) that is used as the upper boundary of the elements that are fully sorted. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. - * 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. - */ - function partial_sort>(first: RandomAccessIterator, middle: RandomAccessIterator, last: RandomAccessIterator): void; - /** - *

    Partially sort elements in range.

    - * - *

    Rearranges the elements in the range [first, last), in such a way that the elements before - * middle are the smallest elements in the entire range and are sorted in ascending order, while the remaining - * elements are left without any specific order.

    - * - *

    The elements are compared using comp.

    - * - * @param last {@link IArrayIterator Random-access iterator} to the first position of the sequence to be sorted. - * @param middle {@link IArrayIterator Random-access iterator} pointing to the element within the range [first, last) that is used as the upper boundary of the elements that are fully sorted. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. - * 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. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value - * convertible to boolean. The value returned indicates whether the element passed as - * first argument is considered to go before the second in the specific strict weak ordering it - * defines. The function shall not modify any of its arguments. - */ - function partial_sort>(first: RandomAccessIterator, middle: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; - /** - *

    Copy and partially sort range.

    - * - *

    Copies the smallest elements in the range [first, last) to - * [result_first, result_last), sorting the elements copied. The number of elements copied is the same - * as the {@link distance} between result_first and result_last (unless this is more than the amount of - * elements in [first, last)).

    - * - *

    The range [first, last) is not modified.

    - * - *

    The elements are compared using {@link less}.

    - * - * @param first {@link Iterator Input iterator} to the initial position of the sequence to copy from. - * @param last {@link Iterator Input iterator} to the final position of the sequence to copy from. 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. - * InputIterator shall point to a type assignable to the elements pointed by - * RandomAccessIterator. - * @param result_first {@link Iterator Random-access iterator} to the initial position of the destination sequence. - * @param result_last {@link Iterator Random-access iterator} to the final position of the destination sequence. - * The range used is [result_first, result_last). - * @param compare Binary function that accepts two elements in the result range as arguments, and returns a value - * convertible to bool. The value returned indicates whether the element passed as first - * argument is considered to go before the second in the specific strict weak ordering it - * defines. The function shall not modify any of its arguments. - * - * @return An iterator pointing to the element that follows the last element written in the result sequence. - */ - function partial_sort_copy, RandomAccessIterator extends Iterator>(first: InputIterator, last: InputIterator, result_first: RandomAccessIterator, result_last: RandomAccessIterator): RandomAccessIterator; - /** - *

    Copy and partially sort range.

    - * - *

    Copies the smallest (or largest) elements in the range [first, last) to - * [result_first, result_last), sorting the elements copied. The number of elements copied is the same - * as the {@link distance} between result_first and result_last (unless this is more than the amount of - * elements in [first, last)).

    - * - *

    The range [first, last) is not modified.

    - * - *

    The elements are compared using compare.

    - * - * @param first {@link Iterator Input iterator} to the initial position of the sequence to copy from. - * @param last {@link Iterator Input iterator} to the final position of the sequence to copy from. 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. - * InputIterator shall point to a type assignable to the elements pointed by - * RandomAccessIterator. - * @param result_first {@link Iterator Random-access iterator} to the initial position of the destination sequence. - * @param result_last {@link Iterator Random-access iterator} to the final position of the destination sequence. - * The range used is [result_first, result_last). - * @param compare Binary function that accepts two elements in the result range as arguments, and returns a value - * convertible to bool. The value returned indicates whether the element passed as first - * argument is considered to go before the second in the specific strict weak ordering it - * defines. The function shall not modify any of its arguments. - * - * @return An iterator pointing to the element that follows the last element written in the result sequence. - */ - function partial_sort_copy, RandomAccessIterator extends Iterator>(first: InputIterator, last: InputIterator, result_first: RandomAccessIterator, result_last: RandomAccessIterator, compare: (x: T, y: T) => boolean): RandomAccessIterator; - /** - *

    Check whether range is sorted.

    - * - *

    Returns true if the range [first, last) is sorted into ascending order.

    - * - *

    The elements are compared using {@link less}.

    - * - * @param first {@link Iterator Forward iterator} to the initial position of the sequence. - * @param last {@link Iterator Forward iterator} to the final position of the sequence. The range checked 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. - * - * @return true if the range [first, last) is sorted into ascending order, - * false otherwise. If the range [first, last) contains less than two elements, - * the function always returns true. - */ - function is_sorted>(first: ForwardIterator, last: ForwardIterator): boolean; - /** - *

    Check whether range is sorted.

    - * - *

    Returns true if the range [first, last) is sorted into ascending order.

    - * - *

    The elements are compared using compare.

    - * - * @param first {@link Iterator Forward iterator} to the initial position of the sequence. - * @param last {@link Iterator Forward iterator} to the final position of the sequence. The range checked 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. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible - * to bool. The value returned indicates whether the element passed as first argument is - * considered to go before the second in the specific strict weak ordering it defines. The function - * shall not modify any of its arguments. - * - * @return true if the range [first, last) is sorted into ascending order, - * false otherwise. If the range [first, last) contains less than two elements, - * the function always returns true. - */ - function is_sorted>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): boolean; - /** - *

    Find first unsorted element in range.

    - * - *

    Returns an iterator to the first element in the range [first, last) which does not follow an - * ascending order.

    - * - *

    The range between first and the iterator returned {@link is_sorted is sorted}.

    - * - *

    If the entire range is sorted, the function returns last.

    - * - *

    The elements are compared using {@link equal_to}.

    - * - * @param first {@link Iterator Forward iterator} to the initial position of the sequence. - * @param last {@link Iterator Forward iterator} to the final position of the sequence. The range checked 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. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible - * to bool. The value returned indicates whether the element passed as first argument is - * considered to go before the second in the specific strict weak ordering it defines. The function - * shall not modify any of its arguments. - * - * @return An iterator to the first element in the range which does not follow an ascending order, or last if - * all elements are sorted or if the range contains less than two elements. - */ - function is_sorted_until>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; - /** - *

    Find first unsorted element in range.

    - * - *

    Returns an iterator to the first element in the range [first, last) which does not follow an - * ascending order.

    - * - *

    The range between first and the iterator returned {@link is_sorted is sorted}.

    - * - *

    If the entire range is sorted, the function returns last.

    - * - *

    The elements are compared using compare.

    - * - * @param first {@link Iterator Forward iterator} to the initial position of the sequence. - * @param last {@link Iterator Forward iterator} to the final position of the sequence. The range checked 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. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible - * to bool. The value returned indicates whether the element passed as first argument is - * considered to go before the second in the specific strict weak ordering it defines. The function - * shall not modify any of its arguments. - * - * @return An iterator to the first element in the range which does not follow an ascending order, or last if - * all elements are sorted or if the range contains less than two elements. - */ - function is_sorted_until>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): ForwardIterator; -} -declare namespace std { - /** - *

    Make heap from range.

    - * - *

    Rearranges the elements in the range [first, last) in such a way that they form a heap.

    - * - *

    A heap is a way to organize the elements of a range that allows for fast retrieval of the element with the - * highest value at any moment (with {@link pop_heap}), even repeatedly, while allowing for fast insertion of new - * elements (with {@link push_heap}).

    - * - *

    The element with the highest value is always pointed by first. The order of the other elements depends on the - * particular implementation, but it is consistent throughout all heap-related functions of this header.

    - * - *

    The elements are compared using {@link less}: The element with the highest value is an element for which this - * would return false when compared to every other element in the range.

    - * - *

    The standard container adaptor {@link PriorityQueue} calls {@link make_heap}, {@link push_heap} and - * {@link pop_heap} automatically to maintain heap properties for a container.

    - * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be - * transformed into a heap. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be transformed - * into a heap. 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. {@link IArrayIterator RandomAccessIterator} shall point to a type for which - * {@link Iterator.swap swap} is properly defined. - */ - function make_heap>(first: RandomAccessIterator, last: RandomAccessIterator): void; - /** - *

    Make heap from range.

    - * - *

    Rearranges the elements in the range [first, last) in such a way that they form a heap.

    - * - *

    A heap is a way to organize the elements of a range that allows for fast retrieval of the element with the - * highest value at any moment (with {@link pop_heap}), even repeatedly, while allowing for fast insertion of new - * elements (with {@link push_heap}).

    - * - *

    The element with the highest value is always pointed by first. The order of the other elements depends on the - * particular implementation, but it is consistent throughout all heap-related functions of this header.

    - * - *

    The elements are compared using compare: The element with the highest value is an element for which this - * would return false when compared to every other element in the range.

    - * - *

    The standard container adaptor {@link PriorityQueue} calls {@link make_heap}, {@link push_heap} and - * {@link pop_heap} automatically to maintain heap properties for a container.

    - * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be - * transformed into a heap. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be transformed - * into a heap. 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. {@link IArrayIterator RandomAccessIterator} shall point to a type for which - * {@link Iterator.swap swap} is properly defined. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value - * convertible to boolean. The value returned indicates whether the element passed as - * first argument is considered to go before the second in the specific strict weak ordering it defines. - * The function shall not modify any of its arguments. This can either be a function pointer or a - * function object. - */ - function make_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; - /** - *

    Push element into heap range.

    - * - *

    Given a heap in the range [first, last - 1), this function extends the range considered a heap to - * [first, last) by placing the value in (last - 1) into its corresponding location within it. - *

    - * - *

    A range can be organized into a heap by calling {@link make_heap}. After that, its heap properties are - * preserved if elements are added and removed from it using {@link push_heap} and {@link pop_heap}, respectively. - *

    - * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the new heap range, including - * the pushed element. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the new heap range, including - * the pushed element. 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. {@link IArrayIterator RandomAccessIterator} shall point to a type for which - * {@link Iterator.swap swap} is properly defined. - */ - function push_heap>(first: RandomAccessIterator, last: RandomAccessIterator): void; - /** - *

    Push element into heap range.

    - * - *

    Given a heap in the range [first, last - 1), this function extends the range considered a heap to - * [first, last) by placing the value in (last - 1) into its corresponding location within it. - *

    - * - *

    A range can be organized into a heap by calling {@link make_heap}. After that, its heap properties are - * preserved if elements are added and removed from it using {@link push_heap} and {@link pop_heap}, respectively. - *

    - * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the new heap range, including - * the pushed element. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the new heap range, including - * the pushed element. 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. {@link IArrayIterator RandomAccessIterator} shall point to a type for which - * {@link Iterator.swap swap} is properly defined. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value - * convertible to boolean. The value returned indicates whether the element passed as - * first argument is considered to go before the second in the specific strict weak ordering it defines. - * The function shall not modify any of its arguments. This can either be a function pointer or a - * function object. - */ - function push_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; - /** - *

    Pop element from heap range.

    - * - *

    Rearranges the elements in the heap range [first, last) in such a way that the part considered a - * heap is shortened by one: The element with the highest value is moved to (last - 1).

    - * - *

    While the element with the highest value is moved from first to (last - 1) (which now is out of the - * heap), the other elements are reorganized in such a way that the range [first, last - 1) preserves - * the properties of a heap.

    - * - *

    A range can be organized into a heap by calling {@link make_heap}. After that, its heap properties are - * preserved if elements are added and removed from it using {@link push_heap} and {@link pop_heap}, respectively. - *

    - * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the heap to be shrank by one. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the heap to be shrank by one. - * 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. - * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} - * is properly defined. - */ - function pop_heap>(first: RandomAccessIterator, last: RandomAccessIterator): void; - /** - *

    Pop element from heap range.

    - * - *

    Rearranges the elements in the heap range [first, last) in such a way that the part considered a - * heap is shortened by one: The element with the highest value is moved to (last - 1).

    - * - *

    While the element with the highest value is moved from first to (last - 1) (which now is out of the - * heap), the other elements are reorganized in such a way that the range [first, last - 1) preserves - * the properties of a heap.

    - * - *

    A range can be organized into a heap by calling {@link make_heap}. After that, its heap properties are - * preserved if elements are added and removed from it using {@link push_heap} and {@link pop_heap}, respectively. - *

    - * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the heap to be shrank by one. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the heap to be shrank by one. - * 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. - * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} - * is properly defined. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value - * convertible to boolean. The value returned indicates whether the element passed as - * first argument is considered to go before the second in the specific strict weak ordering it defines. - * The function shall not modify any of its arguments. This can either be a function pointer or a - * function object. - */ - function pop_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; - /** - *

    Test if range is heap.

    - * - *

    Returns true if the range [first, last) forms a heap, as if constructed with {@link make_heap}. - *

    - * - *

    The elements are compared using {@link less}.

    - * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence. 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. - * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} - * is properly defined. - * - * @return true if the range [first, last) is a heap (as if constructed with - * {@link make_heap}), false otherwise. If the range [first, last) contains less - * than two elements, the function always returns true. - */ - function is_heap>(first: RandomAccessIterator, last: RandomAccessIterator): boolean; - /** - *

    Test if range is heap.

    - * - *

    Returns true if the range [first, last) forms a heap, as if constructed with {@link make_heap}. - *

    - * - *

    The elements are compared using compare.

    - * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence. 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. - * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} - * is properly defined. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value - * convertible to boolean. The value returned indicates whether the element passed as - * first argument is considered to go before the second in the specific strict weak ordering it defines. - * The function shall not modify any of its arguments. This can either be a function pointer or a - * function object. - * - * @return true if the range [first, last) is a heap (as if constructed with - * {@link make_heap}), false otherwise. If the range [first, last) contains less - * than two elements, the function always returns true. - */ - function is_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): boolean; - /** - *

    Find first element not in heap order.

    - * - *

    Returns an iterator to the first element in the range [first, last) which is not in a valid - * position if the range is considered a heap (as if constructed with {@link make_heap}).

    - * - *

    The range between first and the iterator returned is a heap.

    - * - *

    If the entire range is a valid heap, the function returns last.

    - * - *

    The elements are compared using {@link less}.

    - * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence. 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. - * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} - * is properly defined. - */ - function is_heap_until>(first: RandomAccessIterator, last: RandomAccessIterator): RandomAccessIterator; - /** - *

    Find first element not in heap order.

    - * - *

    Returns an iterator to the first element in the range [first, last) which is not in a valid - * position if the range is considered a heap (as if constructed with {@link make_heap}).

    - * - *

    The range between first and the iterator returned is a heap.

    - * - *

    If the entire range is a valid heap, the function returns last.

    - * - *

    The elements are compared using {@link less}.

    - * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence. 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. - * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} - * is properly defined. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value - * convertible to boolean. The value returned indicates whether the element passed as - * first argument is considered to go before the second in the specific strict weak ordering it defines. - * The function shall not modify any of its arguments. This can either be a function pointer or a - * function object. - */ - function is_heap_until>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): RandomAccessIterator; - /** - *

    Sort elements of heap.

    - * - *

    Sorts the elements in the heap range [first, last) into ascending order.

    - * - *

    The elements are compared using {@link less}, which shall be the same as used to construct the heap.

    - * - *

    The range loses its properties as a heap.

    - * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be sorted. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. - * 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. - * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} - * is properly defined. - */ - function sort_heap>(first: RandomAccessIterator, last: RandomAccessIterator): void; - /** - *

    Sort elements of heap.

    - * - *

    Sorts the elements in the heap range [first, last) into ascending order.

    - * - *

    The elements are compared using compare, which shall be the same as used to construct the heap.

    - * - *

    The range loses its properties as a heap.

    - * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be sorted. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. - * 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. - * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} - * is properly defined. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value - * convertible to boolean. The value returned indicates whether the element passed as - * first argument is considered to go before the second in the specific strict weak ordering it defines. - * The function shall not modify any of its arguments. This can either be a function pointer or a - * function object. - */ - function sort_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; -} -declare namespace std { - /** - *

    Return iterator to lower bound.

    - * - *

    Returns an iterator pointing to the first element in the range [first, last) which does not - * compare less than val.

    - * - *

    The elements are compared using {@link less}. The elements in the range shall already be {@link is_sorted sorted} - * according to this same criterion ({@link less}), or at least {@link is_partitioned partitioned} with respect to - * val.

    - * - *

    The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted - * range, which is specially efficient for {@link IArrayIterator random-access iterators}.

    - * - *

    Unlike {@link upper_bound}, the value pointed by the iterator returned by this function may also be equivalent - * to val, and not only greater.

    - * - * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. - * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. 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. - * @param val Value of the lower bound to search for in the range. T shall be a type supporting being compared - * with elements of the range [first, last) as the left-hand side operand of {@link less}. - * - * @return An iterator to the lower bound of val in the range. If all the element in the range compare less than - * val, the function returns last. - */ - function lower_bound>(first: ForwardIterator, last: ForwardIterator, val: T): ForwardIterator; - /** - *

    Return iterator to lower bound.

    - * - *

    Returns an iterator pointing to the first element in the range [first, last) which does not - * compare less than val.

    - * - *

    The elements are compared using compare. The elements in the range shall already be - * {@link is_sorted sorted} according to this same criterion (compare), or at least - * {@link is_partitioned partitioned} with respect to val.

    - * - *

    The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted - * range, which is specially efficient for {@link IArrayIterator random-access iterators}.

    - * - *

    Unlike {@link upper_bound}, the value pointed by the iterator returned by this function may also be equivalent - * to val, and not only greater.

    - * - * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. - * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. 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. - * @param val Value of the lower bound to search for in the range. - * @param compare Binary function that accepts two arguments (the first of the type pointed by ForwardIterator, - * and the second, always val), and returns a value convertible to bool. The value - * returned indicates whether the first argument is considered to go before the second. The function - * shall not modify any of its arguments. - * - * @return An iterator to the lower bound of val in the range. If all the element in the range compare less than - * val, the function returns last. - */ - function lower_bound>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): ForwardIterator; - /** - *

    Return iterator to upper bound.

    - * - *

    Returns an iterator pointing to the first element in the range [first, last) which compares - * greater than val.

    - * - *

    The elements are compared using {@link less}. The elements in the range shall already be {@link is_sorted sorted} - * according to this same criterion ({@link less}), or at least {@link is_partitioned partitioned} with respect to - * val.

    - * - *

    The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted - * range, which is specially efficient for {@link IArrayIterator random-access iterators}.

    - * - *

    Unlike {@link lower_bound}, the value pointed by the iterator returned by this function cannot be equivalent to - * val, only greater.

    - * - * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. - * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. 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. - * @param val Value of the lower bound to search for in the range. T shall be a type supporting being compared - * with elements of the range [first, last) as the left-hand side operand of {@link less}. - * - * @return An iterator to the upper bound of val in the range. If no element in the range comparse greater than - * val, the function returns last. - */ - function upper_bound>(first: ForwardIterator, last: ForwardIterator, val: T): ForwardIterator; - /** - *

    Return iterator to upper bound.

    - * - *

    Returns an iterator pointing to the first element in the range [first, last) which compares - * greater than val.

    - * - *

    The elements are compared using compare. The elements in the range shall already be - * {@link is_sorted sorted} according to this same criterion (compare), or at least - * {@link is_partitioned partitioned} with respect to val.

    - * - *

    The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted - * range, which is specially efficient for {@link IArrayIterator random-access iterators}.

    - * - *

    Unlike {@link lower_bound}, the value pointed by the iterator returned by this function cannot be equivalent to - * val, only greater.

    - * - * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. - * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. 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. - * @param val Value of the lower bound to search for in the range. - * @param compare Binary function that accepts two arguments (the first of the type pointed by ForwardIterator, - * and the second, always val), and returns a value convertible to bool. The value - * returned indicates whether the first argument is considered to go before the second. The function - * shall not modify any of its arguments. - * - * @return An iterator to the upper bound of val in the range. If no element in the range comparse greater than - * val, the function returns last. - */ - function upper_bound>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): ForwardIterator; - /** - *

    Get subrange of equal elements.

    - * - *

    Returns the bounds of the subrange that includes all the elements of the range [first, last) with - * values equivalent to val.

    - * - *

    The elements are compared using {@link less}. Two elements, ax/i> and y are considered equivalent - * if (!std.less(x, y) && !std.less(y, x)).

    - * - *

    The elements in the range shall already be {@link is_sorted sorted} according to this same criterion - * ({@link less}), or at least {@link is_partitioned partitioned} with respect to val.

    - * - *

    If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both - * iterators pointing to the nearest value greater than val, if any, or to last, if val compares - * greater than all the elements in the range.

    - * - * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. - * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. 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. - * @param val Value of the lower bound to search for in the range. T shall be a type supporting being compared - * with elements of the range [first, last) as the left-hand side operand of {@link less}. - * - * @return A {@link Pair} object, whose member {@link Pair.first} is an iterator to the lower bound of the subrange of - * equivalent values, and {@link Pair.second} its upper bound. The values are the same as those that would be - * returned by functions {@link lower_bound} and {@link upper_bound} respectively. - */ - function equal_range>(first: ForwardIterator, last: ForwardIterator, val: T): Pair; - /** - *

    Get subrange of equal elements.

    - * - *

    Returns the bounds of the subrange that includes all the elements of the range [first, last) with - * values equivalent to val.

    - * - *

    The elements are compared using compare. Two elements, ax/i> and y are considered equivalent - * if (!compare(x, y) && !compare(y, x)).

    - * - *

    The elements in the range shall already be {@link is_sorted sorted} according to this same criterion - * (compare), or at least {@link is_partitioned partitioned} with respect to val.

    - * - *

    If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both - * iterators pointing to the nearest value greater than val, if any, or to last, if val compares - * greater than all the elements in the range.

    - * - * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. - * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. 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. - * @param val Value of the lower bound to search for in the range. - * @param compare Binary function that accepts two arguments of the type pointed by ForwardIterator (and of type - * T), and returns a value convertible to bool. The value returned indicates whether - * the first argument is considered to go before the second. The function shall not modify any of its - * arguments. - * - * @return A {@link Pair} object, whose member {@link Pair.first} is an iterator to the lower bound of the subrange of - * equivalent values, and {@link Pair.second} its upper bound. The values are the same as those that would be - * returned by functions {@link lower_bound} and {@link upper_bound} respectively. - */ - function equal_range>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): Pair; - /** - *

    Get subrange of equal elements.

    - * - *

    Returns the bounds of the subrange that includes all the elements of the range [first, last) with - * values equivalent to val.

    - * - *

    The elements are compared using {@link less}. Two elements, x and y are considered equivalent - * if (!std.less(x, y) && !std.less(y, x)).

    - * - *

    The elements in the range shall already be {@link is_sorted sorted} according to this same criterion - * ({@link less}), or at least {@link is_partitioned partitioned} with respect to val.

    - * - *

    If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both - * iterators pointing to the nearest value greater than val, if any, or to last, if val compares - * greater than all the elements in the range.

    - * - * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. - * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. 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. - * @param val Value of the lower bound to search for in the range. T shall be a type supporting being compared - * with elements of the range [first, last) as the left-hand side operand of {@link less}. - * - * @return true if an element equivalent to val is found, and false otherwise. - */ - function binary_search>(first: ForwardIterator, last: ForwardIterator, val: T): boolean; - /** - *

    Get subrange of equal elements.

    - * - *

    Returns the bounds of the subrange that includes all the elements of the range [first, last) with - * values equivalent to val.

    - * - *

    The elements are compared using {compare}. Two elements, x and y are considered equivalent - * if (!compare(x, y) && !compare(y, x)).

    - * - *

    The elements in the range shall already be {@link is_sorted sorted} according to this same criterion - * (compare), or at least {@link is_partitioned partitioned} with respect to val.

    - * - *

    If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both - * iterators pointing to the nearest value greater than val, if any, or to last, if val compares - * greater than all the elements in the range.

    - * - * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. - * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. 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. - * @param val Value of the lower bound to search for in the range. - * @param compare Binary function that accepts two arguments of the type pointed by ForwardIterator (and of type - * T), and returns a value convertible to bool. The value returned indicates whether - * the first argument is considered to go before the second. The function shall not modify any of its - * arguments. - * - * @return true if an element equivalent to val is found, and false otherwise. - */ - function binary_search>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): boolean; -} -declare namespace std { - /** - *

    Test whether range is partitioned.

    - * - *

    Returns true if all the elements in the range [first, last) for which pred - * returns true precede those for which it returns false.

    - * - *

    If the range is {@link IContainer.empty empty}, the function returns true.

    - * - * @param first {@link Iterator Input iterator} to the initial position of the sequence. - * @param last {@link Iterator Input iterator} to the final position of the sequence. 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. - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element belongs to the first group (if - * true, the element is expected before all the elements for which it returns - * false). The function shall not modify its argument. - * - * @return true if all the elements in the range [first, last) for which pred returns - * true precede those for which it returns false. Otherwise it returns - * false. If the range is {@link IContainer.empty empty}, the function returns true. - */ - function is_partitioned>(first: InputIterator, last: InputIterator, pred: (x: T) => boolean): boolean; - /** - *

    Partition range in two.

    - * - *

    Rearranges the elements from the range [first, last), in such a way that all the elements for - * which pred returns true precede all those for which it returns false. The iterator - * returned points to the first element of the second group.

    - * - *

    The relative ordering within each group is not necessarily the same as before the call. See - * {@link stable_partition} for a function with a similar behavior but with stable ordering within each group.

    - * - * @param first {@link Iterator Forward iterator} to the initial position of the sequence to partition. - * @param last {@link Iterator Forward iterator} to the final position of the sequence to partition. 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. - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element belongs to the first group (if - * true, the element is expected before all the elements for which it returns - * false). The function shall not modify its argument. - * - * @return An iterator that points to the first element of the second group of elements (those for which pred - * returns false), or last if this group is {@link IContainer.empty empty}. - */ - function partition>(first: BidirectionalIterator, last: BidirectionalIterator, pred: (x: T) => boolean): BidirectionalIterator; - /** - *

    Partition range in two - stable ordering.

    - * - *

    Rearranges the elements in the range [first, last), in such a way that all the elements for which - * pred returns true precede all those for which it returns false, and, unlike - * function {@link partition}, the relative order of elements within each group is preserved.

    - * - *

    This is generally implemented using an internal temporary buffer.

    - * - * @param first {@link Iterator Bidirectional iterator} to the initial position of the sequence to partition. - * @param last {@link Iterator Bidirectional iterator} to the final position of the sequence to partition. 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. - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element belongs to the first group (if - * true, the element is expected before all the elements for which it returns - * false). The function shall not modify its argument. - * - * @return An iterator that points to the first element of the second group of elements (those for which pred - * returns false), or last if this group is {@link IContainer.empty empty}. - */ - function stable_partition>(first: BidirectionalIterator, last: BidirectionalIterator, pred: (x: T) => boolean): BidirectionalIterator; - /** - *

    Partition range into two.

    - * - *

    Copies the elements in the range [first, last) for which pred returns true - * into the range pointed by result_true, and those for which it does not into the range pointed by - * result_false.

    - * - * @param first {@link Iterator Input iterator} to the initial position of the range to be copy-partitioned. - * @param last {@link Iterator Input iterator} to the final position of the range to be copy-partitioned. 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. - * @param result_true {@link Iterator Output iterator} to the initial position of the range where the elements for - * which pred returns true are stored. - * @param result_false {@link Iterator Output iterator} to the initial position of the range where the elements for - * which pred returns false are stored. - * @param pred Unary function that accepts an element pointed by InputIterator as argument, and returns a value - * convertible to bool. The value returned indicates on which result range the element is - * copied. The function shall not modify its argument. - * - * @return A {@link Pair} of iterators with the end of the generated sequences pointed by result_true and - * result_false, respectivelly. Its member {@link Pair.first first} points to the element that follows - * the last element copied to the sequence of elements for which pred returned true. Its - * member {@link Pair.second second} points to the element that follows the last element copied to the sequence - * of elements for which pred returned false. - */ - function partition_copy, OutputIterator1 extends base.ILinearIterator, OutputIterator2 extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result_true: OutputIterator1, result_false: OutputIterator2, pred: (val: T) => T): Pair; - /** - *

    Get partition point.

    - * - *

    Returns an iterator to the first element in the partitioned range [first, last) for which - * pred is not true, indicating its partition point.

    - * - *

    The elements in the range shall already {@link is_partitioned be partitioned}, as if {@link partition} had been - * called with the same arguments.

    - * - *

    The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted - * range, which is specially efficient for {@link Iteartor random-access iterators}.

    - * - * @param first {@link Iterator Forward iterator} to the initial position of the partitioned sequence. - * @param last {@link Iterator Forward iterator} to the final position of the partitioned sequence. The range checked - * is [first, last), which contains all the elements between first an last, - * including the element pointed by first but not the element pointed by last. - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element goes before the partition point (if - * true, it goes before; if false goes at or after it). The function shall not - * modify its argument. - * - * @return An iterator to the first element in the partitioned range [first, last) for which pred - * is not true, or last if it is not true for any element. - */ - function partition_point>(first: ForwardIterator, last: ForwardIterator, pred: (x: T) => boolean): ForwardIterator; -} -declare namespace std { - /** - *

    Merge sorted ranges.

    - * - *

    Combines the elements in the sorted ranges [first1, last1) and [first2, last2), into - * a new range beginning at result with all its elements sorted.

    - * - *

    The elements are compared using {@link less}. The elements in both ranges shall already be ordered according to - * this same criterion ({@link less}). The resulting range is also sorted according to this.

    - * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting combined - * range is stored. Its size is equal to the sum of both ranges above. - * - * @return An iterator pointing to the past-the-end element in the resulting sequence. - */ - function merge, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; - /** - *

    Merge sorted ranges.

    - * - *

    Combines the elements in the sorted ranges [first1, last1) and [first2, last2), into - * a new range beginning at result with all its elements sorted.

    - * - *

    The elements are compared using {@link less}. The elements in both ranges shall already be ordered according to - * this same criterion (compare). The resulting range is also sorted according to this.

    - * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting combined - * range is stored. Its size is equal to the sum of both ranges above. - * @param compare Binary function that accepts two arguments of the types pointed by the iterators, and returns a value - * convertible to bool. The value returned indicates whether the first argument is - * considered to go before the second in the specific strict weak ordering it defines. The - * function shall not modify any of its arguments. - * - * @return An iterator pointing to the past-the-end element in the resulting sequence. - */ - function merge, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; - /** - *

    Merge consecutive sorted ranges.

    - * - *

    Merges two consecutive sorted ranges: [first, middle) and [middle, last), putting - * the result into the combined sorted range [first, last).

    - * - *

    The elements are compared using {@link less}. The elements in both ranges shall already be ordered according to - * this same criterion ({@link less}). The resulting range is also sorted according to this.

    - * - *

    The function preserves the relative order of elements with equivalent values, with the elements in the first - * range preceding those equivalent in the second.

    - * - * @param first {@link Iterator Bidirectional iterator} to the initial position in the first sorted sequence to merge. - * This is also the initial position where the resulting merged range is stored. - * @param middle {@link Iterator Bidirectional iterator} to the initial position of the second sorted sequence, which - * because both sequences must be consecutive, matches the past-the-end position of the first - * sequence. - * @param last {@link Iterator Bidirectional iterator} to the past-the-end position of the second sorted - * sequence. This is also the past-the-end position of the range where the resulting merged range is - * stored. - */ - function inplace_merge>(first: BidirectionalIterator, middle: BidirectionalIterator, last: BidirectionalIterator): void; - /** - *

    Merge consecutive sorted ranges.

    - * - *

    Merges two consecutive sorted ranges: [first, middle) and [middle, last), putting - * the result into the combined sorted range [first, last).

    - * - *

    The elements are compared using compare. The elements in both ranges shall already be ordered according - * to this same criterion (compare). The resulting range is also sorted according to this.

    - * - *

    The function preserves the relative order of elements with equivalent values, with the elements in the first - * range preceding those equivalent in the second.

    - * - * @param first {@link Iterator Bidirectional iterator} to the initial position in the first sorted sequence to merge. - * This is also the initial position where the resulting merged range is stored. - * @param middle {@link Iterator Bidirectional iterator} to the initial position of the second sorted sequence, which - * because both sequences must be consecutive, matches the past-the-end position of the first - * sequence. - * @param last {@link Iterator Bidirectional iterator} to the past-the-end position of the second sorted - * sequence. This is also the past-the-end position of the range where the resulting merged range is - * stored. - * @param compare Binary function that accepts two arguments of the types pointed by the iterators, and returns a value - * convertible to bool. The value returned indicates whether the first argument is - * considered to go before the second in the specific strict weak ordering it defines. The - * function shall not modify any of its arguments. - */ - function inplace_merge>(first: BidirectionalIterator, middle: BidirectionalIterator, last: BidirectionalIterator, compare: (x: T, y: T) => boolean): void; - /** - *

    Test whether sorted range includes another sorted range.

    - * - *

    Returns true if the sorted range [first1, last1) contains all the elements in the - * sorted range [first2, last2).

    - * - *

    The elements are compared using {@link less}. Two elements, x and y are considered equivalent - * if (!std.less(x, y) && !std.less(y, x)).

    - * - *

    The elements in the range shall already be ordered according to this same criterion ({@link less}).

    - * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence (which is tested on - * whether it contains the second sequence). The range used is [first1, last1), which - * contains all the elements between first1 and last1, including the element pointed by - * first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. (which is tested - * on whether it is contained in the first sequence). The range used is [first2, last2). - * - * @return true if every element in the range [first2, last2) is contained in the range - * [first1, last1), false otherwise. If [first2, last2) is an empty - * range, the function returns true. - */ - function includes, InputIterator2 extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2): boolean; - /** - *

    Test whether sorted range includes another sorted range.

    - * - *

    Returns true if the sorted range [first1, last1) contains all the elements in the - * sorted range [first2, last2).

    - * - *

    The elements are compared using compare. Two elements, x and y are considered equivalent - * if (!compare(x, y) && !compare(y, x)).

    - * - *

    The elements in the range shall already be ordered according to this same criterion (compare).

    - * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence (which is tested on - * whether it contains the second sequence). The range used is [first1, last1), which - * contains all the elements between first1 and last1, including the element pointed by - * first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. (which is tested - * on whether it is contained in the first sequence). The range used is [first2, last2). - * @param compare Binary function that accepts two elements as arguments (one from each of the two sequences, in the - * same order), and returns a value convertible to bool. The value returned indicates - * whether the element passed as first argument is considered to go before the second in the specific - * strict weak ordering it defines. The function shall not modify any of its arguments. - * - * @return true if every element in the range [first2, last2) is contained in the range - * [first1, last1), false otherwise. If [first2, last2) is an empty - * range, the function returns true. - */ - function includes, InputIterator2 extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, compare: (x: T, y: T) => boolean): boolean; - /** - *

    Union of two sorted ranges.

    - * - *

    Constructs a sorted range beginning in the location pointed by result with the set union of the - * two sorted ranges [first1, last1) and [first2, last2).

    - * - *

    The union of two sets is formed by the elements that are present in either one of the sets, or in both. - * Elements from the second range that have an equivalent element in the first range are not copied to the resulting - * range.

    - * - *

    The elements are compared using {@link less}. Two elements, x and y are considered equivalent - * if (!std.less(x, y) && !std.less(y, x)).

    - * - *

    The elements in the ranges shall already be ordered according to this same criterion ({@link less}). The - * resulting range is also sorted according to this.

    - * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element from the other ranges. - * - * @return An iterator to the end of the constructed range. - */ - function set_union, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; - /** - *

    Union of two sorted ranges.

    - * - *

    Constructs a sorted range beginning in the location pointed by result with the set union of the - * two sorted ranges [first1, last1) and [first2, last2).

    - * - *

    The union of two sets is formed by the elements that are present in either one of the sets, or in both. - * Elements from the second range that have an equivalent element in the first range are not copied to the resulting - * range.

    - * - *

    The elements are compared using compare. Two elements, x and y are considered equivalent - * if (!compare(x, y) && !compare(y, x)).

    - * - *

    The elements in the ranges shall already be ordered according to this same criterion (compare). The - * resulting range is also sorted according to this.

    - * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element from the other ranges. - * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a - * value convertible to bool. The value returned indicates whether the first argument is - * considered to go before the second in the specific strict weak ordering it defines. The - * function shall not modify any of its arguments. - * - * @return An iterator to the end of the constructed range. - */ - function set_union, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; - /** - *

    Intersection of two sorted ranges.

    - * - *

    Constructs a sorted range beginning in the location pointed by result with the set intersection of - * the two sorted ranges [first1, last1) and [first2, last2).

    - * - *

    The intersection of two sets is formed only by the elements that are present in both sets. The elements - * copied by the function come always from the first range, in the same order.

    - * - *

    The elements are compared using {@link less}. Two elements, x and y are considered equivalent - * if (!std.less(x, y) && !std.less(y, x)).

    - * - *

    The elements in the ranges shall already be ordered according to this same criterion ({@link less}). The - * resulting range is also sorted according to this.

    - * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element from the first range. - * - * @return An iterator to the end of the constructed range. - */ - function set_intersection, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; - /** - *

    Intersection of two sorted ranges.

    - * - *

    Constructs a sorted range beginning in the location pointed by result with the set intersection of - * the two sorted ranges [first1, last1) and [first2, last2).

    - * - *

    The intersection of two sets is formed only by the elements that are present in both sets. The elements - * copied by the function come always from the first range, in the same order.

    - * - *

    The elements are compared using compare. Two elements, x and y are considered equivalent - * if (!compare(x, y) && !compare(y, x)).

    - * - *

    The elements in the ranges shall already be ordered according to this same criterion (compare). The - * resulting range is also sorted according to this.

    - * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element from the first range. - * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a - * value convertible to bool. The value returned indicates whether the first argument is - * considered to go before the second in the specific strict weak ordering it defines. The - * function shall not modify any of its arguments. - * - * @return An iterator to the end of the constructed range. - */ - function set_intersection, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; - /** - *

    Difference of two sorted ranges.

    - * - *

    Constructs a sorted range beginning in the location pointed by result with the set difference of - * the sorted range [first1, last1) with respect to the sorted range [first2, last2).

    - * - *

    The difference of two sets is formed by the elements that are present in the first set, but not in the - * second one. The elements copied by the function come always from the first range, in the same order.

    - * - *

    For containers supporting multiple occurrences of a value, the difference includes as many occurrences of - * a given value as in the first range, minus the amount of matching elements in the second, preserving order.

    - * - *

    Notice that this is a directional operation - for a symmetrical equivalent, see {@link set_symmetric_difference}. - *

    - * - *

    The elements are compared using {@link less}. Two elements, x and y are considered equivalent - * if (!std.less(x, y) && !std.less(y, x)).

    - * - *

    The elements in the ranges shall already be ordered according to this same criterion ({@link less}). The - * resulting range is also sorted according to this.

    - * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element from the first range. - * - * @return An iterator to the end of the constructed range. - */ - function set_difference, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; - /** - *

    Difference of two sorted ranges.

    - * - *

    Constructs a sorted range beginning in the location pointed by result with the set difference of - * the sorted range [first1, last1) with respect to the sorted range [first2, last2).

    - * - *

    The difference of two sets is formed by the elements that are present in the first set, but not in the - * second one. The elements copied by the function come always from the first range, in the same order.

    - * - *

    For containers supporting multiple occurrences of a value, the difference includes as many occurrences of - * a given value as in the first range, minus the amount of matching elements in the second, preserving order.

    - * - *

    Notice that this is a directional operation - for a symmetrical equivalent, see {@link set_symmetric_difference}. - *

    - * - *

    The elements are compared using compare. Two elements, x and y are considered equivalent - * if (!compare(x, y) && !compare(y, x)).

    - * - *

    The elements in the ranges shall already be ordered according to this same criterion (compare). The - * resulting range is also sorted according to this.

    - * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element from the first range. - * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a - * value convertible to bool. The value returned indicates whether the first argument is - * considered to go before the second in the specific strict weak ordering it defines. The - * function shall not modify any of its arguments. - * - * @return An iterator to the end of the constructed range. - */ - function set_difference, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; - /** - *

    Symmetric difference of two sorted ranges.

    - * - *

    Constructs a sorted range beginning in the location pointed by0 result with the set - * symmetric difference of the two sorted ranges [first1, last1) and [first2, last2). - *

    - * - *

    The symmetric difference of two sets is formed by the elements that are present in one of the sets, but - * not in the other. Among the equivalent elements in each range, those discarded are those that appear before in the - * existent order before the call. The existing order is also preserved for the copied elements.

    - * - *

    The elements are compared using {@link less}. Two elements, x and y are considered equivalent - * if (!std.less(x, y) && !std.less(y, x)).

    - * - *

    The elements in the ranges shall already be ordered according to this same criterion ({@link std.less}). The - * resulting range is also sorted according to this.

    - * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element from the other ranges. - * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a - * value convertible to bool. The value returned indicates whether the first argument is - * considered to go before the second in the specific strict weak ordering it defines. The - * function shall not modify any of its arguments. - * - * @return An iterator to the end of the constructed range. - */ - function set_symmetric_difference, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; - /** - *

    Symmetric difference of two sorted ranges.

    - * - *

    Constructs a sorted range beginning in the location pointed by0 result with the set - * symmetric difference of the two sorted ranges [first1, last1) and [first2, last2). - *

    - * - *

    The symmetric difference of two sets is formed by the elements that are present in one of the sets, but - * not in the other. Among the equivalent elements in each range, those discarded are those that appear before in the - * existent order before the call. The existing order is also preserved for the copied elements.

    - * - *

    The elements are compared using compare. Two elements, x and y are considered equivalent - * if (!compare(x, y) && !compare(y, x)).

    - * - *

    The elements in the ranges shall already be ordered according to this same criterion (compare). The - * resulting range is also sorted according to this.

    - * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element from the other ranges. - * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a - * value convertible to bool. The value returned indicates whether the first argument is - * considered to go before the second in the specific strict weak ordering it defines. The - * function shall not modify any of its arguments. - * - * @return An iterator to the end of the constructed range. - */ - function set_symmetric_difference, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; -} -declare namespace std { - /** - *

    Return the smallest.

    - * - *

    Returns the smallest of all the elements in the args.

    - * - * @param args Values to compare. - * - * @return The lesser of the values passed as arguments. - */ - function min(...args: T[]): T; - /** - *

    Return the largest.

    - * - *

    Returns the largest of all the elements in the args.

    - * - * @param args Values to compare. - * - * @return The largest of the values passed as arguments. - */ - function max(...args: T[]): T; - /** - *

    Return smallest and largest elements.

    - * - *

    Returns a {@link Pair} with the smallest of all the elements in the args as first element (the first of - * them, if there are more than one), and the largest as second (the last of them, if there are more than one).

    - * - * @param args Values to compare. - * - * @return The lesser and greatest of the values passed as arguments. - */ - function minmax(...args: T[]): Pair; - /** - *

    Return smallest element in range.

    - * - *

    Returns an iterator pointing to the element with the smallest value in the range [first, last). - *

    - * - *

    The comparisons are performed using either {@link less}; An element is the smallest if no other element - * compares less than it. If more than one element fulfills this condition, the iterator returned points to the first - * of such elements.

    - * - * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. - * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. 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. - * - * @return An iterator to smallest value in the range, or last if the range is empty. - */ - function min_element>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; - /** - *

    Return smallest element in range.

    - * - *

    Returns an iterator pointing to the element with the smallest value in the range [first, last). - *

    - * - *

    The comparisons are performed using either compare; An element is the smallest if no other element - * compares less than it. If more than one element fulfills this condition, the iterator returned points to the first - * of such elements.

    - * - * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. - * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. 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. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible - * to bool. The value returned indicates whether the element passed as first argument is - * considered less than the second. The function shall not modify any of its arguments. - * - * @return An iterator to smallest value in the range, or last if the range is empty. - */ - function min_element>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): ForwardIterator; - /** - *

    Return largest element in range.

    - * - *

    Returns an iterator pointing to the element with the largest value in the range [first, last). - *

    - * - *

    The comparisons are performed using either {@link greater}; An element is the largest if no other element - * compares less than it. If more than one element fulfills this condition, the iterator returned points to the first - * of such elements.

    - * - * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. - * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. 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. - * - * @return An iterator to largest value in the range, or last if the range is empty. - */ - function max_element>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; - /** - *

    Return largest element in range.

    - * - *

    Returns an iterator pointing to the element with the largest value in the range [first, last). - *

    - * - *

    The comparisons are performed using either compare; An element is the largest if no other element - * compares less than it. If more than one element fulfills this condition, the iterator returned points to the first - * of such elements.

    - * - * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. - * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. 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. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible - * to bool. The value returned indicates whether the element passed as first argument is - * considered less than the second. The function shall not modify any of its arguments. - * - * @return An iterator to largest value in the range, or last if the range is empty. - */ - function max_element>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): ForwardIterator; - /** - *

    Return smallest and largest elements in range.

    - * - *

    Returns a {@link Pair} with an iterator pointing to the element with the smallest value in the range - * [first, last) as first element, and the largest as second.

    - * - *

    The comparisons are performed using either {@link less} and {@link greater}.

    - * - *

    If more than one equivalent element has the smallest value, the first iterator points to the first of such - * elements.

    - * - *

    If more than one equivalent element has the largest value, the second iterator points to the last of such - * elements.

    - * - * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. - * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. 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. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible - * to bool. The value returned indicates whether the element passed as first argument is - * considered less than the second. The function shall not modify any of its arguments. - * - * @return A {@link Pair} with an iterator pointing to the element with the smallest value in the range - * [first, last) as first element, and the largest as second. - */ - function minmax_element>(first: ForwardIterator, last: ForwardIterator): Pair; - /** - *

    Return smallest and largest elements in range.

    - * - *

    Returns a {@link Pair} with an iterator pointing to the element with the smallest value in the range - * [first, last) as first element, and the largest as second.

    - * - *

    The comparisons are performed using either compare.

    - * - *

    If more than one equivalent element has the smallest value, the first iterator points to the first of such - * elements.

    - * - *

    If more than one equivalent element has the largest value, the second iterator points to the last of such - * elements.

    - * - * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. - * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. 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. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible - * to bool. The value returned indicates whether the element passed as first argument is - * considered less than the second. The function shall not modify any of its arguments. - * - * @return A {@link Pair} with an iterator pointing to the element with the smallest value in the range - * [first, last) as first element, and the largest as second. - */ - function minmax_element>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): Pair; - /** - *

    Test whether range is permutation of another.

    - * - *

    Compares the elements in the range [first1, last1) with those in the range beginning at - * first2, and returns true if all of the elements in both ranges match, even in a different - * order.

    - * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to - * as many elements of this sequence as those in the range [first1, last1). - * - * @return true if all the elements in the range [first1, last1) compare equal to those - * of the range starting at first2 in any order, and false otherwise. - */ - function is_permutation, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2): boolean; - /** - *

    Test whether range is permutation of another.

    - * - *

    Compares the elements in the range [first1, last1) with those in the range beginning at - * first2, and returns true if all of the elements in both ranges match, even in a different - * order.

    - * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to - * as many elements of this sequence as those in the range [first1, last1). - * @param pred Binary function that accepts two elements as argument (one of each of the two sequences, in the same - * order), and returns a value convertible to bool. The value returned indicates whether - * the elements are considered to match in the context of this function. - * - * @return true if all the elements in the range [first1, last1) compare equal to those - * of the range starting at first2 in any order, and false otherwise. - */ - function is_permutation, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, pred: (x: T, y: T) => boolean): boolean; - /** - * Transform range to previous permutation. - * - * Rearranges the elements in the range [*first*, *last*) into the previous *lexicographically-ordered* permutation. - * - * A *permutation* is each one of the N! possible arrangements the elements can take (where *N* is the number of - * elements in the range). Different permutations can be ordered according to how they compare - * {@link lexicographicaly lexicographical_compare} to each other; The first such-sorted possible permutation (the one - * that would compare *lexicographically smaller* to all other permutations) is the one which has all its elements - * sorted in ascending order, and the largest has all its elements sorted in descending order. - * - * The comparisons of individual elements are performed using the {@link std.less std.less()} function. - * - * If the function can determine the previous permutation, it rearranges the elements as such and returns true. If - * that was not possible (because it is already at the lowest possible permutation), it rearranges the elements - * according to the last permutation (sorted in descending order) and returns false. - * - * @param first Bidirectional iterators to the initial positions of the sequence - * @param last Bidirectional iterators to the final positions of the sequence. 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*. - * - * @return true if the function could rearrange the object as a lexicographicaly smaller permutation. Otherwise, the - * function returns false to indicate that the arrangement is not less than the previous, but the largest - * possible (sorted in descending order). - */ - function prev_permutation>(first: BidirectionalIterator, last: BidirectionalIterator): boolean; - /** - * Transform range to previous permutation. - * - * Rearranges the elements in the range [*first*, *last*) into the previous *lexicographically-ordered* permutation. - * - * A *permutation* is each one of the N! possible arrangements the elements can take (where *N* is the number of - * elements in the range). Different permutations can be ordered according to how they compare - * {@link lexicographicaly lexicographical_compare} to each other; The first such-sorted possible permutation (the one - * that would compare *lexicographically smaller* to all other permutations) is the one which has all its elements - * sorted in ascending order, and the largest has all its elements sorted in descending order. - * - * The comparisons of individual elements are performed using the *compare*. - * - * If the function can determine the previous permutation, it rearranges the elements as such and returns true. If - * that was not possible (because it is already at the lowest possible permutation), it rearranges the elements - * according to the last permutation (sorted in descending order) and returns false. - * - * @param first Bidirectional iterators to the initial positions of the sequence - * @param last Bidirectional iterators to the final positions of the sequence. 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*. - * @param compare Binary function that accepts two arguments of the type pointed by BidirectionalIterator, and returns - * a value convertible to bool. The value returned indicates whether the first argument is considered - * to go before the second in the specific strict weak ordering it defines. - * - * @return true if the function could rearrange the object as a lexicographicaly smaller permutation. Otherwise, the - * function returns false to indicate that the arrangement is not less than the previous, but the largest - * possible (sorted in descending order). - */ - function prev_permutation>(first: BidirectionalIterator, last: BidirectionalIterator, compare: (x: T, y: T) => boolean): boolean; - /** - * Transform range to next permutation. - * - * Rearranges the elements in the range [*first*, *last*) into the next *lexicographically greater* permutation. - * - * A permutation is each one of the *N!* possible arrangements the elements can take (where *N* is the number of - * elements in the range). Different permutations can be ordered according to how they compare - * {@link lexicographicaly lexicographical_compare} to each other; The first such-sorted possible permutation (the one - * that would compare *lexicographically smaller* to all other permutations) is the one which has all its elements - * sorted in ascending order, and the largest has all its elements sorted in descending order. - * - * The comparisons of individual elements are performed using the {@link std.less} function. - * - * If the function can determine the next higher permutation, it rearranges the elements as such and returns true. If - * that was not possible (because it is already at the largest possible permutation), it rearranges the elements - * according to the first permutation (sorted in ascending order) and returns false. - * - * @param first Bidirectional iterators to the initial positions of the sequence - * @param last Bidirectional iterators to the final positions of the sequence. 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*. - * - * @return true if the function could rearrange the object as a lexicographicaly greater permutation. Otherwise, the - * function returns false to indicate that the arrangement is not greater than the previous, but the lowest - * possible (sorted in ascending order). - */ - function next_permutation>(first: BidirectionalIterator, last: BidirectionalIterator): boolean; - /** - * Transform range to next permutation. - * - * Rearranges the elements in the range [*first*, *last*) into the next *lexicographically greater* permutation. - * - * A permutation is each one of the *N!* possible arrangements the elements can take (where *N* is the number of - * elements in the range). Different permutations can be ordered according to how they compare - * {@link lexicographicaly lexicographical_compare} to each other; The first such-sorted possible permutation (the one - * that would compare *lexicographically smaller* to all other permutations) is the one which has all its elements - * sorted in ascending order, and the largest has all its elements sorted in descending order. - * - * The comparisons of individual elements are performed using the *compare*. - * - * If the function can determine the next higher permutation, it rearranges the elements as such and returns true. If - * that was not possible (because it is already at the largest possible permutation), it rearranges the elements - * according to the first permutation (sorted in ascending order) and returns false. - * - * @param first Bidirectional iterators to the initial positions of the sequence - * @param last Bidirectional iterators to the final positions of the sequence. 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*. - * @param compare Binary function that accepts two arguments of the type pointed by BidirectionalIterator, and returns - * a value convertible to bool. The value returned indicates whether the first argument is considered - * to go before the second in the specific strict weak ordering it defines. - * - * @return true if the function could rearrange the object as a lexicographicaly greater permutation. Otherwise, the - * function returns false to indicate that the arrangement is not greater than the previous, but the lowest - * possible (sorted in ascending order). - */ - function next_permutation>(first: BidirectionalIterator, last: BidirectionalIterator, compare: (x: T, y: T) => boolean): boolean; -} -declare namespace std.base { - /** - *

    Static class holding enumeration codes of color of Red-black tree.

    - * - *

    Color codes imposed to nodes of RB-Tree are following those rules:

    - * - *
      - *
    1. A node is either red or black.
    2. - *
    3. The root is black. This rule is sometimes omitted. Since the root can - * always be changed from red to black, but not - * necessarily vice versa, this rule has little effect on analysis.
    4. - *
    5. All leaves (NIL; null) are black.
    6. - *
    7. If a node is red, then both its children are - * black.
    8. - *
    9. Every path from a given node to any of its descendant NIL nodes contains the same number of - * black nodes. Some definitions: the number of - * black nodes from the root to a node is the node's - * black depth; the uniform number of black - * nodes in all paths from root to the leaves is called the black-height of - * the red-black tree.
    10. - *
    - * - * @author Migrated by Jeongho Nam - */ - enum Color { - /** - *

    Code of color black.

    - * - *
      - *
    • Those are clearly black: root, leaf nodes or children nodes of red.
    • - *
    • Every path from a given nodes containes the same number of black nodes exclude NIL(s).
    • - *
    - */ - BLACK = 0, - /** - *

    Code of color red.

    - */ - RED = 1, - } -} -declare namespace std.base { - /** - *

    An abstract container.

    - * - *

    - * - *

    - * - *

    Container properties

    - *
    - *
    Sequence
    - *
    Elements in sequence containers are ordered in a strict linear sequence. Individual elements are - * accessed by their position in this sequence.
    - * - *
    Doubly-linked list
    - *
    Each element keeps information on how to locate the next and the previous elements, allowing - * constant time insert and erase operations before or after a specific element (even of entire ranges), - * but no direct random access.
    - *
    - * - * @param Type of elements. - * - * @author Jeongho Nam - */ - abstract class Container implements IContainer { - /** - * Default Constructor. - */ - protected constructor(); - /** - * @inheritdoc - */ - abstract assign>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - abstract begin(): Iterator; - /** - * @inheritdoc - */ - abstract end(): Iterator; - /** - * @inheritdoc - */ - abstract rbegin(): base.IReverseIterator; - /** - * @inheritdoc - */ - abstract rend(): base.IReverseIterator; - /** - * @inheritdoc - */ - abstract size(): number; - /** - * @inheritdoc - */ - empty(): boolean; - /** - * @inheritdoc - */ - abstract push(...items: T[]): number; - /** - * @inheritdoc - */ - abstract insert(position: Iterator, val: T): Iterator; - /** - * @inheritdoc - */ - abstract erase(position: Iterator): Iterator; - /** - * @inheritdoc - */ - abstract erase(begin: Iterator, end: Iterator): Iterator; - /** - * @inheritdoc - */ - swap(obj: IContainer): void; - } -} -declare namespace std.base { - /** - *

    An abstract error instance.

    - * - *

    {@link ErrorInstance} is an abstract class of {@link ErrorCode} and {@link ErrorCondition} - * holding an error instance's identifier {@link value}, associated with a {@link category}.

    - * - *

    The operating system and other low-level applications and libraries generate numerical error codes to - * represent possible results. These numerical values may carry essential information for a specific platform, - * but be non-portable from one platform to another.

    - * - *

    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}.

    - * - *

    - *

    - * - * @author Jeongho Nam - */ - abstract class ErrorInstance { - /** - * @hidden - */ - protected category_: ErrorCategory; - /** - * @hidden - */ - protected value_: number; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from a numeric value and error category. - * - * @param val A numerical value identifying an error instance. - * @param category A reference to an {@link ErrorCategory} object. - */ - constructor(val: number, category: ErrorCategory); - /** - *

    Assign error instance.

    - * - *

    Assigns the {@link ErrorCode} object a value of val associated with the {@link ErrorCategory}.

    - * - * @param val A numerical value identifying an error instance. - * @param category A reference to an {@link ErrorCategory} object. - */ - assign(val: number, category: ErrorCategory): void; - /** - *

    Clear error instance.

    - * - *

    Clears the value in the {@link ErrorCode} object so that it is set to a value of 0 of the - * {@link ErrorCategory.systemCategory ErrorCategory.systemCategory()} (indicating no error).

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

    Get category.

    - * - *

    Returns a reference to the {@link ErrorCategory} associated with the {@link ErrorCode} object.

    - * - * @return A reference to a non-copyable object of a type derived from {@link ErrorCategory}. - */ - category(): ErrorCategory; - /** - *

    Error value.

    - * - *

    Returns the error value associated with the {@link ErrorCode} object.

    - * - * @return The error value. - */ - value(): number; - /** - *

    Get message.

    - * - *

    Returns the message associated with the error instance.

    - * - *

    Error messages are defined by the {@link category} the error instance belongs to.

    - * - *

    This function returns the same as if the following member was called:

    - * - *

    category().message(value())

    - * - * @return A string object with the message associated with the {@link ErrorCode}. - */ - message(): string; - /** - *

    Default error condition.

    - * - *

    Returns the default {@link ErrorCondition}object associated with the {@link ErrorCode} object.

    - * - *

    This function returns the same as if the following member was called:

    - * - *

    category().default_error_condition(value())

    - * - *

    {@link ErrorCategory.default_error_condition ErrorCategory.default_error_condition()} - * is a virtual member function, that can operate differently for each category.

    - * - * @return An {@link ErrorCondition}object that corresponds to the {@link ErrorCode} object. - */ - default_error_condition(): ErrorCondition; - /** - *

    Convert to bool.

    - * - *

    Returns whether the error instance has a numerical {@link value} other than 0.

    - * - *

    If it is zero (which is generally used to represent no error), the function returns false, otherwise it returns true.

    - * - * @return true if the error's numerical value is not zero. - * false otherwise. - */ - to_bool(): boolean; - } -} -declare namespace std.base { - enum Hash { - MIN_SIZE = 10, - RATIO = 1, - MAX_RATIO = 2, - } - /** - *

    Hask buckets.

    - * - * @author Jeongho Nam - */ - abstract class HashBuckets { - /** - * @hidden - */ - private buckets_; - /** - * @hidden - */ - private item_size_; - /** - * Default Constructor. - */ - protected constructor(); - /** - *

    Reconstruction of hash table.

    - * - *

    All the elements in the hash buckets are rearranged according to their hash value into the new set of - * buckets. This may alter the order of iteration of elements within the container.

    - * - *

    Notice that {@link rehash rehashes} are automatically performed whenever its number of elements is going - * to greater than its own {@link capacity}.

    - * - * @param size Number of bucket size to rehash. - */ - rehash(size: number): void; - clear(): void; - size(): number; - item_size(): number; - capacity(): number; - at(index: number): Vector; - hash_index(val: T): number; - insert(val: T): void; - erase(val: T): void; - } -} -declare namespace std.base { - /** - *

    Common interface for hash map.

    - * - *

    {@link IHashMap}s are associative containers that store elements formed by the combination of - * a key value and a mapped value.

    - * - *

    In an {@link IHashMap}, 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 IHashMap} 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).

    - * - *

    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

    - *
    - *
    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.
    - * - *
    Map
    - *
    Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value.
    - *
    - * - * @param Type of the key values. - * Each element in an {@link IHashMap} is identified by a key value. - * @param Type of the mapped value. - * Each element in an {@link IHashMap} is used to store some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/unordered_map - * @author Jeongho Nam - */ - interface IHashMap { - /** - *

    Return iterator to beginning.

    - * - *

    Returns an iterator pointing to the first element in the {@link IHashMap}.

    - * - *

    Notice that an {@link IHashMap} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * container, until invalidated.

    - * - * @return An iterator to the first element in the container. - */ - begin(): MapIterator; - /** - *

    Return iterator to beginning.

    - * - *

    Returns an iterator pointing to the first element in one of buckets in the {@link IHashMap}.

    - * - *

    Notice that an {@link IHashMap} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * bucket, until invalidated.

    - * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return An iterator to the first element in the bucket. - */ - begin(index: number): MapIterator; - /** - *

    Return iterator to end.

    - * - *

    Returns an iterator pointing to the past-the-end element in the {@link HaspMap} container.

    - * - *

    The iterator returned by end does not point to any element, but to the position that follows the last - * element in the {@link HaspMap} container (its past-the-end position). Thus, the value returned shall - * not be dereferenced - it is generally used to describe the open-end of a range, such as - * [begin, end).

    - * - *

    Notice that an {@link IHashMap} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

    - * - * @return An iterator to the element past the end of the container. - */ - end(): MapIterator; - /** - *

    Return iterator to end.

    - * - *

    Returns an iterator pointing to the past-the-end element in the {@link HaspMap} container.

    - * - *

    The iterator returned by end does not point to any element, but to the position that follows the last - * element in the {@link HaspMap} container (its past-the-end position). Thus, the value returned shall - * not be dereferenced - it is generally used to describe the open-end of a range, such as - * [begin, end).

    - * - *

    Notice that an {@link IHashMap} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

    - * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return An iterator to the element past the end of the bucket. - */ - end(index: number): MapIterator; - /** - *

    Return {@link MapReverseIterator reverse iterator} to reverse beginning.

    - * - *

    Returns a {@link MapReverseIterator reverse iterator} pointing to the last element in the {@link IHashMap} - * (i.e., its reverse beginning).

    - * - * {@link MapReverseIterator Reverse iterators} iterate backwards: increasing them moves them towards the - * beginning of the container.

    - * - *

    {@link rbegin} points to the element preceding the one that would be pointed to by member {@link end}.

    - * - *

    Notice that an {@link IHashMap} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * bucket, until invalidated.

    - * - * @return A {@link MapReverseIterator reverse iterator} to the reverse beginning of the sequence - */ - rbegin(): MapReverseIterator; - /** - *

    Return {@link MapReverseIterator reverse iterator} to reverse beginning.

    - * - *

    Returns a {@link MapReverseIterator reverse iterator} pointing to the last element in one of buckets in the - * {@link IHashMap} (i.e., its reverse beginning).

    - * - * {@link MapReverseIterator Reverse iterators} iterate backwards: increasing them moves them towards the - * beginning of the container.

    - * - *

    {@link rbegin} points to the element preceding the one that would be pointed to by member {@link end}.

    - * - *

    Notice that an {@link IHashMap} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * bucket, until invalidated.

    - * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return A {@link MapReverseIterator reverse iterator} to the reverse beginning of the sequence - */ - rbegin(index: number): MapReverseIterator; - /** - *

    Return {@link MapReverseIterator reverse iterator} to reverse end.

    - * - *

    Returns a {@link MapReverseIterator reverse iterator} pointing to the theoretical element right before - * the first element in the {@link IHashMap hash map container} (which is considered its reverse end).

    - * - *

    The range between {@link IHashMap}.{@link rbegin} and {@link IHashMap}.{@link rend} contains all the - * elements of the container (in reverse order).

    - * - *

    Notice that an {@link IHashMap} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

    - * - * @return A {@link MapReverseIterator reverse iterator} to the reverse end of the sequence. - */ - rend(): MapReverseIterator; - /** - *

    Return {@link MapReverseIterator reverse iterator} to reverse end.

    - * - *

    Returns a {@link MapReverseIterator reverse iterator} pointing to the theoretical element right before - * the first element in one of buckets in the {@link IHashMap hash map container} (which is considered its - * reverse end).

    - * - *

    The range between {@link IHashMap}.{@link rbegin} and {@link IHashMap}.{@link rend} contains all the - * elements of the container (in reverse order).

    - * - *

    Notice that an {@link IHashMap} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

    - * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return A {@link MapReverseIterator reverse iterator} to the reverse end of the sequence. - */ - rend(index: number): MapReverseIterator; - /** - *

    Return number of buckets.

    - * - *

    Returns the number of buckets in the {@link IHashMap} container.

    - * - *

    A bucket is a slot in the container's internal hash table to which elements are assigned based on the - * hash value of their key.

    - * - *

    The number of buckets influences directly the {@link load_factor load factor} of the container's hash - * table (and thus the probability of collision). The container automatically increases the number of buckets to - * keep the load factor below a specific threshold (its {@link max_load_factor}), causing a {@link rehash} each - * time the number of buckets needs to be increased.

    - * - * @return The current amount of buckets. - */ - bucket_count(): number; - /** - *

    Return bucket size.

    - * - *

    Returns the number of elements in bucket n.

    - * - *

    A bucket is a slot in the container's internal hash table to which elements are assigned based on the hash - * value of their key.

    - * - *

    The number of elements in a bucket influences the time it takes to access a particular element in the - * bucket. The container automatically increases the number of buckets to keep the {@link load_cator load factor} - * (which is the average bucket size) below its {@link max_load_factor}.

    - * - * @param n Bucket number. This shall be lower than {@link bucket_count}. - * - * @return The number of elements in bucket n. - */ - bucket_size(n: number): number; - /** - *

    Get maximum load factor.

    - * - *

    Returns the current maximum load factor for the {@link HashMultiMap} container.

    - * - *

    The load factor is the ratio between the number of elements in the container (its {@link size}) and the - * number of buckets ({@link bucket_count}).

    - * - *

    By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0.

    - * - *

    The load factor influences the probability of collision in the hash table (i.e., the probability of two - * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold - * that forces an increase in the number of buckets (and thus causing a {@link rehash}).

    - * - *

    Note though, that implementations may impose an upper limit on the number of buckets (see - * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}.

    - * - * @return The current load factor. - */ - max_load_factor(): number; - /** - *

    Set maximum load factor.

    - * - *

    Sets z as the cnew maximum load factor for the {@link HashMultiMap} container.

    - * - *

    The load factor is the ratio between the number of elements in the container (its {@link size}) and the - * number of buckets ({@link bucket_count}).

    - * - *

    By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0.

    - * - *

    The load factor influences the probability of collision in the hash table (i.e., the probability of two - * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold - * that forces an increase in the number of buckets (and thus causing a {@link rehash}).

    - * - *

    Note though, that implementations may impose an upper limit on the number of buckets (see - * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}.

    - * - * @param z The new maximum load factor. - */ - max_load_factor(z: number): void; - /** - *

    Locate element's bucket.

    - * - *

    Returns the bucket number where the element with key is located.

    - * - *

    A bucket is a slot in the container's internal hash table to which elements are assigned based on the - * hash value of their key. Buckets are numbered from 0 to ({@link bucket_count} - 1).

    - * - *

    Individual elements in a bucket can be accessed by means of the range iterators returned by - * {@link begin} and {@link end}.

    - * - * @param key Key whose bucket is to be located. - */ - bucket(key: Key): number; - /** - *

    Request a capacity change.

    - * - *

    Sets the number of buckets in the container ({@link bucket_count}) to the most appropriate to contain at - * least n elements.

    - * - *

    If n is greater than the current {@link bucket_count} multiplied by the {@link max_load_factor}, - * the container's {@link bucket_count} is increased and a {@link rehash} is forced.

    - * - *

    If n is lower than that, the function may have no effect.

    - * - * @param n The number of elements requested as minimum capacity. - */ - reserve(n: number): void; - /** - *

    Set number of buckets.

    - * - *

    Sets the number of buckets in the container to n or more.

    - * - *

    If n is greater than the current number of buckets in the container ({@link bucket_count}), a - * {@link HashBuckets.rehash rehash} is forced. The new {@link bucket_count bucket count} can either be equal or - * greater than n.

    - * - *

    If n is lower than the current number of buckets in the container ({@link bucket_count}), the - * function may have no effect on the {@link bucket_count bucket count} and may not force a - * {@link HashBuckets.rehash rehash}.

    - * - *

    A {@link HashBuckets.rehash rehash} is the reconstruction of the hash table: All the elements in the - * container are rearranged according to their hash value into the new set of buckets. This may alter the order - * of iteration of elements within the container.

    - * - *

    {@link HashBuckets.rehash Rehashes} are automatically performed by the container whenever its - * {@link load_factor load factor} is going to surpass its {@link max_load_factor} in an operation.

    - * - *

    Notice that this function expects the number of buckets as argument. A similar function exists, - * {@link reserve}, that expects the number of elements in the container as argument.

    - * - * @param n The minimum number of buckets for the container hash table. - */ - rehash(n: number): void; - } -} -declare namespace std.base { - /** - *

    Hash buckets storing {@link MapIterator MapIterators}.

    - * - *

    - * - *

    - * - * @author Jeongho Nam - */ - class MapHashBuckets extends HashBuckets> { - private map; - constructor(map: MapContainer); - find(key: K): MapIterator; - } -} -declare namespace std.base { - /** - *

    A common interface for hash set.

    - * - *

    {@link IHashSet}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 IHashSet}, 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 IHashSet} cannot be - * modified once in the container - they can be inserted and removed, though.

    - * - *

    Internally, the elements in the {@link IHashSet} 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 IHashSet} 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.
    - *
    - * - * @param Type of the elements. - * Each element in an {@link IHashSet} is also uniquely identified by this value. - * - * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set - * @author Jeongho Nam - */ - interface IHashSet { - /** - *

    Return iterator to beginning.

    - * - *

    Returns an iterator pointing to the first element in the {@link IHashSet}.

    - * - *

    Notice that an {@link IHashSet} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * container, until invalidated.

    - * - * @return An iterator to the first element in the container. - */ - begin(): SetIterator; - /** - *

    Return iterator to beginning.

    - * - *

    Returns an iterator pointing to the first element in one of buckets in the {@link IHashSet}.

    - * - *

    Notice that an {@link IHashSet} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * bucket, until invalidated.

    - * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return An iterator to the first element in the bucket. - */ - begin(index: number): SetIterator; - /** - *

    Return iterator to end.

    - * - *

    Returns an iterator pointing to the past-the-end element in the {@link HaspMap} container.

    - * - *

    The iterator returned by end does not point to any element, but to the position that follows the last - * element in the {@link HaspMap} container (its past-the-end position). Thus, the value returned shall - * not be dereferenced - it is generally used to describe the open-end of a range, such as - * [begin, end).

    - * - *

    Notice that an {@link IHashSet} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

    - * - * @return An iterator to the element past the end of the container. - */ - end(): SetIterator; - /** - *

    Return iterator to end.

    - * - *

    Returns an iterator pointing to the past-the-end element in the {@link HaspMap} container.

    - * - *

    The iterator returned by end does not point to any element, but to the position that follows the last - * element in the {@link HaspMap} container (its past-the-end position). Thus, the value returned shall - * not be dereferenced - it is generally used to describe the open-end of a range, such as - * [begin, end).

    - * - *

    Notice that an {@link IHashSet} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

    - * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return An iterator to the element past the end of the bucket. - */ - end(index: number): SetIterator; - rbegin(): SetReverseIterator; - rbegin(index: number): SetReverseIterator; - rend(): SetReverseIterator; - rend(index: number): SetReverseIterator; - /** - *

    Return number of buckets.

    - * - *

    Returns the number of buckets in the {@link IHashSet} container.

    - * - *

    A bucket is a slot in the container's internal hash table to which elements are assigned based on the - * hash value of their key.

    - * - *

    The number of buckets influences directly the {@link load_factor load factor} of the container's hash - * table (and thus the probability of collision). The container automatically increases the number of buckets to - * keep the load factor below a specific threshold (its {@link max_load_factor}), causing a {@link rehash} each - * time the number of buckets needs to be increased.

    - * - * @return The current amount of buckets. - */ - bucket_count(): number; - /** - *

    Return bucket size.

    - * - *

    Returns the number of elements in bucket n.

    - * - *

    A bucket is a slot in the container's internal hash table to which elements are assigned based on the hash - * value of their key.

    - * - *

    The number of elements in a bucket influences the time it takes to access a particular element in the - * bucket. The container automatically increases the number of buckets to keep the {@link load_cator load factor} - * (which is the average bucket size) below its {@link max_load_factor}.

    - * - * @param n Bucket number. This shall be lower than {@link bucket_count}. - * - * @return The number of elements in bucket n. - */ - bucket_size(n: number): number; - /** - *

    Get maximum load factor.

    - * - *

    Returns the current maximum load factor for the {@link HashMultiMap} container.

    - * - *

    The load factor is the ratio between the number of elements in the container (its {@link size}) and the - * number of buckets ({@link bucket_count}).

    - * - *

    By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0.

    - * - *

    The load factor influences the probability of collision in the hash table (i.e., the probability of two - * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold - * that forces an increase in the number of buckets (and thus causing a {@link rehash}).

    - * - *

    Note though, that implementations may impose an upper limit on the number of buckets (see - * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}.

    - * - * @return The current load factor. - */ - max_load_factor(): number; - /** - *

    Set maximum load factor.

    - * - *

    Sets z as the cnew maximum load factor for the {@link HashMultiMap} container.

    - * - *

    The load factor is the ratio between the number of elements in the container (its {@link size}) and the - * number of buckets ({@link bucket_count}).

    - * - *

    By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0.

    - * - *

    The load factor influences the probability of collision in the hash table (i.e., the probability of two - * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold - * that forces an increase in the number of buckets (and thus causing a {@link rehash}).

    - * - *

    Note though, that implementations may impose an upper limit on the number of buckets (see - * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}.

    - * - * @param z The new maximum load factor. - */ - max_load_factor(z: number): void; - /** - *

    Locate element's bucket.

    - * - *

    Returns the bucket number where the element with key is located.

    - * - *

    A bucket is a slot in the container's internal hash table to which elements are assigned based on the - * hash value of their key. Buckets are numbered from 0 to ({@link bucket_count} - 1).

    - * - *

    Individual elements in a bucket can be accessed by means of the range iterators returned by - * {@link begin} and {@link end}.

    - * - * @param key Key whose bucket is to be located. - */ - bucket(key: T): number; - /** - *

    Request a capacity change.

    - * - *

    Sets the number of buckets in the container ({@link bucket_count}) to the most appropriate to contain at - * least n elements.

    - * - *

    If n is greater than the current {@link bucket_count} multiplied by the {@link max_load_factor}, - * the container's {@link bucket_count} is increased and a {@link rehash} is forced.

    - * - *

    If n is lower than that, the function may have no effect.

    - * - * @param n The number of elements requested as minimum capacity. - */ - reserve(n: number): void; - /** - *

    Set number of buckets.

    - * - *

    Sets the number of buckets in the container to n or more.

    - * - *

    If n is greater than the current number of buckets in the container ({@link bucket_count}), a - * {@link HashBuckets.rehash rehash} is forced. The new {@link bucket_count bucket count} can either be equal or - * greater than n.

    - * - *

    If n is lower than the current number of buckets in the container ({@link bucket_count}), the - * function may have no effect on the {@link bucket_count bucket count} and may not force a - * {@link HashBuckets.rehash rehash}.

    - * - *

    A {@link HashBuckets.rehash rehash} is the reconstruction of the hash table: All the elements in the - * container are rearranged according to their hash value into the new set of buckets. This may alter the order - * of iteration of elements within the container.

    - * - *

    {@link HashBuckets.rehash Rehashes} are automatically performed by the container whenever its - * {@link load_factor load factor} is going to surpass its {@link max_load_factor} in an operation.

    - * - *

    Notice that this function expects the number of buckets as argument. A similar function exists, - * {@link reserve}, that expects the number of elements in the container as argument.

    - * - * @param n The minimum number of buckets for the container hash table. - */ - rehash(n: number): void; - } -} -declare namespace std.base { - /** - *

    Hash buckets storing {@link SetIterator SetIterators}.

    - * - *

    - * - *

    - * - * @author Jeongho Nam - */ - class SetHashBuckets extends HashBuckets> { - private set; - constructor(set: SetContainer); - find(val: T): SetIterator; - } -} -declare namespace std.base { - /** - *

    Array

    - * - *

    {@link IArray} is an interface for sequence containers representing arrays that can change in - * {@link size}. However, compared to arrays, {@link IArray} objectss consume more memory in exchange for - * the ability to manage storage and grow dynamically in an efficient way.

    - * - *

    Both {@link Vector Vectors} and {@link Deque Deques} who implemented {@link IArray} provide a very - * similar interface and can be used for similar purposes, but internally both work in quite different ways: - * While {@link Vector Vectors} use a single array that needs to be occasionally reallocated for growth, the - * elements of a {@link Deque} can be scattered in different chunks of storage, with the container keeping the - * necessary information internally to provide direct access to any of its elements in constant time and with a - * uniform sequential interface (through iterators). Therefore, {@link Deque Deques} are a little more complex - * internally than {@link Vector Vectors}, but this allows them to grow more efficiently under certain - * circumstances, especially with very long sequences, where reallocations become more expensive.

    - * - *

    Both {@link Vector Vectors} and {@link Deque Deques} provide a very similar interface and can be used for - * similar purposes, but internally both work in quite different ways: While {@link Vector Vectors} use a single - * array that needs to be occasionally reallocated for growth, the elements of a {@link Deque} can be scattered - * in different chunks of storage, with the container keeping the necessary information internally to provide - * direct access to any of its elements in constant time and with a uniform sequential interface (through - * iterators). Therefore, {@link Deque Deques} are a little more complex internally than {@link Vector Vectors}, - * but this allows them to grow more efficiently under certain circumstances, especially with very long - * sequences, where reallocations become more expensive.

    - * - *

    For operations that involve frequent insertion or removals of elements at positions other than the - * beginning or the end, {@link IArray} objects perform worse and have less consistent iterators and references - * than {@link List Lists}

    . - * - *

    - * - *

    - * - *

    Container properties

    - *
    - *
    Sequence
    - *
    - * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are - * accessed by their position in this sequence. - *
    - * - *
    Dynamic array
    - *
    - * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides - * relatively fast addition/removal of elements at the end of the sequence. - *
    - *
    - * - * @param Type of the elements. - * - * @author Jeongho Nam - */ - interface IArrayContainer extends ILinearContainer { - /** - *

    Request a change in capacity.

    - * - *

    Requests that the {@link IArray container} {@link capacity} be at least enough to contain - * n elements.

    - * - *

    If n is greater than the current {@link IArray container} {@link capacity}, the - * function causes the {@link IArray container} to reallocate its storage increasing its - * {@link capacity} to n (or greater).

    - * - *

    In all other cases, the function call does not cause a reallocation and the - * {@link IArray container} {@link capacity} is not affected.

    - * - *

    This function has no effect on the {@link IArray container} {@link size} and cannot alter - * its elements.

    - * - * @param n Minimum {@link capacity} for the {@link IArray container}. - * Note that the resulting {@link capacity} may be equal or greater than n. - */ - reserve(n: number): void; - /** - *

    Return size of allocated storage capacity.

    - * - *

    Returns the size of the storage space currently allocated for the {@link IArray container}, - * expressed in terms of elements.

    - * - *

    This {@link capacity} is not necessarily equal to the {@link IArray 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} does not suppose a limit on the {@link size} of the - * {@link IArray container}. When this {@link capacity} is exhausted and more is needed, it is - * automatically expanded by the {@link IArray container} (reallocating it storage space). - * The theoretical limit on the {@link size} of a {@link IArray container} is given by member - * {@link max_size}.

    - * - *

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

    - * - * @return The size of the currently allocated storage capacity in the {@link IArray container}, - * measured in terms of the number elements it can hold. - */ - capacity(): number; - /** - *

    Access element.

    - *

    Returns a value to the element at position index in the {@link IArray container}.

    - * - *

    The function automatically checks whether index is within the bounds of valid elements - * in the {@link IArray container}, throwing an {@link OutOfRange} exception if it is not (i.e., - * if index is greater or equal than its {@link size}).

    - * - * @param index Position of an element in the - * If this is greater than or equal to the {@link IArray container} {@link size}, an - * exception of type {@link OutOfRange} is thrown. Notice that the first - * element has a position of 0 (not 1). - * - * @return The element at the specified position in the - */ - at(index: number): T; - /** - *

    Modify element.

    - *

    Replaces an element at the specified position (index) in this {@link IArray container} - * with the specified element (val).

    - * - *

    The function automatically checks whether index is within the bounds of valid elements - * in the {@link IArray container}, throwing an {@link OutOfRange} exception if it is not (i.e., if - * index is greater or equal than its {@link size}).

    - * - * @.param index A specified position of the value to replace. - * @param val A value to be stored at the specified position. - * - * @return The previous element had stored at the specified position. - */ - set(index: number, val: T): void; - } - /** - *

    Random-access iterator.

    - * - *

    {@link IArrayIterator Random-access iterators} are iterators that can be used to access elements at an - * arbitrary offset position relative to the element they point to, offering the same functionality as pointers. - *

    - * - *

    {@link IArrayIterator Random-access iterators} are the most complete iterators in terms of functionality. - * All pointer types are also valid {@link IArrayIterator random-access iterators}.

    - * - *

    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 - * @author Jeongho Nam - */ - interface IArrayIterator extends ILinearIterator { - /** - * Get index, sequence number of the iterator in the source {@link IArray array}. - * - * @return Sequence number of the iterator in the source {@link IArray array}. - */ - index: number; - /** - * @inheritdoc - */ - prev(): IArrayIterator; - /** - * @inheritdoc - */ - next(): IArrayIterator; - } -} -declare namespace std.base { - /** - *

    An interface of containers.

    - * - *

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

    - * - *

    - * - *

    - * - *

    Container properties

    - *
    - *
    Sequence
    - *
    Elements in sequence containers are ordered in a strict linear sequence. Individual elements are - * accessed by their position in this sequence.
    - * - *
    Doubly-linked list
    - *
    Each element keeps information on how to locate the next and the previous elements, allowing - * constant time insert and erase operations before or after a specific element (even of entire ranges), - * but no direct random access.
    - *
    - * - * @param Type of elements. - * - * @author Jeongho Nam - */ - interface IContainer { - /** - *

    Assign new content to content.

    - * - *

    Assigns new contents to the container, replacing its current contents, and modifying its - * {@link size} accordingly.

    - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - assign>(begin: InputIterator, end: InputIterator): void; - /** - *

    Clear content.

    - * - *

    Removes all elements from the Container, leaving the container with a size of 0.

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

    Return iterator to beginning.

    - * - *

    Returns an iterator referring the first element in the

    - * - *

    Note

    - *

    If the container is {@link empty}, the returned iterator is same with {@link end end()}.

    - * - * @return An iterator to the first element in the The iterator containes the first element's value. - */ - begin(): Iterator; - /** - *

    Return iterator to end.

    - *

    Returns an iterator referring to the past-the-end element in the

    - * - *

    The past-the-end element is the theoretical element that would follow the last element in the - * It does not point to any element, and thus shall not be dereferenced.

    - * - *

    Because the ranges used by functions of the Container do not include the element reference by their - * closing iterator, this function is often used in combination with {@link IContainer}.{@link begin} to - * specify a range including all the elements in the container.

    - * - *

    Note

    - *

    Returned iterator from {@link IContainer}.{@link end} does not refer any element. Trying to accessing - * element by the iterator will cause throwing exception ({@link OutOfRange}).

    - * - *

    If the container is {@link empty}, this function returns the same as {@link Container}.{@link begin}. - *

    - * - * @return An iterator to the end element in the - */ - end(): Iterator; - /** - *

    Return {@link ReverseIterator reverse iterator} to reverse beginning.

    - * - *

    Returns a {@link ReverseIterator reverse iterator} pointing to the last element in the container (i.e., - * its reverse beginning).

    - * - *

    {@link ReverseIterator reverse iterators} iterate backwards: increasing them moves them towards the - * beginning of the

    - * - *

    {@link rbegin} points to the element right before the one that would be pointed to by member {@link end}. - *

    - * - * @return A {@link ReverseIterator reverse iterator} to the reverse beginning of the sequence - */ - rbegin(): base.IReverseIterator; - /** - *

    Return {@link ReverseIterator reverse iterator} to reverse end.

    - * - *

    Returns a {@link ReverseIterator reverse iterator} pointing to the theoretical element preceding the - * first element in the container (which is considered its reverse end).

    - * - *

    The range between {@link IContainer}.{@link rbegin} and {@link IContainer}.{@link rend} contains all - * the elements of the container (in reverse order). - * - * @return A {@link ReverseIterator reverse iterator} to the reverse end of the sequence - */ - rend(): base.IReverseIterator; - /** - * Return the number of elements in the Container. - * - * @return The number of elements in the - */ - size(): number; - /** - *

    Test whether the container is empty.

    - *

    Returns whether the container is empty (i.e. whether its size is 0).

    - * - *

    This function does not modify the container in any way. To clear the content of the container, - * see {@link clear clear()}.

    - * - * @return true if the container size is 0, false otherwise. - */ - empty(): boolean; - /** - *

    Insert elements.

    - * - *

    Appends new elements to the container, and returns the new size of the

    - * - * @param items New elements to insert. - * - * @return New size of the Container. - */ - push(...items: T[]): number; - /** - *

    Insert an element.

    - * - *

    The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link IContainer.size container size} by the amount of - * elements inserted.

    - * - * @param position Position in the {@link IContainer} where the new element is inserted. - * {@link iterator} is a member type, defined as a {@link Iterator random access iterator} - * type that points to elements. - * @param val Value to be copied to the inserted element. - * - * @return An iterator that points to the newly inserted element. - */ - insert(position: Iterator, val: T): Iterator; - /** - *

    Erase an element.

    - * - *

    Removes from the container a single element.

    - * - *

    This effectively reduces the container size by the number of element removed.

    - * - * @param position Iterator pointing to a single element to be removed from the Container. - * - * @return An iterator pointing to the element that followed the last element erased by the function - * call. This is the {@link end Container.end} if the operation erased the last element in the - * sequence. - */ - erase(position: Iterator): Iterator; - /** - *

    Erase elements.

    - * - *

    Removes from the container a range of elements.

    - * - *

    This effectively reduces the container size by the number of elements removed.

    - * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - * - * @return An iterator pointing to the element that followed the last element erased by the function - * call. This is the {@link end Container.end} if the operation erased the last element in - * the sequence. - */ - erase(begin: Iterator, end: Iterator): Iterator; - /** - *

    Swap content.

    - * - *

    Exchanges the content of the container by the content of obj, which is another - * {@link IContainer 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 IContainer 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 IContainer}. - */ - swap(obj: IContainer): void; - } - interface IReverseIterator extends ReverseIterator, IReverseIterator> { - } -} -declare namespace std.base { - /** - *

    An interface for deque

    - * - *

    - * - *

    - * - * @author Jeongho Nam - */ - interface IDequeContainer extends ILinearContainer { - /** - *

    Insert element at beginning.

    - * - *

    Inserts a new element at the beginning of the {@link IDeque container}, right before its - * current first element. This effectively increases the {@link IDeque container} {@link size} by - * one.

    - * - * @param val Value to be inserted as an element. - */ - push_front(val: T): void; - /** - *

    Delete first element.

    - * - *

    Removes the first element in the {@link IDeque container}, effectively reducing its - * {@link size} by one.

    - */ - pop_front(): void; - } -} -declare namespace std.base { - /** - *

    An interface for linear containers.

    - * - *

    - * - *

    - * - * @author Jeonngho Nam - */ - interface ILinearContainer extends IContainer { - /** - * @inheritdoc - */ - assign>(begin: InputIterator, end: InputIterator): void; - /** - *

    Assign container content.

    - * - *

    Assigns new contents to the {@link IList container}, replacing its current contents, - * and modifying its {@link size} accordingly.

    - * - * @param n New size for the - * @param val Value to fill the container with. Each of the n elements in the container will - * be initialized to a copy of this value. - */ - assign(n: number, val: T): void; - /** - *

    Access first element.

    - *

    Returns a value of the first element in the {@link IList container}.

    - * - *

    Unlike member {@link end end()}, which returns an iterator just past this element, - * this function returns a direct value.

    - * - *

    Calling this function on an {@link empty} {@link IList container} causes undefined behavior.

    - * - * @return A value of the first element of the {@link IList container}. - */ - front(): T; - /** - *

    Access last element.

    - *

    Returns a value of the last element in the {@link IList container}.

    - * - *

    Unlike member {@link end end()}, which returns an iterator just past this element, - * this function returns a direct value.

    - * - *

    Calling this function on an {@link empty} {@link IList container} causes undefined behavior.

    - * - * @return A value of the last element of the {@link IList container}. - */ - back(): T; - /** - *

    Add element at the end.

    - * - *

    Adds a new element at the end of the {@link IList container}, after its current last element. - * This effectively increases the {@link IList container} {@link size} by one.

    - * - * @param val Value to be copied to the new element. - */ - push_back(val: T): void; - /** - *

    Delete last element.

    - * - *

    Removes the last element in the {@link IList container}, effectively reducing the - * {@link IList container} {@link size} by one.

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

    Insert an element.

    - * - *

    The {@link IList conatiner} is extended by inserting new element before the element at the - * specified position, effectively increasing the {@link IList container} {@link size} by - * one.

    - * - * @param position Position in the {@link IList container} where the new elements are inserted. - * {@link iterator} is a member type, defined as a {@link iterator random access iterator} - * type that points to elements. - * @param val Value to be copied to the inserted element. - * - * @return An iterator that points to the newly inserted element. - */ - insert(position: Iterator, val: T): Iterator; - /** - *

    Insert elements by range iterators.

    - * - *

    The {@link IList container} is extended by inserting new elements before the element at the - * specified position, effectively increasing the {@link IList container} {@link size} by - * the number of repeating elements n.

    - * - * @param position Position in the {@link IList container} where the new elements are inserted. - * {@link iterator} is a member type, defined as a {@link iterator random access iterator} - * type that points to elements. - * @param n Number of elements to insert. Each element is initialized to a copy of val. - * @param val Value to be copied (or moved) to the inserted elements. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert(position: Iterator, n: number, val: T): Iterator; - /** - *

    Insert elements by range iterators.

    - * - *

    The {@link IList container} is extended by inserting new elements before the element at the - * specified position, effectively increasing the {@link IList container} {@link size} by - * the number of elements inserted by range iterators.

    - * - * @param position Position in the {@link IList container} where the new elements are inserted. - * {@link iterator} is a member type, defined as a {@link iterator random access iterator} - * type that points to elements. - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert>(position: Iterator, begin: InputIterator, end: InputIterator): Iterator; - } - /** - * An interface for iterators from linear containers. - * - * {@link ILieanerIterator} is an bi-directional iterator which is created from the related - * {@link ILinearContainer linear containers}. Not only accessing to {@link value} of the pointed element from - * this {@link ILieanerIterator}, but also modifying the {@link value} is possible. - * - * @author Jeongho Nam - */ - interface ILinearIterator extends Iterator { - /** - * @inheritdoc - */ - value: T; - /** - * @inheritdoc - */ - prev(): ILinearIterator; - /** - * @inheritdoc - */ - next(): ILinearIterator; - } -} -declare namespace std { - /** - *

    Bi-directional iterator.

    - * - *

    {@link Iterator Bidirectional iterators} are iterators that can be used to access the sequence of elements - * in a range in both directions (towards the end and towards the beginning).

    - * - *

    All {@link IArrayIterator random-access iterators} are also valid {@link Iterrator bidirectional iterators}. - *

    - * - *

    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 - * @author Jeongho Nam - */ - abstract class Iterator { - /** - * Source container of the iterator is directing for. - */ - protected source_: base.IContainer; - /** - * Construct from the source {@link IContainer container}. - * - * @param source The source container. - */ - protected constructor(source: base.IContainer); - /** - *

    Get iterator to previous element.

    - *

    If current iterator is the first item(equal with {@link IContainer.begin IContainer.begin()}), - * returns {@link IContainer.end IContainer.end()}.

    - * - * @return An iterator of the previous item. - */ - abstract prev(): Iterator; - /** - *

    Get iterator to next element.

    - *

    If current iterator is the last item, returns {@link IContainer.end IContainer.end()}.

    - * - * @return An iterator of the next item. - */ - abstract next(): Iterator; - /** - * Advances the {@link Iterator} by n element positions. - * - * @param n Number of element positions to advance. - * @return An advanced iterator. - */ - advance(n: number): Iterator; - /** - * Get source - */ - get_source(): base.IContainer; - /** - *

    Whether an iterator is equal with the iterator.

    - * - *

    Compare two iterators and returns whether they are equal or not.

    - * - *

    Note

    - *

    Iterator's {@link equals equals()} only compare souce container and index number.

    - * - *

    Although elements in a pair, key and value are {@link std.equal_to equal_to}, if the source map or - * index number is different, then the {@link equals equals()} will return false. If you want to - * compare the elements of a pair, compare them directly by yourself.

    - * - * @param obj An iterator to compare - * @return Indicates whether equal or not. - */ - equals(obj: Iterator): boolean; - /** - *

    Get value of the iterator is pointing.

    - * - * @return A value of the iterator. - */ - readonly abstract value: T; - abstract swap(obj: Iterator): void; - } -} -declare namespace std { - /** - *

    This class reverses the direction in which a bidirectional or random-access iterator iterates through a range. - *

    - * - *

    A copy of the original iterator (the {@link Iterator base iterator}) is kept internally and used to reflect - * the operations performed on the {@link ReverseIterator}: whenever the {@link ReverseIterator} is incremented, its - * {@link Iterator base iterator} is decreased, and vice versa. A copy of the {@link Iterator base iterator} with the - * current state can be obtained at any time by calling member {@link base}.

    - * - *

    Notice however that when an iterator is reversed, the reversed version does not point to the same element in - * the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a - * range: An iterator pointing to a past-the-end element in a range, when reversed, is pointing to the last element - * (not past it) of the range (this would be the first element of the reversed range). And if an iterator to the - * 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. - */ - protected 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(base: Base): This; - /** - *

    Get value of the iterator is pointing.

    - * - * @return A value of the reverse iterator. - */ - readonly value: T; - /** - * @inheritdoc - */ - prev(): This; - /** - * @inheritdoc - */ - next(): This; - /** - * @inheritdoc - */ - advance(n: number): This; - /** - * @inheritdoc - */ - equals(obj: This): boolean; - /** - * @inheritdoc - */ - swap(obj: This): void; - } - /** - *

    Return distance between {@link Iterator iterators}.

    - * - *

    Calculates the number of elements between first and last.

    - * - *

    If it is a {@link IArrayIterator random-access iterator}, the function uses operator- to calculate this. - * Otherwise, the function uses the increase operator {@link Iterator.next next()} repeatedly.

    - * - * @param first Iterator pointing to the initial element. - * @param last Iterator pointing to the final element. This must be reachable from first. - * - * @return The number of elements between first and last. - */ - function distance>(first: InputIterator, last: InputIterator): number; - /** - *

    Advance iterator.

    - * - *

    Advances the iterator it by n elements positions.

    - * - * @param it Iterator to be advanced. - * @param n Number of element positions to advance. - * - * @return An iterator to the element n positions before it. - */ - function advance>(it: InputIterator, n: number): InputIterator; - /** - *

    Get iterator to previous element.

    - * - *

    Returns an iterator pointing to the element that it would be pointing to if advanced -n positions.

    - * - * @param it Iterator to base position. - * @param n Number of element positions offset (1 by default). - * - * @return An iterator to the element n positions before it. - */ - function prev>(it: BidirectionalIterator, n?: number): BidirectionalIterator; - /** - *

    Get iterator to next element.

    - * - *

    Returns an iterator pointing to the element that it would be pointing to if advanced n positions.

    - * - * @param it Iterator to base position. - * @param n Number of element positions offset (1 by default). - * - * @return An iterator to the element n positions away from it. - */ - function next>(it: ForwardIterator, n?: number): ForwardIterator; - /** - *

    Iterator to beginning.

    - * - *

    Returns an iterator pointing to the first element in the sequence.

    - * - *

    If the sequence is empty, the returned value shall not be dereferenced.

    - * - * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. - * - * @return The same as returned by {@link IContainer.begin container.begin()}. - */ - function begin(container: Vector): VectorIterator; - /** - *

    Iterator to beginning.

    - * - *

    Returns an iterator pointing to the first element in the sequence.

    - * - *

    If the sequence is empty, the returned value shall not be dereferenced.

    - * - * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. - * - * @return The same as returned by {@link IContainer.begin container.begin()}. - */ - function begin(container: List): ListIterator; - /** - *

    Iterator to beginning.

    - * - *

    Returns an iterator pointing to the first element in the sequence.

    - * - *

    If the sequence is empty, the returned value shall not be dereferenced.

    - * - * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. - * - * @return The same as returned by {@link IContainer.begin container.begin()}. - */ - function begin(container: Deque): DequeIterator; - /** - *

    Iterator to beginning.

    - * - *

    Returns an iterator pointing to the first element in the sequence.

    - * - *

    If the sequence is empty, the returned value shall not be dereferenced.

    - * - * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. - * - * @return The same as returned by {@link IContainer.begin container.begin()}. - */ - function begin(container: base.SetContainer): SetIterator; - /** - *

    Iterator to beginning.

    - * - *

    Returns an iterator pointing to the first element in the sequence.

    - * - *

    If the sequence is empty, the returned value shall not be dereferenced.

    - * - * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. - * - * @return The same as returned by {@link IContainer.begin container.begin()}. - */ - function begin(container: base.MapContainer): MapIterator; - /** - *

    Iterator to end.

    - * - *

    Returns an iterator pointing to the past-the-end element in the sequence.

    - * - *

    If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

    - * - * @param container A container of a class type for which member {@link IContainer.end end} is defined. - * - * @return The same as returned by {@link IContainer.end container.end()}. - */ - function end(container: Vector): VectorIterator; - /** - *

    Iterator to end.

    - * - *

    Returns an iterator pointing to the past-the-end element in the sequence.

    - * - *

    If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

    - * - * @param container A container of a class type for which member {@link IContainer.end end} is defined. - * - * @return The same as returned by {@link IContainer.end container.end()}. - */ - function end(container: List): ListIterator; - /** - *

    Iterator to end.

    - * - *

    Returns an iterator pointing to the past-the-end element in the sequence.

    - * - *

    If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

    - * - * @param container A container of a class type for which member {@link IContainer.end end} is defined. - * - * @return The same as returned by {@link IContainer.end container.end()}. - */ - function end(container: Deque): DequeIterator; - /** - *

    Iterator to end.

    - * - *

    Returns an iterator pointing to the past-the-end element in the sequence.

    - * - *

    If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

    - * - * @param container A container of a class type for which member {@link IContainer.end end} is defined. - * - * @return The same as returned by {@link IContainer.end container.end()}. - */ - function end(container: base.SetContainer): SetIterator; - /** - *

    Iterator to end.

    - * - *

    Returns an iterator pointing to the past-the-end element in the sequence.

    - * - *

    If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

    - * - * @param container A container of a class type for which member {@link IContainer.end end} is defined. - * - * @return The same as returned by {@link IContainer.end container.end()}. - */ - function end(container: base.MapContainer): MapIterator; -} -declare namespace std.base { - /** - * An abstract list. - * - *

    {@link ListContainer}s are sequence containers that allow constant time insert and erase operations anywhere - * within the sequence, and iteration in both directions.

    - * - *

    List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they - * contain in different and unrelated storage locations. The ordering is kept internally by the association to each - * element of a link to the element preceding it and a link to the element following it.

    - * - *

    Compared to other base standard sequence containers (array, vector and deque), lists perform generally better - * in inserting, extracting and moving elements in any position within the container for which an iterator has already - * been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms.

    - * - *

    The main drawback of lists and forward_lists compared to these other sequence containers is that they lack - * direct access to the elements by their position; For example, to access the sixth element in a list, one has to - * iterate from a known position (like the beginning or the end) to that position, which takes linear time in the - * 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

    - *
    - *
    Sequence
    - *
    Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by - * their position in this sequence.
    - * - *
    Doubly-linked list
    - *
    Each element keeps information on how to locate the next and the previous elements, allowing constant time - * insert and erase operations before or after a specific element (even of entire ranges), but no direct random - * access.
    - *
    - * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/list/list/ - * - * @author Jeongho Nam - */ - abstract class ListContainer> extends Container implements IDequeContainer { - /** - * @hidden - */ - private begin_; - /** - * @hidden - */ - private end_; - /** - * @hidden - */ - private size_; - /** - * Default Constructor. - */ - protected constructor(); - /** - * @hidden - */ - protected abstract _Create_iterator(prev: BidirectionalIterator, next: BidirectionalIterator, val: T): BidirectionalIterator; - /** - * @hidden - */ - protected _Set_begin(it: BidirectionalIterator): void; - /** - * @inheritdoc - */ - assign>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - begin(): BidirectionalIterator; - /** - * @inheritdoc - */ - end(): BidirectionalIterator; - /** - * @inheritdoc - */ - size(): number; - /** - * @inheritdoc - */ - front(): T; - /** - * @inheritdoc - */ - back(): T; - /** - * @inheritdoc - */ - push_front(val: T): void; - /** - * @inheritdoc - */ - push_back(val: T): void; - /** - * @inheritdoc - */ - pop_front(): void; - /** - * @inheritdoc - */ - pop_back(): void; - /** - * @inheritdoc - */ - push(...items: T[]): number; - /** - *

    Insert an element.

    - * - *

    The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

    - * - *

    Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

    - * - * @param position Position in the container where the new element is inserted. - * {@link iterator}> is a member type, defined as a - * {@link ListIterator bidirectional iterator} type that points to elements. - * @param val Value to be inserted as an element. - * - * @return An iterator that points to the newly inserted element; val. - */ - insert(position: BidirectionalIterator, val: T): BidirectionalIterator; - /** - *

    Insert elements by repeated filling.

    - * - *

    The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

    - * - *

    Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

    - * - * @param position Position in the container where the new elements are inserted. The {@link iterator} is a - * member type, defined as a {@link ListIterator bidirectional iterator} type that points to - * elements. - * @param size Number of elements to insert. - * @param val Value to be inserted as an element. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert(position: BidirectionalIterator, size: number, val: T): BidirectionalIterator; - /** - *

    Insert elements by range iterators.

    - * - *

    The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

    - * - *

    Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

    - * - * @param position Position in the container where the new elements are inserted. The {@link iterator} is a - * member type, defined as a {@link ListIterator bidirectional iterator} type that points to - * elements. - * @param begin An iterator specifying range of the begining element. - * @param end An iterator specifying range of the ending element. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert>(position: BidirectionalIterator, begin: InputIterator, end: InputIterator): BidirectionalIterator; - /** - * @hidden - */ - private insert_by_val(position, val); - /** - * @hidden - */ - protected _Insert_by_repeating_val(position: BidirectionalIterator, size: number, val: T): BidirectionalIterator; - /** - * @hidden - */ - protected _Insert_by_range>(position: BidirectionalIterator, begin: InputIterator, end: InputIterator): BidirectionalIterator; - /** - *

    Erase an element.

    - * - *

    Removes from the {@link List} either a single element; position.

    - * - *

    This effectively reduces the container size by the number of element removed.

    - * - *

    Unlike other standard sequence containers, {@link List} objects are specifically designed to be - * efficient inserting and removing elements in any position, even in the middle of the sequence.

    - * - * @param position Iterator pointing to a single element to be removed from the {@link List}. - * - * @return An iterator pointing to the element that followed the last element erased by the function call. - * This is the {@link end end()} if the operation erased the last element in the sequence. - */ - erase(position: BidirectionalIterator): BidirectionalIterator; - /** - *

    Erase elements.

    - * - *

    Removes from the {@link List} container a range of elements.

    - * - *

    This effectively reduces the container {@link size} by the number of elements removed.

    - * - *

    Unlike other standard sequence containers, {@link List} objects are specifically designed to be - * efficient inserting and removing elements in any position, even in the middle of the sequence.

    - * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - * - * @return An iterator pointing to the element that followed the last element erased by the function call. - * This is the {@link end end()} if the operation erased the last element in the sequence. - */ - erase(begin: BidirectionalIterator, end: BidirectionalIterator): BidirectionalIterator; - /** - * @hidden - */ - protected _Erase_by_range(first: BidirectionalIterator, last: BidirectionalIterator): BidirectionalIterator; - /** - *

    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: ListContainer): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer): void; - } -} -declare namespace std.base { - /** - * An iterator, node of a List-based container. - * - * - * - * - * - * @author Jeongho Nam - */ - abstract class ListIteratorBase extends Iterator { - /** - * @hidden - */ - private prev_; - /** - * @hidden - */ - private next_; - /** - * @hidden - */ - protected value_: T; - /** - * Initializer Constructor. - * - * @param source The source {@link Container} to reference. - * @param prev A refenrece of previous node ({@link ListIterator iterator}). - * @param next A refenrece of next node ({@link ListIterator iterator}). - * @param value Value to be stored in the node (iterator). - */ - protected constructor(source: Container, prev: ListIteratorBase, next: ListIteratorBase, value: T); - /** - * @inheritdoc - */ - prev(): ListIteratorBase; - /** - * @inheritdoc - */ - next(): ListIteratorBase; - /** - * @inheritdoc - */ - advance(step: number): ListIteratorBase; - /** - * @inheritdoc - */ - readonly value: T; - /** - * @inheritdoc - */ - equals(obj: ListIteratorBase): boolean; - /** - * @inheritdoc - */ - swap(obj: ListIteratorBase): void; - } -} -declare namespace std.base { - /** - *

    An abstract map.

    - * - *

    {@link MapContainer MapContainers} are associative containers that store elements formed by a combination - * of a key value (Key) and a mapped value (T), and which allows for fast retrieval - * of individual elements based on their keys.

    - * - *

    In a {@link MapContainer}, the key values are generally used to identify the elements, while the - * mapped values store the content associated to this key. The types of key and - * mapped value may differ, and are grouped together in member type value_type, which is a - * {@link Pair} type combining both:

    - * - *

    typedef pair value_type;

    - * - *

    {@link MapContainer} 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. - *
    - * - *
    Map
    - *
    - * Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value. - *
    - *
    - * - * @param Type of the keys. Each element in a map is identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @author Jeongho Nam - */ - abstract class MapContainer extends Container> { - /** - *

    {@link List} storing elements.

    - * - *

    Storing elements and keeping those sequence of the {@link MapContainer} are implemented by - * {@link data_ this list container}. Implementing index-table is also related with {@link data_ this list} - * by storing {@link ListIterator iterators} ({@link MapIterator} references {@link ListIterator}) who are - * created from {@link data_ here}.

    - */ - private data_; - /** - * Default Constructor. - */ - protected constructor(); - /** - * @inheritdoc - */ - assign>>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - clear(): void; - /** - *

    Get iterator to element.

    - * - *

    Searches the container for an element with a identifier equivalent to key and returns an - * iterator to it if found, otherwise it returns an iterator to {@link end end()}.

    - * - *

    Two keys are considered equivalent if the container's comparison object returns false reflexively - * (i.e., no matter the order in which the elements are passed as arguments).

    - * - *

    Another member functions, {@link has has()} and {@link count count()}, can be used to just check - * whether a particular key exists.

    - * - * @param key Key to be searched for - * @return An iterator to the element, if an element with specified key is found, or - * {@link end end()} otherwise. - */ - abstract find(key: Key): MapIterator; - /** - *

    Return iterator to beginning.

    - * - *

    Returns an iterator referring the first element in the

    - * - *

    Note

    - *

    If the container is {@link empty}, the returned iterator is same with {@link end end()}.

    - * - * @return An iterator to the first element in the The iterator containes the first element's value. - */ - begin(): MapIterator; - /** - *

    Return iterator to end.

    - *

    Returns an iterator referring to the past-the-end element in the

    - * - *

    The past-the-end element is the theoretical element that would follow the last element in the - * It does not point to any element, and thus shall not be dereferenced.

    - * - *

    Because the ranges used by functions of the container do not include the element reference by their - * closing iterator, this function is often used in combination with {@link MapContainer}.{@link begin} to - * specify a range including all the elements in the

    - * - *

    Note

    - *

    Returned iterator from {@link MapContainer}.{@link end} does not refer any element. Trying to accessing - * element by the iterator will cause throwing exception ({@link OutOfRange}).

    - * - *

    If the container is {@link empty}, this function returns the same as {@link begin}.

    - * - * @return An iterator to the end element in the - */ - end(): MapIterator; - /** - *

    Return {@link MapReverseIterator reverse iterator} to reverse beginning.

    - * - *

    Returns a {@link MapReverseIterator reverse iterator} pointing to the last element in the container - * (i.e., its reverse beginning).

    - * - * {@link MapReverseIterator Reverse iterators} iterate backwards: increasing them moves them towards the - * beginning of the container.

    - * - *

    {@link rbegin} points to the element preceding the one that would be pointed to by member {@link end}. - *

    7 - * - * @return A {@link MapReverseIterator reverse iterator} to the reverse beginning of the sequence - * - */ - rbegin(): MapReverseIterator; - /** - *

    Return {@link MapReverseIterator reverse iterator} to reverse end.

    - * - *

    Returns a {@link MapReverseIterator reverse iterator} pointing to the theoretical element right before - * the first element in the {@link MapContainer map container} (which is considered its reverse end). - *

    - * - *

    The range between {@link MapContainer}.{@link rbegin} and {@link MapContainer}.{@link rend} contains - * all the elements of the container (in reverse order).

    - * - * @return A {@link MapReverseIterator reverse iterator} to the reverse end of the sequence - */ - rend(): MapReverseIterator; - /** - *

    Whether have the item or not.

    - * - *

    Indicates whether a map has an item having the specified identifier.

    - * - * @param key Key value of the element whose mapped value is accessed. - * - * @return Whether the map has an item having the specified identifier. - */ - has(key: Key): boolean; - /** - *

    Count elements with a specific key.

    - * - *

    Searches the container for elements whose key is key and returns the number of elements found.

    - * - * @param key Key value to be searched for. - * - * @return The number of elements in the container with a key. - */ - abstract count(key: Key): number; - /** - * Return the number of elements in the map. - */ - size(): number; - /** - * @inheritdoc - */ - push(...args: Pair[]): number; - /** - * @inheritdoc - */ - push(...args: [Key, T][]): number; - /** - * Construct and insert element with hint - * - * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in - * place using *args* as the arguments for the element's constructor. *hint* points to a location in the - * container suggested as a hint on where to start the search for its insertion point (the container may or - * may not use this suggestion to optimize the insertion operation). - * - * A similar member function exists, {@link insert}, which either copies or moves an existing object into - * the container, and may also take a position *hint*. - * - * @param hint Hint for the position where the element can be inserted. - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - emplace_hint(hint: MapIterator, key: Key, val: T): MapIterator; - /** - * Construct and insert element with hint - * - * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in - * place using *args* as the arguments for the element's constructor. *hint* points to a location in the - * container suggested as a hint on where to start the search for its insertion point (the container may or - * may not use this suggestion to optimize the insertion operation). - * - * A similar member function exists, {@link insert}, which either copies or moves an existing object into - * the container, and may also take a position *hint*. - * - * @param hint Hint for the position where the element can be inserted. - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return An {@link MapIterator iterator} pointing to either the newly inserted element or to the element - * that already had an equivalent key in the {@link MapContainer}. - */ - emplace_hint(hint: MapReverseIterator, key: Key, val: T): MapReverseIterator; - /** - * Construct and insert element with hint - * - * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in - * place using *args* as the arguments for the element's constructor. *hint* points to a location in the - * container suggested as a hint on where to start the search for its insertion point (the container may or - * may not use this suggestion to optimize the insertion operation). - * - * A similar member function exists, {@link insert}, which either copies or moves an existing object into - * the container, and may also take a position *hint*. - * - * @param hint Hint for the position where the element can be inserted. - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - emplace_hint(hint: MapIterator, pair: Pair): MapIterator; - /** - * Construct and insert element with hint - * - * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in - * place using *args* as the arguments for the element's constructor. *hint* points to a location in the - * container suggested as a hint on where to start the search for its insertion point (the container may or - * may not use this suggestion to optimize the insertion operation). - * - * A similar member function exists, {@link insert}, which either copies or moves an existing object into - * the container, and may also take a position *hint*. - * - * @param hint Hint for the position where the element can be inserted. - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return An {@link MapIterator iterator} pointing to either the newly inserted element or to the element - * that already had an equivalent key in the {@link MapContainer}. - */ - emplace_hint(hint: MapReverseIterator, pair: Pair): MapReverseIterator; - /** - *

    Insert an element.

    - * - *

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

    - * - * @param hint Hint for the position where the element can be inserted. - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - insert(hint: MapIterator, pair: Pair): MapIterator; - /** - *

    Insert an element.

    - * - *

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

    - * - * @param hint Hint for the position where the element can be inserted. - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; - /** - *

    Insert an element.

    - * - *

    Extends the container by inserting new elements, effectively increasing the container {@link size} - * by the number of elements inserted.

    - * - * @param hint Hint for the position where the element can be inserted. - * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - insert(hint: MapIterator, tuple: [L, U]): MapIterator; - /** - *

    Insert an element.

    - * - *

    Extends the container by inserting new elements, effectively increasing the container {@link size} - * by the number of elements inserted.

    - * - * @param hint Hint for the position where the element can be inserted. - * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; - /** - *

    Insert elements from range iterators.

    - * - *

    Extends the container by inserting new elements, effectively increasing the container {@link size} by - * the number of elements inserted.

    - * - * @param begin Input iterator specifying initial position of a range of elements. - * @param end Input iterator specifying final position of a range of elements. - * Notice that the range includes all the elements between begin and end, - * including the element pointed by begin but not the one pointed by end. - */ - insert>>(first: InputIterator, last: InputIterator): void; - /** - * @hidden - */ - protected abstract _Insert_by_pair(pair: Pair): any; - /** - * @hidden - */ - private insert_by_tuple(tuple); - /** - * @hidden - */ - protected abstract _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; - /** - * @hidden - */ - private insert_by_hint_with_tuple(hint, tuple); - /** - * @hidden - */ - protected abstract _Insert_by_range>>(first: InputIterator, last: InputIterator): void; - /** - *

    Erase an elemet by key.

    - * - *

    Removes from the {@link MapContainer map container} a single element.

    - * - *

    This effectively reduces the container {@link size} by the number of element removed (zero or one), - * which are destroyed.

    - * - * @param key Key of the element to be removed from the {@link MapContainer}. - */ - erase(key: Key): number; - /** - *

    Erase an elemet by iterator.

    - * - *

    Removes from the {@link MapContainer map container} a single element.

    - * - *

    This effectively reduces the container {@link size} by the number of element removed (zero or one), - * which are destroyed.

    - * - * @param it Iterator specifying position winthin the {@link MapContainer map contaier} to be removed. - */ - erase(it: MapIterator): MapIterator; - /** - *

    Erase elements by range iterators.

    - * - *

    Removes from the {@link MapContainer map container} a range of elements.

    - * - *

    This effectively reduces the container {@link size} by the number of elements removed, which are - * destroyed.

    - * - * @param begin An iterator specifying initial position of a range within {@link MApContainer map container} - * to be removed. - * @param end An iterator specifying initial position of a range within {@link MApContainer map container} - * to be removed. - * Notice that the range includes all the elements between begin and end, - * including the element pointed by begin but not the one pointed by end. - */ - erase(begin: MapIterator, end: MapIterator): MapIterator; - /** - *

    Erase an elemet by iterator.

    - * - *

    Removes from the {@link MapContainer map container} a single element.

    - * - *

    This effectively reduces the container {@link size} by the number of element removed (zero or one), - * which are destroyed.

    - * - * @param it Iterator specifying position winthin the {@link MapContainer map contaier} to be removed. - */ - erase(it: MapReverseIterator): MapReverseIterator; - /** - *

    Erase elements by range iterators.

    - * - *

    Removes from the {@link MapContainer map container} a range of elements.

    - * - *

    This effectively reduces the container {@link size} by the number of elements removed, which are - * destroyed.

    - * - * @param begin An iterator specifying initial position of a range within {@link MApContainer map container} - * to be removed. - * @param end An iterator specifying initial position of a range within {@link MApContainer map container} - * to be removed. - * Notice that the range includes all the elements between begin and end, - * including the element pointed by begin but not the one pointed by end. - */ - erase(begin: MapReverseIterator, end: MapReverseIterator): MapReverseIterator; - /** - * @hidden - */ - private erase_by_key(key); - /** - * @hidden - */ - private erase_by_iterator(first, last?); - /** - * @hidden - */ - private erase_by_range(first, last); - /** - * @hidden - */ - protected _Swap(obj: MapContainer): void; - /** - * Merge two maps. - * - * Extracts and transfers elements from *source* to this container. - * - * @param source A {@link MapContainer map container} to transfer the elements from. - */ - abstract merge(source: MapContainer): void; - /** - *

    Abstract method handling insertions for indexing.

    - * - *

    This method, {@link _Handle_insert} is designed to register the first to last to somewhere storing - * those {@link MapIterator iterators} for indexing, fast accessment and retrievalance.

    - * - *

    When {@link insert} is called, new elements will be inserted into the {@link data_ list container} and new - * {@link MapIterator iterators} first to last, pointing the inserted elements, will be created and the - * newly created iterators first to last will be shifted into this method {@link _Handle_insert} after the - * insertions.

    - * - *

    If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the {@link MapIterator iterators} - * will be registered into the {@link TreeSet.tree_ tree} as a {@link XTreeNode tree node item}. Else if the - * derived one is {@link HashBuckets hash-based} like {@link HashSet}, the first to last will be - * registered into the {@link HashSet.hash_buckets_ hash bucket}.

    - * - * @param first An {@link MapIterator} to the initial position in a sequence. - * @param last An {@link MapIterator} to the final position in a sequence. 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. - */ - protected abstract _Handle_insert(first: MapIterator, last: MapIterator): void; - /** - *

    Abstract method handling deletions for indexing.

    - * - *

    This method, {@link _Handle_erase} is designed to unregister the first to last to somewhere storing - * those {@link MapIterator iterators} for indexing, fast accessment and retrievalance.

    - * - *

    When {@link erase} is called with first to last, {@link MapIterator iterators} positioning somewhere - * place to be deleted, is memorized and shifted to this method {@link _Handle_erase} after the deletion process is - * terminated.

    - * - *

    If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the {@link MapIterator iterators} - * will be unregistered from the {@link TreeSet.tree_ tree} as a {@link XTreeNode tree node item}. Else if the - * derived one is {@link HashBuckets hash-based} like {@link HashSet}, the first to last will be - * unregistered from the {@link HashSet.hash_buckets_ hash bucket}.

    - * - * @param first An {@link MapIterator} to the initial position in a sequence. - * @param last An {@link MapIterator} to the final position in a sequence. 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. - */ - protected abstract _Handle_erase(first: MapIterator, last: MapIterator): void; - } - /** - * @hidden - */ - class MapElementList extends ListContainer, MapIterator> { - private associative_; - private rend_; - constructor(associative: MapContainer); - protected _Create_iterator(prev: MapIterator, next: MapIterator, val: Pair): MapIterator; - protected _Set_begin(it: MapIterator): void; - get_associative(): MapContainer; - rbegin(): MapReverseIterator; - rend(): MapReverseIterator; - } -} -declare namespace std { - /** - *

    An iterator of {@link MapContainer map container}.

    - * - *

    - *

    - * - * @author Jeongho Nam - */ - class MapIterator extends base.ListIteratorBase> implements IComparable> { - /** - * Construct from the {@link MapContainer source map} and {@link ListIterator list iterator}. - * - * @param source The source {@link MapContainer}. - * @param list_iterator A {@link ListIterator} pointing {@link Pair} of key and value. - */ - constructor(source: base.MapElementList, prev: MapIterator, next: MapIterator, val: Pair); - /** - * Get iterator to previous element. - */ - prev(): MapIterator; - /** - * Get iterator to next element. - */ - next(): MapIterator; - /** - * Advances the Iterator by n element positions. - * - * @param step Number of element positions to advance. - * @return An advanced Iterator. - */ - advance(step: number): MapIterator; - /** - * @hidden - */ - get_source(): base.MapContainer; - /** - * Get first, key element. - */ - readonly first: Key; - /** - * Get second, value element. - */ - /** - * Set second value. - */ - second: T; - /** - * @inheritdoc - */ - less(obj: MapIterator): boolean; - /** - * @inheritdoc - */ - equals(obj: MapIterator): boolean; - /** - * @inheritdoc - */ - hashCode(): number; - /** - * @inheritdoc - */ - swap(obj: MapIterator): void; - } - /** - *

    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(base: MapIterator): MapReverseIterator; - /** - * Get first, key element. - */ - readonly first: Key; - /** - * Get second, value element. - */ - /** - * Set second value. - */ - second: T; - } -} -declare namespace std.base { - /** - *

    An abstract multi-map.

    - * - *

    {@link MultiMap MultiMaps} are associative containers that store elements formed by a combination of a - * key value (Key) and a mapped value (T), and which allows for fast retrieval of - * individual elements based on their keys.

    - * - *

    In a {@link MapContainer}, the key values are generally used to identify the elements, while the - * mapped values store the content associated to this key. The types of key and - * mapped value may differ, and are grouped together in member type value_type, which is a - * {@link Pair} type combining both:

    - * - *

    typedef pair value_type;

    - * - *

    {@link UniqueMap} 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. - *
    - * - *
    Map
    - *
    - * Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value. - *
    - * - *
    Multiple equivalent keys
    - *
    Multiple elements in the container can have equivalent keys.
    - *
    - * - * @param Type of the keys. Each element in a map is identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @author Jeongho Nam - */ - abstract class MultiMap extends MapContainer { - /** - * Construct and insert element. - * - * Inserts a new element in the {@link MultiMap}. This new element is constructed in place using args - * as the arguments for the element's constructor. - * - * This effectively increases the container {@link size} by one. - * - * A similar member function exists, {@link insert}, which either copies or moves existing objects into the - * container. - * - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return An {@link MapIterator iterator} to the newly inserted element. - */ - emplace(key: Key, value: T): MapIterator; - /** - * Construct and insert element. - * - * Inserts a new element in the {@link MultiMap}. This new element is constructed in place using args - * as the arguments for the element's constructor. - * - * This effectively increases the container {@link size} by one. - * - * A similar member function exists, {@link insert}, which either copies or moves existing objects into the - * container. - * - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * @return An {@link MapIterator iterator} to the newly inserted element. - */ - emplace(pair: Pair): MapIterator; - /** - *

    Insert elements.

    - * - *

    Extends the container by inserting new elements, effectively increasing the container {@link size} by - * the number of elements inserted.

    - * - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return An iterator pointing to the newly inserted element. - */ - insert(pair: Pair): MapIterator; - /** - *

    Insert elements.

    - * - *

    Extends the container by inserting new elements, effectively increasing the container {@link size} by - * the number of elements inserted.

    - * - * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. - * - * @return An iterator pointing to the newly inserted element. - */ - insert(tuple: [L, U]): MapIterator; - /** - * @inheritdoc - */ - insert(hint: MapIterator, pair: Pair): MapIterator; - /** - * @inheritdoc - */ - insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; - /** - * @inheritdoc - */ - insert(hint: MapIterator, tuple: [L, U]): MapIterator; - /** - * @inheritdoc - */ - insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; - /** - * @inheritdoc - */ - insert>>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - merge(source: MapContainer): void; - } -} -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 - * 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.
    - *
    - * - * @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 SetContainer extends Container { - /** - *

    {@link List} storing elements.

    - * - *

    Storing elements and keeping those sequence of the {@link SetContainer} are implemented by - * {@link data_ this list container}. Implementing index-table is also related with {@link data_ this list} - * by storing {@link ListIterator iterators} ({@link SetIterator} references {@link ListIterator}) who are - * created from {@link data_ here}.

    - */ - private data_; - /** - * Default Constructor. - */ - protected constructor(); - /** - * @inheritdoc - */ - assign>(begin: Iterator, end: Iterator): void; - /** - * @inheritdoc - */ - clear(): void; - /** - *

    Get iterator to element.

    - * - *

    Searches the container for an element with key as value and returns an iterator to it if found, - * otherwise it returns an iterator to {@link end end()} (the element past the end of the container).

    - * - *

    Another member function, {@link count count()}, can be used to just check whether a particular element - * exists.

    - * - * @param key Key to be searched for. - * - * @return An iterator to the element, if the specified value is found, or {@link end end()} if it is not - * found in the - */ - abstract find(val: T): SetIterator; - /** - * @inheritdoc - */ - begin(): SetIterator; - /** - * @inheritdoc - */ - end(): SetIterator; - /** - * @inheritdoc - */ - rbegin(): SetReverseIterator; - /** - * @inheritdoc - */ - rend(): SetReverseIterator; - /** - *

    Whether have the item or not.

    - * - *

    Indicates whether a set has an item having the specified identifier.

    - * - * @param key Key value of the element whose mapped value is accessed. - * - * @return Whether the set has an item having the specified identifier. - */ - has(val: T): boolean; - /** - *

    Count elements with a specific key.

    - * - *

    Searches the container for elements with a value of k and returns the number of elements found.

    - * - * @param key Value of the elements to be counted. - * - * @return The number of elements in the container with a key. - */ - abstract count(val: T): number; - /** - * @inheritdoc - */ - size(): number; - /** - * @inheritdoc - */ - push(...args: T[]): number; - /** - *

    Insert an element with hint.

    - * - *

    Extends the container by inserting new elements, effectively increasing the container size by the - * number of elements inserted.

    - * - * @param hint Hint for the position where the element can be inserted. - * @param val Value to be inserted as an element. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had its - * same value in the {@link SetContainer}. - */ - insert(hint: SetIterator, val: T): SetIterator; - /** - *

    Insert an element with hint.

    - * - *

    Extends the container by inserting new elements, effectively increasing the container size by the - * number of elements inserted.

    - * - * @param hint Hint for the position where the element can be inserted. - * @param val Value to be inserted as an element. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had its - * same value in the {@link SetContainer}. - */ - insert(hint: SetReverseIterator, val: T): SetReverseIterator; - /** - *

    Insert elements with a range of a

    - * - *

    Extends the container by inserting new elements, effectively increasing the container size by the - * number of elements inserted.

    - * - * @param begin An iterator specifying range of the begining element. - * @param end An iterator specifying range of the ending element. - */ - insert>(begin: InputIterator, end: InputIterator): void; - /** - * @hidden - */ - protected abstract _Insert_by_val(val: T): any; - /** - * @hidden - */ - protected abstract _Insert_by_hint(hint: SetIterator, val: T): SetIterator; - /** - * @hidden - */ - protected abstract _Insert_by_range>(begin: InputIterator, end: InputIterator): void; - /** - *

    Erase an element.

    - *

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

    - * - *

    This effectively reduces the container size by the number of elements removed.

    - * - * @param key Value of the elements to be erased. - * - * @return Number of elements erased. - */ - erase(val: T): number; - /** - * @inheritdoc - */ - erase(it: SetIterator): SetIterator; - /** - *

    Erase elements.

    - *

    Removes from the set container a range of elements..

    - * - *

    This effectively reduces the container size by the number of elements removed.

    - * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - */ - erase(begin: SetIterator, end: SetIterator): SetIterator; - /** - * @inheritdoc - */ - erase(it: SetReverseIterator): SetReverseIterator; - /** - *

    Erase elements.

    - *

    Removes from the set container a range of elements..

    - * - *

    This effectively reduces the container size by the number of elements removed.

    - * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - */ - erase(begin: SetReverseIterator, end: SetReverseIterator): SetReverseIterator; - /** - * @hidden - */ - private erase_by_iterator(first, last?); - /** - * @hidden - */ - private erase_by_val(val); - /** - * @hidden - */ - private erase_by_range(first, last); - /** - * @hidden - */ - protected _Swap(obj: SetContainer): void; - /** - * Merge two sets. - * - * Extracts and transfers elements from *source* to this container. - * - * @param source A {@link SetContainer set container} to transfer the elements from. - */ - abstract merge(source: SetContainer): void; - /** - *

    Abstract method handling insertions for indexing.

    - * - *

    This method, {@link _Handle_insert} is designed to register the first to last to somewhere storing - * those {@link SetIterator iterators} for indexing, fast accessment and retrievalance.

    - * - *

    When {@link insert} is called, new elements will be inserted into the {@link data_ list container} and new - * {@link SetIterator iterators} first to last, pointing the inserted elements, will be created and the - * newly created iterators first to last will be shifted into this method {@link _Handle_insert} after the - * insertions.

    - * - *

    If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the {@link SetIterator iterators} - * will be registered into the {@link TreeSet.tree_ tree} as a {@link XTreeNode tree node item}. Else if the - * derived one is {@link HashBuckets hash-based} like {@link HashSet}, the first to last will be - * registered into the {@link HashSet.hash_buckets_ hash bucket}.

    - * - * @param first An {@link SetIterator} to the initial position in a sequence. - * @param last An {@link SetIterator} to the final position in a sequence. 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. - */ - protected abstract _Handle_insert(first: SetIterator, last: SetIterator): void; - /** - *

    Abstract method handling deletions for indexing.

    - * - *

    This method, {@link _Handle_erase} is designed to unregister the first to last to somewhere storing - * those {@link SetIterator iterators} for indexing, fast accessment and retrievalance.

    - * - *

    When {@link erase} is called with first to last, {@link SetIterator iterators} positioning somewhere - * place to be deleted, is memorized and shifted to this method {@link _Handle_erase} after the deletion process is - * terminated.

    - * - *

    If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the {@link SetIterator iterators} - * will be unregistered from the {@link TreeSet.tree_ tree} as a {@link XTreeNode tree node item}. Else if the - * derived one is {@link HashBuckets hash-based} like {@link HashSet}, the first to last will be - * unregistered from the {@link HashSet.hash_buckets_ hash bucket}.

    - * - * @param first An {@link SetIterator} to the initial position in a sequence. - * @param last An {@link SetIterator} to the final position in a sequence. 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. - */ - protected abstract _Handle_erase(first: SetIterator, last: SetIterator): void; - } - /** - * @hidden - */ - class SetElementList extends ListContainer> { - private associative_; - private rend_; - constructor(associative: SetContainer); - protected _Create_iterator(prev: SetIterator, next: SetIterator, val: T): SetIterator; - protected _Set_begin(it: SetIterator): void; - get_associative(): SetContainer; - rbegin(): SetReverseIterator; - rend(): SetReverseIterator; - } -} -declare namespace std { - /** - *

    An iterator of a Set.

    - * - *

    - *

    - * - * @author Jeongho Nam - */ - class SetIterator extends base.ListIteratorBase implements IComparable> { - /** - *

    Construct from source and index number.

    - * - *

    Note

    - *

    Do not create iterator directly.

    - *

    Use begin(), find() or end() in Map instead.

    - * - * @param map The source Set to reference. - * @param index Sequence number of the element in the source Set. - */ - constructor(source: base.SetElementList, prev: SetIterator, next: SetIterator, val: T); - /** - * @inheritdoc - */ - get_source(): base.SetContainer; - /** - * @inheritdoc - */ - prev(): SetIterator; - /** - * @inheritdoc - */ - next(): SetIterator; - /** - * @inheritdoc - */ - advance(size: number): SetIterator; - /** - * @inheritdoc - */ - less(obj: SetIterator): boolean; - /** - * @inheritdoc - */ - equals(obj: SetIterator): boolean; - /** - * @inheritdoc - */ - hashCode(): number; - /** - * @inheritdoc - */ - swap(obj: SetIterator): void; - } - /** - *

    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); - /** - * @hidden - */ - protected _Create_neighbor(base: SetIterator): 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 - * 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.
    - * - *
    Multiple equivalent keys
    - *
    Multiple 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 MultiSet extends SetContainer { - /** - *

    Insert an element.

    - * - *

    Extends the container by inserting new elements, effectively increasing the container {@link size} by - * the number of elements inserted.

    - * - * @param key Value to be inserted as an element. - * - * @return An iterator to the newly inserted element. - */ - insert(val: T): SetIterator; - /** - * @inheritdoc - */ - insert(hint: SetIterator, val: T): SetIterator; - /** - * @inheritdoc - */ - insert(hint: SetReverseIterator, val: T): SetReverseIterator; - /** - * @inheritdoc - */ - insert>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - merge(source: SetContainer): void; - } -} -declare namespace std.base { - /** - *

    Red-black Tree.

    - * - *

    A red-black tree is a kind of self-balancing - * binary search tree. Each node of the binary tree has an extra bit, and that bit is often interpreted as the - * color (red or black) of the node. These color bits - * are used to ensure the tree remains approximately balanced during insertions and deletions.

    - * - *

    Balance is preserved by painting each node of the tree with one of two colors (typically called - * 'red' and 'black') in a way that satisfies certain - * properties, which collectively constrain how unbalanced the tree can become in the worst case. When the tree - * is modified, the new tree is subsequently rearranged and repainted to restore the coloring properties. The - * properties are designed in such a way that this rearranging and recoloring can be performed efficiently.

    - * - *

    The balancing of the tree is not perfect but it is good enough to allow it to guarantee searching in - * O(log n) time, where n is the total number of elements in the tree. The insertion and deletion operations, - * along with the tree rearrangement and recoloring, are also performed in O(log n) time.

    - * - *

    Tracking the color of each node requires only 1 bit of information per node because there are only two - * colors. The tree does not contain any other data specific to its being a - * red-black tree so its memory footprint is almost - * identical to a classic (uncolored) binary search tree. In many cases the additional bit of information can - * be stored at no additional memory cost.

    - * - *

    Properties

    - *

    In addition to the requirements imposed on a binary search tree the following must be satisfied by a - * red-black tree:

    - * - *
      - *
    1. A node is either red or black.
    2. - *
    3. - * The root is black. This rule is sometimes omitted. Since the root can - * always be changed from red to black, but not - * necessarily vice versa, this rule has little effect on analysis. - *
    4. - *
    5. All leaves (NIL; null) are black.
    6. - *
    7. - * If a node is red, then both its children are - * black. - *
    8. - *
    9. - * Every path from a given node to any of its descendant NIL nodes contains the same number of - * black nodes. Some definitions: the number of - * black nodes from the root to a node is the node's - * black depth; the uniform number of black - * nodes in all paths from root to the leaves is called the black-height of - * the red-black tree. - *
    10. - *
    - * - *

    - * - *

    These constraints enforce a critical property of red-black trees: the path from the root to the farthest - * leaf is no more than twice as long as the path from the root to the nearest leaf. The result is that the tree - * is roughly height-balanced. Since operations such as inserting, deleting, and finding values require - * worst-case time proportional to the height of the tree, this theoretical upper bound on the height allows - * red-black trees to be efficient in the worst case, unlike ordinary binary search trees.

    - * - *

    To see why this is guaranteed, it suffices to consider the effect of properties 4 and 5 together. For a - * red-black tree T, let B be the number of black nodes in property 5. Let the - * shortest possible path from the root of T to any leaf consist of B black nodes. - * Longer possible paths may be constructed by inserting red nodes. However, property 4 - * makes it impossible to insert more than one consecutive red node. Therefore, - * ignoring any black NIL leaves, the longest possible path consists of 2*B nodes, - * alternating black and red (this is the worst case). - * Counting the black NIL leaves, the longest possible path consists of 2*B-1 - * nodes.

    - * - *

    The shortest possible path has all black nodes, and the longest possible - * path alternates between red and black nodes. Since all - * maximal paths have the same number of black nodes, by property 5, this shows - * that no path is more than twice as long as any other path.

    - * - * @param Type of elements. - * - * @reference https://en.wikipedia.org/w/index.php?title=Red%E2%80%93black_tree - * @inventor Rudolf Bayer - * @author Migrated by Jeongho Nam - */ - abstract class XTree { - /** - * Root node. - */ - protected root_: XTreeNode; - /** - * Default Constructor. - */ - protected constructor(); - /** - * Clear, removes all tree nodes. - */ - clear(): void; - /** - * Find a node from its contained value. - * - * @param val Value to find. - */ - find(val: T): XTreeNode; - /** - * Fetch maximum (the rightes?) node from one. - * - * @param node A node to fetch its maximum node. - * @return The maximum node. - */ - protected fetch_maximum(node: XTreeNode): XTreeNode; - abstract is_less(left: T, right: T): boolean; - abstract is_equal_to(left: T, right: T): boolean; - /** - *

    Insert an element with a new node.

    - * - *

    Insertion begins by adding the node as any binary search tree insertion does and by coloring it - * red. Whereas in the binary search tree, we always add a leaf, in the red-black - * tree, leaves contain no information, so instead we add a red interior node, with - * two black leaves, in place of an existing - * black leaf.

    - * - *

    What happens next depends on the color of other nearby nodes. The term uncle node will be used to - * refer to the sibling of a node's parent, as in human family trees. Note that:

    - * - *
      - *
    • property 3 (all leaves are black) always holds.
    • - *
    • - * property 4 (both children of every red node are - * black) is threatened only by adding a red - * node, repainting a black node red, or a - * rotation. - *
    • - *
    • - * property 5 (all paths from any given node to its leaf nodes contain the same number of - * black nodes) is threatened only by adding a - * black node, repainting a red node - * black (or vice versa), or a rotation. - *
    • - *
    - * - *

    Notes

    - *
      - *
    1. - * The label N will be used to denote the current node (colored - * red). In the diagrams N carries a blue contour. At the - * beginning, this is the new node being inserted, but the entire procedure may also be applied - * recursively to other nodes (see case 3). {@link XTreeNode.parent P} will denote - * N's parent node, {@link XTreeNode.grand_parent G} will denote N's - * grandparent, and {@link XTreeNode.uncle U} will denote N's uncle. In between - * some cases, the roles and labels of the nodes are exchanged, but in each case, every label continues - * to represent the same node it represented at the beginning of the case. - *
    2. - *
    3. - * If a node in the right (target) half of a diagram carries a blue contour it will become the current - * node in the next iteration and there the other nodes will be newly assigned relative to it. Any - * color shown in the diagram is either assumed in its case or implied by those assumptions. - *
    4. - *
    5. - * A numbered triangle represents a subtree of unspecified depth. A black - * circle atop a triangle means that black-height of subtree is greater - * by one compared to subtree without this circle.
    6. - *
    - * - *

    There are several cases of red-black tree insertion to handle:

    - * - *
      - *
    • N is the root node, i.e., first node of red-black tree.
    • - *
    • - * N's parent ({@link XTreeNode.parent P}) is black. - *
    • - *
    • - * N's parent ({@link XTreeNode.parent P}) and uncle - * ({@link XTreeNode.uncle U}) are red. - *
    • - *
    • - * N is added to right of left child of grandparent, or N is added to left - * of right child of grandparent ({@link XTreeNode.parent P} is red and - * {@link XTreeNode.uncle U} is black). - *
    • - *
    • - * N is added to left of left child of grandparent, or N is added to right - * of right child of grandparent ({@link XTreeNode.parent P} is red and - * {@link XTreeNode.uncle U} is black). - *
    • - *
    - * - *

    Note

    - *

    Note that inserting is actually in-place, since all the calls above use tail recursion.

    - * - *

    In the algorithm above, all cases are chained in order, except in insert case 3 where it can recurse - * to case 1 back to the grandparent node: this is the only case where an iterative implementation will - * effectively loop. Because the problem of repair is escalated to the next higher level but one, it takes - * maximally h⁄2 iterations to repair the tree (where h is the height of the tree). Because the probability - * for escalation decreases exponentially with each iteration the average insertion cost is constant.

    - * - * @param val An element to insert. - */ - insert(val: T): void; - /** - *

    N is the root node, i.e., first node of red-black tree.

    - * - *

    The current node N is at the {@link root_ root} of the tree.

    - * - *

    In this case, it is repainted black to satisfy property 2 (the root is - * black). Since this adds one black node to - * every path at once, property 5 (all paths from any given node to its leaf nodes contain the same number - * of black nodes) is not violated.

    - * - * @param N A node to be inserted or swapped. - */ - private insert_case1(N); - /** - *

    N's parent ({@link XTreeNode.parent P}) is black.

    - * - *

    The current node's parent {@link XTreeNode.parent P} is black, - * so property 4 (both children of every red node are - * black) is not invalidated.

    - * - *

    In this case, the tree is still valid. Property 5 (all paths from any given node to its leaf nodes - * contain the same number of black nodes) is not threatened, because the - * current node N has two black leaf children, but because - * N is red, the paths through each of its children have the same - * number of black nodes as the path through the leaf it replaced, which was - * black, and so this property remains satisfied.

    - * - * @param N A node to be inserted or swapped. - */ - private insert_case2(N); - /** - *

    N's parent ({@link XTreeNode.parent P}) and uncle - * ({@link XTreeNode.uncle U}) are red.

    - * - *

    If both the parent {@link XTreeNode.parent P} and the uncle {@link XTreeNode.uncle U} - * are red, then both of them can be repainted black - * and the grandparent {@link XTreeNode.grand_parent G} becomes red (to - * maintain property 5 (all paths from any given node to its leaf nodes contain the same number of - * black nodes)).

    - * - *

    Now, the current red node N has a - * black parent. Since any path through the parent or uncle must pass through - * the grandparent, the number of black nodes on these paths has not changed. - * - *

    However, the grandparent {@link XTreeNode.grand_parent G} may now violate properties 2 (The - * root is black) or 4 (Both children of every red - * node are black) (property 4 possibly being violated since - * {@link XTreeNode.grand_parent G} may have a red parent).

    - * - *

    To fix this, the entire procedure is recursively performed on {@link XTreeNode.grand_parent G} - * from case 1. Note that this is a tail-recursive call, so it could be rewritten as a loop; since this is - * 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. - */ - private insert_case3(N); - /** - *

    N is added to right of left child of grandparent, or N is added to left - * of right child of grandparent ({@link XTreeNode.parent P} is red and - * {@link XTreeNode.uncle U} is black).

    - * - *

    The parent {@link XTreeNode.parent P} is red but the uncle - * {@link XTreeNode.uncle U} is black; also, the current node - * N is the right child of {@link XTreeNode.parent P}, and - * {@link XTreeNode.parent P} in turn is the left child of its parent - * {@link XTreeNode.grand_parent G}.

    - * - *

    In this case, a left rotation on {@link XTreeNode.parent P} that switches the roles of the - * current node N and its parent {@link XTreeNode.parent P} can be performed; then, - * the former parent node {@link XTreeNode.parent P} is dealt with using case 5 - * (relabeling N and {@link XTreeNode.parent P}) because property 4 (both children of - * every red node are black) is still violated.

    - * - *

    The rotation causes some paths (those in the sub-tree labelled "1") to pass through the node - * N where they did not before. It also causes some paths (those in the sub-tree labelled "3") - * not to pass through the node {@link XTreeNode.parent P} where they did before. However, both of - * these nodes are red, so property 5 (all paths from any given node to its leaf - * nodes contain the same number of black nodes) is not violated by the - * rotation.

    - * - *

    After this case has been completed, property 4 (both children of every red - * 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. - */ - private insert_case4(node); - /** - *

    N is added to left of left child of grandparent, or N is added to right - * of right child of grandparent ({@link XTreeNode.parent P} is red and - * {@link XTreeNode.uncle U} is black).

    - * - *

    The parent {@link XTreeNode.parent P} is red but the uncle - * {@link XTreeNode.uncle U} is black, the current node N - * is the left child of {@link XTreeNode.parent P}, and {@link XTreeNode.parent P} is the left - * child of its parent {@link XTreeNode.grand_parent G}.

    - * - *

    In this case, a right rotation on {@link XTreeNode.grand_parent G} is performed; the result is a - * tree where the former parent {@link XTreeNode.parent P} is now the parent of both the current node - * N and the former grandparent {@link XTreeNode.grand_parent G}.

    - * - *

    {@link XTreeNode.grand_parent G} is known to be black, since its - * former child {@link XTreeNode.parent P} could not have been red otherwise - * (without violating property 4). Then, the colors of {@link XTreeNode.parent P} and - * {@link XTreeNode.grand_parent G} are switched, and the resulting tree satisfies property 4 (both - * children of every red node are black). Property 5 - * (all paths from any given node to its leaf nodes contain the same number of - * black nodes) also remains satisfied, since all paths that went through any - * of these three nodes went through {@link XTreeNode.grand_parent G} before, and now they all go - * 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. - */ - private insert_case5(node); - /** - *

    Erase an element with its node.

    - * - *

    In a regular binary search tree when deleting a node with two non-leaf children, we find either the - * maximum element in its left subtree (which is the in-order predecessor) or the minimum element in its - * right subtree (which is the in-order successor) and move its value into the node being deleted (as shown - * here). We then delete the node we copied the value from, which must have fewer than two non-leaf children. - * (Non-leaf children, rather than all children, are specified here because unlike normal binary search - * trees, red-black trees can have leaf nodes anywhere, so that all nodes are either internal nodes with - * two children or leaf nodes with, by definition, zero children. In effect, internal nodes having two leaf - * children in a red-black tree are like the leaf nodes in a regular binary search tree.) Because merely - * copying a value does not violate any red-black properties, this reduces to the problem of deleting a node - * with at most one non-leaf child. Once we have solved that problem, the solution applies equally to the - * case where the node we originally want to delete has at most one non-leaf child as to the case just - * considered where it has two non-leaf children.

    - * - *

    Therefore, for the remainder of this discussion we address the deletion of a node with at most one - * non-leaf child. We use the label M to denote the node to be deleted; C will denote a - * selected child of M, which we will also call "its child". If M does have a non-leaf child, - * call that its child, C; otherwise, choose either leaf as its child, C.

    - * - *

    If M is a red node, we simply replace it with its child C, - * which must be black by property 4. (This can only occur when M has - * two leaf children, because if the red node M had a - * black non-leaf child on one side but just a leaf child on the other side, - * then the count of black nodes on both sides would be different, thus the - * tree would violate property 5.) All paths through the deleted node will simply pass through one fewer - * red node, and both the deleted node's parent and child must be - * black, so property 3 (all leaves are black) - * and property 4 (both children of every red node are - * black) still hold.

    - * - *

    Another simple case is when M is black and C is - * red. Simply removing a black node could break - * Properties 4 (“Both children of every red node are - * black”) and 5 (“All paths from any given node to its leaf nodes contain the - * same number of black nodes”), but if we repaint C - * black, both of these properties are preserved.

    - * - *

    The complex case is when both M and C are black. (This - * can only occur when deleting a black node which has two leaf children, - * because if the black node M had a black - * non-leaf child on one side but just a leaf child on the other side, then the count of - * black nodes on both sides would be different, thus the tree would have been - * an invalid red-black tree by violation of property 5.) We begin by replacing M with its child - * C. We will relabel this child C (in its new position) N, and its sibling (its - * new parent's other child) {@link XTreeNode.sibling S}. ({@link XTreeNode.sibling S} was - * previously the sibling of M.)

    - * - *

    In the diagrams below, we will also use {@link XTreeNode.parent P} for N's new - * parent (M's old parent), SL for {@link XTreeNode.sibling S}'s left child, and - * SR for {@link XTreeNode.sibling S}'s right child ({@link XTreeNode.sibling S} cannot - * be a leaf because if M and C were black, then - * {@link XTreeNode.parent P}'s one subtree which included M counted two - * black-height and thus {@link XTreeNode.parent P}'s other subtree - * which includes {@link XTreeNode.sibling S} must also count two - * black-height, which cannot be the case if {@link XTreeNode.sibling S} - * is a leaf node).

    - * - *

    Notes

    - *
      - *
    1. - * The label N will be used to denote the current node (colored - * black). In the diagrams N carries a blue contour. At the - * beginning, this is the replacement node and a leaf, but the entire procedure may also be applied - * recursively to other nodes (see case 3). In between some cases, the roles and labels of the nodes - * are exchanged, but in each case, every label continues to represent the same node it represented at - * the beginning of the case. - *
    2. - *
    3. - * If a node in the right (target) half of a diagram carries a blue contour it will become the current - * node in the next iteration and there the other nodes will be newly assigned relative to it. Any - * color shown in the diagram is either assumed in its case or implied by those assumptions. - * White represents an arbitrary color (either red or - * black), but the same in both halves of the diagram. - *
    4. - *
    5. - * A numbered triangle represents a subtree of unspecified depth. A black - * circle atop a triangle means that black-height of subtree is greater - * by one compared to subtree without this circle. - *
    6. - *
    - * - *

    If both N and its original parent are black, then - * deleting this original parent causes paths which proceed through N to have one fewer - * black node than paths that do not. As this violates property 5 (all paths - * from any given node to its leaf nodes contain the same number of black - * nodes), the tree must be rebalanced. There are several cases to consider:

    - * - *
      - *
    1. N is the new root.
    2. - *
    3. {@link XTreeNode.sibling S} is red.
    4. - *
    5. - * {@link XTreeNode.parent P}, {@link XTreeNode.sibling S}, and - * {@link XTreeNode.sibling S}'s children are black.
    6. - *
    7. - * {@link XTreeNode.sibling S} and {@link XTreeNode.sibling S}'s children are - * black, but {@link XTreeNode.parent P} is - * red. - *
    8. - *
    9. - * {@link XTreeNode.sibling S} is black, - * {@link XTreeNode.sibling S}'s left child is red, - * {@link XTreeNode.sibling S}'s right child is black, and - * N is the left child of its parent. - *
    10. - *
    11. - * {@link XTreeNode.sibling S} is black, - * {@link XTreeNode.sibling S}'s right child is red, and - * N is the left child of its parent {@link XTreeNode.parent P}. - *
    12. - *
    - * - *

    Again, the function calls all use tail recursion, so the algorithm is in-place.

    - * - *

    In the algorithm above, all cases are chained in order, except in delete case 3 where it can recurse - * to case 1 back to the parent node: this is the only case where an iterative implementation will - * effectively loop. No more than h loops back to case 1 will occur (where h is the height of the tree). - * And because the probability for escalation decreases exponentially with each iteration the average - * removal cost is constant.

    - * - *

    Additionally, no tail recursion ever occurs on a child node, so the tail recursion loop can only - * move from a child back to its successive ancestors. If a rotation occurs in case 2 (which is the only - * possibility of rotation within the loop of cases 1–3), then the parent of the node N - * becomes red after the rotation and we will exit the loop. Therefore, at most one - * rotation will occur within this loop. Since no more than two additional rotations will occur after - * exiting the loop, at most three rotations occur in total.

    - * - * @param val An element to erase. - */ - erase(val: T): void; - /** - *

    N is the new root.

    - * - *

    In this case, we are done. We removed one black node from every path, - * and the new root is black, so the properties are preserved.

    - * - *

    Note

    - *

    In cases 2, 5, and 6, we assume N is the left child of its parent - * {@link XTreeNode.parent P}. If it is the right child, left and right should be reversed throughout - * these three cases. Again, the code examples take both cases into account.

    - * - * @param N A node to be erased or swapped. - */ - private erase_case1(N); - /** - *

    {@link XTreeNode.sibling S} is red.

    - * - *

    - * - *

    In this case we reverse the colors of {@link XTreeNode.parent P} and - * {@link XTreeNode.sibling S}, and then rotate left at {@link XTreeNode.parent P}, turning - * {@link XTreeNode.sibling S} into N's grandparent.

    - * - *

    Note that {@link XTreeNode.parent P} has to be black as it had a - * red child. The resulting subtree has a path short one - * black node so we are not done. Now N has a - * black sibling and a red parent, so we can proceed - * to step 4, 5, or 6. (Its new sibling is black because it was once the child - * of the red {@link XTreeNode.sibling S}.) In later cases, we will re-label - * N's new sibling as {@link XTreeNode.sibling S}.

    - * - * @param N A node to be erased or swapped. - */ - private erase_case2(N); - /** - *

    {@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 - * result is that all paths passing through {@link XTreeNode.sibling S}, which are precisely those - * paths not passing through N, have one less black node. - * Because deleting N's original parent made all paths passing through N have - * one less black node, this evens things up.

    - * - *

    However, all paths through {@link XTreeNode.parent P} now have one fewer - * black node than paths that do not pass through - * {@link XTreeNode.parent P}, so property 5 (all paths from any given node to its leaf nodes contain - * the same number of black nodes) is still violated.

    - * - *

    To correct this, we perform the rebalancing procedure on {@link XTreeNode.parent P}, starting - * at case 1.

    - * - * @param N A node to be erased or swapped. - */ - private erase_case3(N); - /** - *

    {@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 - * {@link XTreeNode.parent P}. This does not affect the number of black - * nodes on paths going through {@link XTreeNode.sibling S}, but it does add one to the number of - * black nodes on paths going through N, making up for the - * deleted black node on those paths.

    - * - * @param N A node to be erased or swapped. - */ - private erase_case4(N); - /** - *

    {@link XTreeNode.sibling S} is black, {@link XTreeNode.sibling S}'s - * 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 - * {@link XTreeNode.sibling S}'s left child becomes {@link XTreeNode.sibling S}'s parent and - * N's new sibling. We then exchange the colors of {@link XTreeNode.sibling S} and its - * new parent.

    - * - *

    All paths still have the same number of black nodes, but now - * N has a black sibling whose right child is - * red, so we fall into case 6. Neither N nor its parent are affected - * by this transformation. (Again, for case 6, we relabel N's new sibling as - * {@link XTreeNode.sibling S}.)

    - * - * @param N A node to be erased or swapped. - */ - private erase_case5(N); - /** - *

    {@link XTreeNode.sibling S} is black, - * {@link XTreeNode.sibling S}'s right child is red, and N is - * the left child of its parent {@link XTreeNode.parent P}.

    - * - *

    In this case we rotate left at {@link XTreeNode.parent P}, so that - * {@link XTreeNode.sibling S} becomes the parent of {@link XTreeNode.parent P} and - * {@link XTreeNode.sibling S}'s right child. We then exchange the colors of - * {@link XTreeNode.parent P} and {@link XTreeNode.sibling S}, and make - * {@link XTreeNode.sibling S}'s right child black.

    - * - *

    The subtree still has the same color at its root, so Properties 4 (Both children of every - * red node are black) and 5 (All paths from any - * given node to its leaf nodes contain the same number of black nodes) are - * not violated. However, N now has one additional black - * ancestor: either {@link XTreeNode.parent P} has become black, or it - * was black and {@link XTreeNode.sibling S} was added as a - * black grandparent.

    - * - *

    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:

    - *
      - *
    1. - * It goes through N's new sibling SL, a node with arbitrary color and the root of - * the subtree labeled 3 (s. diagram). Then, it must go through {@link XTreeNode.sibling S} and - * {@link XTreeNode.parent P}, both formerly and currently, as they have only exchanged colors - * and places. Thus the path contains the same number of black nodes. - *
    2. - *
    3. - * It goes through N's new uncle, {@link XTreeNode.sibling S}'s right child. Then, - * it formerly went through {@link XTreeNode.sibling S}, {@link XTreeNode.sibling S}'s - * parent, and {@link XTreeNode.sibling S}'s right child SR (which was - * red), but now only goes through {@link XTreeNode.sibling S}, which - * has assumed the color of its former parent, and {@link XTreeNode.sibling S}'s right child, - * which has changed from red to black (assuming - * {@link XTreeNode.sibling S}'s color: black). The net effect is - * that this path goes through the same number of black nodes. - *
    4. - *
    - * - *

    Either way, the number of black nodes on these paths does not change. - * Thus, we have restored Properties 4 (Both children of every red node are - * black) and 5 (All paths from any given node to its leaf nodes contain the - * same number of black nodes). The white node in the diagram can be either - * red or black, but must refer to the same color - * both before and after the transformation.

    - * - * @param N A node to be erased or swapped. - */ - private erase_case6(node); - /** - * Rotate a node left. - * - * @param node Node to rotate left. - */ - protected rotate_left(node: XTreeNode): void; - /** - * Rotate a node to right. - * - * @param node A node to rotate right. - */ - protected rotate_right(node: XTreeNode): void; - /** - * Replace a node. - * - * @param oldNode Ordinary node to be replaced. - * @param newNode Target node to replace. - */ - protected replace_node(oldNode: XTreeNode, newNode: XTreeNode): void; - /** - * Fetch color from a node. - * - * @param node A node to fetch color. - * @retur color. - */ - private fetch_color(node); - } -} -declare namespace std.base { - /** - *

    Common interface for tree-structured map.

    - * - *

    {@link ITreeMap ITreeMaps} are associative containers that store elements formed by a combination of - * a key value and a mapped value, following a specific order.

    - * - *

    In a {@link ITreeMap}, the key values are generally used to sort and uniquely identify - * the elements, while the mapped values store the content associated to this key. The types of - * key and mapped value may differ, and are grouped together in member type - * value_type, which is a {@link Pair} type combining both:

    - * - *

    typedef Pair value_type;

    - * - *

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

    - * - *

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

    - * - *

    {@link ITreeMap TreeMultiMaps} 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.
    - * - *
    Map
    - *
    Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value.
    - *
    - * - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/map - * @author Jeongho Nam - */ - interface ITreeMap { - /** - *

    Return key comparison function.

    - * - *

    Returns a references of the comparison function used by the container to compare keys.

    - * - *

    The comparison object of a {@link ITreeMap tree-map object} is set on - * {@link TreeMap.constructor construction}. Its type (Key) is the last parameter of the - * {@link ITreeMap.constructor constructors}. By default, this is a {@link less} function, which returns the same - * as operator<.

    - * - *

    This function determines the order of the elements in the container: it is a function pointer that takes - * two arguments of the same type as the element keys, and returns true if the first argument - * is considered to go before the second in the strict weak ordering it defines, and false otherwise. - *

    - * - *

    Two keys are considered equivalent if {@link key_comp} returns false reflexively (i.e., no - * matter the order in which the keys are passed as arguments).

    - * - * @return The comparison function. - */ - key_comp(): (x: Key, y: Key) => boolean; - /** - *

    Return value comparison function.

    - * - *

    Returns a comparison function that can be used to compare two elements to get whether the key of the first - * one goes before the second.

    - * - *

    The arguments taken by this function object are of member type std.Pair (defined in - * {@link ITreeMap}), but the mapped type (T) part of the value is not taken into consideration in this - * comparison.

    - * - *

    This comparison class returns true if the {@link Pair.first key} of the first argument - * is considered to go before that of the second (according to the strict weak ordering specified by the - * container's comparison function, {@link key_comp}), and false otherwise.

    - * - * @return The comparison function for element values. - */ - value_comp(): (x: Pair, y: Pair) => boolean; - /** - *

    Return iterator to lower bound.

    - * - *

    Returns an iterator pointing to the first element in the container whose key is not considered to - * go before k (i.e., either it is equivalent or goes after).

    - * - *

    The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(k, element_key) would return false.

    - * - *

    If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element whose key is not less than k

    . - * - *

    A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except - * in the case that the {@link ITreeMap} contains an element with a key equivalent to k: In this - * case, {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} - * returns an iterator pointing to the next element.

    - * - * @param k Key to search for. - * - * @return An iterator to the the first element in the container whose key is not considered to go before - * k, or {@link ITreeMap.end} if all keys are considered to go before k. - */ - lower_bound(key: Key): MapIterator; - /** - *

    Return iterator to upper bound.

    - * - *

    Returns an iterator pointing to the first element in the container whose key is considered to - * go after k

    . - * - *

    The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(k, element_key) would return true.

    - * - *

    If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element whose key is greater than k

    . - * - *

    A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except - * in the case that the map contains an element with a key equivalent to k: In this case - * {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} returns an - * iterator pointing to the next element.

    - * - * @param k Key to search for. - * - * @return An iterator to the the first element in the container whose key is considered to go after - * k, or {@link TreeMap.end end} if no keys are considered to go after k. - */ - upper_bound(key: Key): MapIterator; - /** - *

    Get range of equal elements.

    - * - *

    Returns the bounds of a range that includes all the elements in the container which have a key - * equivalent to k

    . - * - *

    If no matches are found, the range returned has a length of zero, with both iterators pointing to - * the first element that has a key considered to go after k according to the container's internal - * comparison object (key_comp).

    - * - *

    Two keys are considered equivalent if the container's comparison object returns false reflexively - * (i.e., no matter the order in which the keys are passed as arguments).

    - * - * @param k Key to search for. - * - * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of - * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound - * (the same as {@link upper_bound}). - */ - equal_range(key: Key): Pair, MapIterator>; - } -} -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. - */ - constructor(map: TreeMap | TreeMultiMap, compare?: (x: Key, y: Key) => boolean); - find(key: Key): XTreeNode>; - find(it: MapIterator): XTreeNode>; - /** - * @hidden - */ - private find_by_key(key); - /** - *

    Return iterator to lower bound.

    - * - *

    Returns an iterator pointing to the first element in the container whose key is not considered to - * go before k (i.e., either it is equivalent or goes after).

    - * - *

    The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(k, element_key) would return false.

    - * - *

    If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element whose key is not less than k

    . - * - *

    A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except - * in the case that the {@link ITreeMap} contains an element with a key equivalent to k: In this - * case, {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} - * returns an iterator pointing to the next element.

    - * - * @param k Key to search for. - * - * @return An iterator to the the first element in the container whose key is not considered to go before - * k, or {@link ITreeMap.end} if all keys are considered to go before k. - */ - lower_bound(key: Key): MapIterator; - /** - *

    Return iterator to upper bound.

    - * - *

    Returns an iterator pointing to the first element in the container whose key is considered to - * go after k

    . - * - *

    The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(k, element_key) would return true.

    - * - *

    If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element whose key is greater than k

    . - * - *

    A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except - * in the case that the map contains an element with a key equivalent to k: In this case - * {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} returns an - * iterator pointing to the next element.

    - * - * @param k Key to search for. - * - * @return An iterator to the the first element in the container whose key is considered to go after - * k, or {@link TreeMap.end end} if no keys are considered to go after k. - */ - upper_bound(key: Key): MapIterator; - /** - *

    Get range of equal elements.

    - * - *

    Returns the bounds of a range that includes all the elements in the container which have a key - * equivalent to k

    . - * - *

    If no matches are found, the range returned has a length of zero, with both iterators pointing to - * the first element that has a key considered to go after k according to the container's internal - * comparison object (key_comp).

    - * - *

    Two keys are considered equivalent if the container's comparison object returns false reflexively - * (i.e., no matter the order in which the keys are passed as arguments).

    - * - * @param k Key to search for. - * - * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of - * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound - * (the same as {@link upper_bound}). - */ - equal_range(key: Key): Pair, MapIterator>; - /** - *

    Return key comparison function.

    - * - *

    Returns a references of the comparison function used by the container to compare keys.

    - * - *

    The comparison object of a {@link ITreeMap tree-map object} is set on - * {@link TreeMap.constructor construction}. Its type (Key) is the last parameter of the - * {@link ITreeMap.constructor constructors}. By default, this is a {@link less} function, which returns the same - * as operator<.

    - * - *

    This function determines the order of the elements in the container: it is a function pointer that takes - * two arguments of the same type as the element keys, and returns true if the first argument - * is considered to go before the second in the strict weak ordering it defines, and false otherwise. - *

    - * - *

    Two keys are considered equivalent if {@link key_comp} returns false reflexively (i.e., no - * matter the order in which the keys are passed as arguments).

    - * - * @return The comparison function. - */ - key_comp(): (x: Key, y: Key) => boolean; - /** - *

    Return value comparison function.

    - * - *

    Returns a comparison function that can be used to compare two elements to get whether the key of the first - * one goes before the second.

    - * - *

    The arguments taken by this function object are of member type std.Pair (defined in - * {@link ITreeMap}), but the mapped type (T) part of the value is not taken into consideration in this - * comparison.

    - * - *

    This comparison class returns true if the {@link Pair.first key} of the first argument - * is considered to go before that of the second (according to the strict weak ordering specified by the - * container's comparison function, {@link key_comp}), and false otherwise.

    - * - * @return The comparison function for element values. - */ - value_comp(): (x: Pair, y: Pair) => boolean; - /** - * @inheritdoc - */ - is_equal_to(left: MapIterator, right: MapIterator): boolean; - /** - * @inheritdoc - */ - is_less(left: MapIterator, right: MapIterator): boolean; - } -} -declare namespace std.base { - /** - *

    A common interface for tree-structured set.

    - * - *

    {@link ITreeSet TreeMultiSets} are containers that store elements following a specific order.

    - * - *

    In a {@link ITreeSet}, the value of an element also identifies it (the value is itself - * the key, of type T). The value of the elements in a {@link ITreeSet} 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 ITreeSet TreeMultiSets} are always sorted following a strict - * weak ordering criterion indicated by its internal comparison method (of {@link IComparable.less less}).

    - * - *

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

    - * - *

    {@link ITreeSet TreeMultiSets} 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.
    - *
    - * - * @param Type of the elements. Each element in a {@link ITreeSet} container is also identified - * by this value (each value is itself also the element's key). - * - * @reference http://www.cplusplus.com/reference/set - * @author Jeongho Nam - */ - interface ITreeSet { - /** - *

    Return comparison function.

    - * - *

    Returns a copy of the comparison function used by the container.

    - * - *

    By default, this is a {@link less} object, which returns the same as operator<.

    - * - *

    This object determines the order of the elements in the container: it is a function pointer or a function - * object that takes two arguments of the same type as the container elements, and returns true if - * the first argument is considered to go before the second in the strict weak ordering it - * defines, and false otherwise.

    - * - *

    Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false - * reflexively (i.e., no matter the order in which the elements are passed as arguments).

    - * - *

    In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, - * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

    - * - * @return The comparison function. - */ - key_comp(): (x: T, y: T) => boolean; - /** - *

    Return comparison function.

    - * - *

    Returns a copy of the comparison function used by the container.

    - * - *

    By default, this is a {@link less} object, which returns the same as operator<.

    - * - *

    This object determines the order of the elements in the container: it is a function pointer or a function - * object that takes two arguments of the same type as the container elements, and returns true if - * the first argument is considered to go before the second in the strict weak ordering it - * defines, and false otherwise.

    - * - *

    Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false - * reflexively (i.e., no matter the order in which the elements are passed as arguments).

    - * - *

    In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, - * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

    - * - * @return The comparison function. - */ - value_comp(): (x: T, y: T) => boolean; - /** - *

    Return iterator to lower bound.

    - * - *

    Returns an iterator pointing to the first element in the container which is not considered to - * go before val (i.e., either it is equivalent or goes after).

    - * - *

    The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(element,val) would return false.

    - * - *

    If the {@link ITreeSet} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element that is not less than val.

    - - *

    A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except - * in the case that the {@link ITreeSet} contains elements equivalent to val: In this case - * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas - * {@link upper_bound} returns an iterator pointing to the element following the last.

    - * - * @param val Value to compare. - * - * @return An iterator to the the first element in the container which is not considered to go before - * val, or {@link ITreeSet.end} if all elements are considered to go before val. - */ - lower_bound(val: T): SetIterator; - /** - *

    Return iterator to upper bound.

    - * - *

    Returns an iterator pointing to the first element in the container which is considered to go after - * val.

    - - *

    The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(val,element) would return true.

    - - *

    If the {@code ITreeSet} class is instantiated with the default comparison type (less), the - * function returns an iterator to the first element that is greater than val.

    - * - *

    A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except - * in the case that the {@ITreeSet} contains elements equivalent to val: In this case - * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas - * {@link upper_bound} returns an iterator pointing to the element following the last.

    - * - * @param val Value to compare. - * - * @return An iterator to the the first element in the container which is considered to go after - * val, or {@link TreeSet.end end} if no elements are considered to go after val. - */ - upper_bound(val: T): SetIterator; - /** - *

    Get range of equal elements.

    - * - *

    Returns the bounds of a range that includes all the elements in the container that are equivalent - * to val.

    - * - *

    If no matches are found, the range returned has a length of zero, with both iterators pointing to - * the first element that is considered to go after val according to the container's - * internal comparison object (key_comp).

    - * - *

    Two elements of a multiset are considered equivalent if the container's comparison object returns - * false reflexively (i.e., no matter the order in which the elements are passed as arguments).

    - * - * @param key Value to search for. - * - * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of - * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound - * (the same as {@link upper_bound}). - */ - equal_range(val: T): Pair, SetIterator>; - } -} -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. - */ - constructor(set: TreeSet | TreeMultiSet, compare?: (x: T, y: T) => boolean); - find(val: T): XTreeNode>; - find(it: SetIterator): XTreeNode>; - /** - * @hidden - */ - private find_by_val(val); - /** - *

    Return iterator to lower bound.

    - * - *

    Returns an iterator pointing to the first element in the container which is not considered to - * go before val (i.e., either it is equivalent or goes after).

    - * - *

    The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(element,val) would return false.

    - * - *

    If the {@link ITreeSet} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element that is not less than val.

    - - *

    A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except - * in the case that the {@link ITreeSet} contains elements equivalent to val: In this case - * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas - * {@link upper_bound} returns an iterator pointing to the element following the last.

    - * - * @param val Value to compare. - * - * @return An iterator to the the first element in the container which is not considered to go before - * val, or {@link ITreeSet.end} if all elements are considered to go before val. - */ - lower_bound(val: T): SetIterator; - /** - *

    Return iterator to upper bound.

    - * - *

    Returns an iterator pointing to the first element in the container which is considered to go after - * val.

    - - *

    The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(val,element) would return true.

    - - *

    If the {@code ITreeSet} class is instantiated with the default comparison type (less), the - * function returns an iterator to the first element that is greater than val.

    - * - *

    A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except - * in the case that the {@ITreeSet} contains elements equivalent to val: In this case - * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas - * {@link upper_bound} returns an iterator pointing to the element following the last.

    - * - * @param val Value to compare. - * - * @return An iterator to the the first element in the container which is considered to go after - * val, or {@link TreeSet.end end} if no elements are considered to go after val. - */ - upper_bound(val: T): SetIterator; - /** - *

    Get range of equal elements.

    - * - *

    Returns the bounds of a range that includes all the elements in the container that are equivalent - * to val.

    - * - *

    If no matches are found, the range returned has a length of zero, with both iterators pointing to - * the first element that is considered to go after val according to the container's - * internal comparison object (key_comp).

    - * - *

    Two elements of a multiset are considered equivalent if the container's comparison object returns - * false reflexively (i.e., no matter the order in which the elements are passed as arguments).

    - * - * @param key Value to search for. - * - * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of - * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound - * (the same as {@link upper_bound}). - */ - equal_range(val: T): Pair, SetIterator>; - /** - *

    Return comparison function.

    - * - *

    Returns a copy of the comparison function used by the container.

    - * - *

    By default, this is a {@link less} object, which returns the same as operator<.

    - * - *

    This object determines the order of the elements in the container: it is a function pointer or a function - * object that takes two arguments of the same type as the container elements, and returns true if - * the first argument is considered to go before the second in the strict weak ordering it - * defines, and false otherwise.

    - * - *

    Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false - * reflexively (i.e., no matter the order in which the elements are passed as arguments).

    - * - *

    In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, - * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

    - * - * @return The comparison function. - */ - key_comp(): (x: T, y: T) => boolean; - /** - *

    Return comparison function.

    - * - *

    Returns a copy of the comparison function used by the container.

    - * - *

    By default, this is a {@link less} object, which returns the same as operator<.

    - * - *

    This object determines the order of the elements in the container: it is a function pointer or a function - * object that takes two arguments of the same type as the container elements, and returns true if - * the first argument is considered to go before the second in the strict weak ordering it - * defines, and false otherwise.

    - * - *

    Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false - * reflexively (i.e., no matter the order in which the elements are passed as arguments).

    - * - *

    In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, - * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

    - * - * @return The comparison function. - */ - value_comp(): (x: T, y: T) => boolean; - /** - * @inheritdoc - */ - is_equal_to(left: SetIterator, right: SetIterator): boolean; - /** - * @inheritdoc - */ - is_less(left: SetIterator, right: SetIterator): boolean; - } -} -declare namespace std.base { - /** - *

    An abstract unique-map.

    - * - *

    {@link UniqueMap UniqueMaps} are associative containers that store elements formed by a combination of a - * key value (Key) and a mapped value (T), and which allows for fast retrieval of - * individual elements based on their keys.

    - * - *

    In a {@link MapContainer}, the key values are generally used to uniquely identify the elements, - * while the mapped values store the content associated to this key. The types of key and - * mapped value may differ, and are grouped together in member type value_type, which is a - * {@link Pair} type combining both:

    - * - *

    typedef pair value_type;

    - * - *

    {@link UniqueMap} 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. - *
    - * - *
    Map
    - *
    - * Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value. - *
    - * - *
    Unique keys
    - *
    No two elements in the container can have equivalent keys.
    - *
    - * - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @author Jeongho Nam - */ - abstract class UniqueMap extends MapContainer { - /** - * @inheritdoc - */ - count(key: Key): number; - /** - *

    Get an element

    - * - *

    Returns a reference to the mapped value of the element identified with key.

    - * - * @param key Key value of the element whose mapped value is accessed. - * - * @throw exception out of range - * - * @return A reference object of the mapped value (_Ty) - */ - get(key: Key): T; - /** - *

    Set an item as the specified identifier.

    - * - *

    If the identifier is already in map, change value of the identifier. If not, then insert the object - * with the identifier.

    - * - * @param key Key value of the element whose mapped value is accessed. - * @param val Value, the item. - */ - set(key: Key, val: T): void; - /** - * Construct and insert element. - * - * Inserts a new element in the {@link UniqueMap} if its *key* is unique. This new element is constructed in - * place using args as the arguments for the construction of a *value_type* (which is an object of a - * {@link Pair} type). - * - * The insertion only takes place if no other element in the container has a *key equivalent* to the one - * being emplaced (*keys* in a {@link UniqueMap} container are unique). - * - * If inserted, this effectively increases the container {@link size} by one. - * - * A similar member function exists, {@link insert}, which either copies or moves existing objects into the - * container. - * - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return If the function successfully inserts the element (because no equivalent element existed already in - * the {@link UniqueMap}), the function returns a {@link Pair} of an {@link MapIterator iterator} to - * the newly inserted element and a value of true. Otherwise, it returns an - * {@link MapIterator iterator} to the equivalent element within the container and a value of false. - */ - emplace(key: Key, value: T): Pair, boolean>; - /** - * Construct and insert element. - * - * Inserts a new element in the {@link UniqueMap} if its *key* is unique. This new element is constructed in - * place using args as the arguments for the construction of a *value_type* (which is an object of a - * {@link Pair} type). - * - * The insertion only takes place if no other element in the container has a *key equivalent* to the one - * being emplaced (*keys* in a {@link UniqueMap} container are unique). - * - * If inserted, this effectively increases the container {@link size} by one. - * - * A similar member function exists, {@link insert}, which either copies or moves existing objects into the - * container. - * - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return If the function successfully inserts the element (because no equivalent element existed already in - * the {@link UniqueMap}), the function returns a {@link Pair} of an {@link MapIterator iterator} to - * the newly inserted element and a value of true. Otherwise, it returns an - * {@link MapIterator iterator} to the equivalent element within the container and a value of false. - */ - emplace(pair: Pair): Pair, boolean>; - /** - *

    Insert an element.

    - * - *

    Extends the container by inserting new elements, effectively increasing the container {@link size} by - * one.

    - * - *

    Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether - * each inserted element has a key equivalent to the one of 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 MultiMap}.

    - * - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly - * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The - * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or - * false if an equivalent key already existed. - */ - insert(pair: Pair): Pair, boolean>; - /** - *

    Insert an element.

    - * - *

    Extends the container by inserting a new element, effectively increasing the container size by the - * number of elements inserted.

    - * - *

    Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether - * each inserted element has a key equivalent to the one of 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 MultiMap}.

    - * - * @param tuple Tuple represensts the {@link Pair} 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 element with an equivalent key in the {@link UniqueMap}. The - * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or - * false if an equivalent key already existed. - */ - insert(tuple: [L, U]): Pair, boolean>; - /** - * @inheritdoc - */ - insert(hint: MapIterator, pair: Pair): MapIterator; - /** - * @inheritdoc - */ - insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; - /** - * @inheritdoc - */ - insert(hint: MapIterator, tuple: [L, U]): MapIterator; - /** - * @inheritdoc - */ - insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; - /** - * @inheritdoc - */ - insert>>(first: InputIterator, last: InputIterator): void; - /** - *

    Insert or assign an element.

    - * - *

    Inserts an element or assigns to the current element if the key already exists.

    - * - *

    Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether - * each inserted element has a key equivalent to the one of an element already in the container, and - * if so, the element is assigned, returning an iterator to this existing element (if the function returns a - * value).

    - * - *

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

    - * - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly - * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The - * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or - * false if an equivalent key already existed so the value is assigned. - */ - insert_or_assign(key: Key, value: T): Pair, boolean>; - /** - *

    Insert or assign an element.

    - * - *

    Inserts an element or assigns to the current element if the key already exists.

    - * - *

    Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether - * each inserted element has a key equivalent to the one of an element already in the container, and - * if so, the element is assigned, returning an iterator to this existing element (if the function returns a - * value).

    - * - *

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

    - * - * @param hint Hint for the position where the element can be inserted. - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link UniqueMap}. - */ - insert_or_assign(hint: MapIterator, key: Key, value: T): MapIterator; - /** - *

    Insert or assign an element.

    - * - *

    Inserts an element or assigns to the current element if the key already exists.

    - * - *

    Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether - * each inserted element has a key equivalent to the one of an element already in the container, and - * if so, the element is assigned, returning an iterator to this existing element (if the function returns a - * value).

    - * - *

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

    - * - * @param hint Hint for the position where the element can be inserted. - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link UniqueMap}. - */ - insert_or_assign(hint: MapReverseIterator, key: Key, value: T): MapReverseIterator; - /** - * @hidden - */ - private insert_or_assign_with_key_value(key, value); - /** - * @hidden - */ - private insert_or_assign_with_hint(hint, key, value); - /** - *

    Extract an element.

    - * - *

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

    - * - * @param key Key value of the element whose mapped value is accessed. - * - * @return A {@link Pair} containing the value pointed to by key. - */ - extract(key: Key): Pair; - /** - *

    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: MapIterator): MapIterator; - /** - *

    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: MapReverseIterator): MapReverseIterator; - /** - * @hidden - */ - private extract_by_key(key); - /** - * @hidden - */ - private extract_by_iterator(it); - /** - * @hidden - */ - private extract_by_reverse_iterator(it); - /** - * Merge two maps. - * - * Attempts to extract each element in *source* and insert it into this container. If there's an element in this - * container with key equivalent to the key of an element from *source*, tnen that element is not extracted from - * the *source*. Otherwise, no element with same key exists in this container, then that element will be - * transfered from the *source* to this container. - * - * @param source A {@link MapContainer map container} to transfer the elements from. - */ - merge(source: MapContainer): void; - } -} -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; - /** - *

    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; - /** - *

    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); - /** - * Merge two sets. - * - * Attempts to extract each element in *source* and insert it into this container. If there's an element in this - * container with key equivalent to the key of an element from *source*, tnen that element is not extracted from - * the *source*. Otherwise, no element with same key exists in this container, then that element will be - * transfered from the *source* to this container. - * - * @param source A {@link SetContainer set container} to transfer the elements from. - */ - merge(source: SetContainer): void; - } -} -declare namespace std.base { - /** - *

    A node in an XTree.

    - * - * @param Type of elements. - * - * @inventor Rudolf Bayer - * @author Migrated by Jeongho Nam - */ - class XTreeNode { - /** - * Parent of the node. - */ - parent: XTreeNode; - /** - * Left child in the node. - */ - left: XTreeNode; - /** - * Right child in the node. - */ - right: XTreeNode; - /** - * Value stored in the node. - */ - value: T; - /** - * Color of the node. - */ - color: Color; - /** - * Construct from value and color of node. - * - * @param value Value to be stored in. - * @param color Color of the node, red or black. - */ - constructor(value: T, color: Color); - /** - * Get grand-parent. - */ - readonly grand_parent: XTreeNode; - /** - * Get sibling, opposite side node in same parent. - */ - readonly sibling: XTreeNode; - /** - * Get uncle, parent's sibling. - */ - readonly uncle: XTreeNode; - } -} -declare namespace std.Deque { - type iterator = std.DequeIterator; - type reverse_iterator = std.DequeReverseIterator; -} -declare namespace std { - /** - *

    Double ended queue.

    - * - *

    {@link Deque} (usually pronounced like "deck") is an irregular acronym of - * double-ended queue. Double-ended queues are sequence containers with dynamic sizes that can be - * expanded or contracted on both ends (either its front or its back).

    - * - *

    Specific libraries may implement deques in different ways, generally as some form of dynamic array. But in any - * case, they allow for the individual elements to be accessed directly through random access iterators, with storage - * handled automatically by expanding and contracting the container as needed.

    - * - *

    Therefore, they provide a functionality similar to vectors, but with efficient insertion and deletion of - * elements also at the beginning of the sequence, and not only at its end. But, unlike {@link Vector Vectors}, - * {@link Deque Deques} are not guaranteed to store all its elements in contiguous storage locations: accessing - * elements in a deque by offsetting a pointer to another element causes undefined behavior.

    - * - *

    Both {@link Vector}s and {@link Deque}s provide a very similar interface and can be used for similar purposes, - * but internally both work in quite different ways: While {@link Vector}s use a single array that needs to be - * occasionally reallocated for growth, the elements of a {@link Deque} can be scattered in different chunks of - * storage, with the container keeping the necessary information internally to provide direct access to any of its - * elements in constant time and with a uniform sequential interface (through iterators). Therefore, - * {@link Deque Deques} are a little more complex internally than {@link Vector}s, but this allows them to grow more - * efficiently under certain circumstances, especially with very long sequences, where reallocations become more - * expensive.

    - * - *

    For operations that involve frequent insertion or removals of elements at positions other than the beginning or - * the end, {@link Deque Deques} perform worse and have less consistent iterators and references than - * {@link List Lists}.

    - * - *

    - * - *

    - * - *

    Container properties

    - *
    - *
    Sequence
    - *
    Elements in sequence containers are ordered in a strict linear sequence. Individual elements - * are accessed by their position in this sequence.
    - * - *
    Dynamic array
    - *
    Generally implemented as a dynamic array, it allows direct access to any element in the - * sequence and provides relatively fast addition/removal of elements at the beginning or the end - * of the sequence.
    - *
    - * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/deque/deque/ - * @author Jeongho Nam - */ - class Deque extends base.Container implements base.IArrayContainer, base.IDequeContainer { - /** - * @hidden - */ - private static readonly ROW; - /** - * @hidden - */ - private static readonly MIN_CAPACITY; - /** - * @hidden - */ - private matrix_; - /** - * @hidden - */ - private size_; - /** - * @hidden - */ - private capacity_; - /** - * @hidden - */ - private get_col_size(); - /** - * @hidden - */ - private end_; - /** - * @hidden - */ - private rend_; - /** - *

    Default Constructor.

    - * - *

    Constructs an empty container, with no elements.

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

    Initializer list Constructor.

    - * - *

    Constructs a container with a copy of each of the elements in array, in the same order.

    - * - * @param array An array containing elements to be copied and contained. - */ - constructor(items: Array); - /** - *

    Fill Constructor.

    - * - *

    Constructs a container with n elements. Each element is a copy of val (if provided).

    - * - * @param n Initial container size (i.e., the number of elements in the container at construction). - * @param val Value to fill the container with. Each of the n elements in the container is - * initialized to a copy of this value. - */ - constructor(size: number, val: T); - /** - *

    Copy Constructor.

    - * - *

    Constructs a container with a copy of each of the elements in container, in the same order.

    - * - * @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: Deque); - /** - *

    Range Constructor.

    - * - *

    Constructs a container with as many elements as the range (begin, end), with each - * element emplace-constructed from its corresponding element in that range, in the same order.

    - * - * @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); - /** - * @inheritdoc - */ - assign>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - assign(n: number, val: T): void; - /** - * @inheritdoc - */ - reserve(capacity: number): void; - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - begin(): DequeIterator; - /** - * @inheritdoc - */ - end(): DequeIterator; - /** - * @inheritdoc - */ - rbegin(): DequeReverseIterator; - /** - * @inheritdoc - */ - rend(): DequeReverseIterator; - /** - * @inheritdoc - */ - size(): number; - /** - * @inheritdoc - */ - empty(): boolean; - /** - * @inheritdoc - */ - capacity(): number; - /** - * @inheritdoc - */ - at(index: number): T; - /** - * @inheritdoc - */ - set(index: number, val: T): void; - /** - * @inheritdoc - */ - front(): T; - /** - * @inheritdoc - */ - back(): T; - /** - // Fetch row and column's index. - /** - * @hidden - */ - private fetch_index(index); - /** - * @inheritdoc - */ - push(...items: T[]): number; - /** - * @inheritdoc - */ - push_front(val: T): void; - /** - * @inheritdoc - */ - push_back(val: T): void; - /** - * @inheritdoc - */ - pop_front(): void; - /** - * @inheritdoc - */ - pop_back(): void; - /** - * @inheritdoc - */ - insert(position: DequeIterator, val: T): DequeIterator; - /** - * @inheritdoc - */ - insert(position: DequeIterator, n: number, val: T): DequeIterator; - /** - * @inheritdoc - */ - insert>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; - /** - * @inheritdoc - */ - insert(position: DequeReverseIterator, val: T): DequeReverseIterator; - /** - * @inheritdoc - */ - insert(position: DequeReverseIterator, n: number, val: T): DequeReverseIterator; - /** - * @inheritdoc - */ - insert>(position: DequeReverseIterator, begin: InputIterator, end: InputIterator): DequeReverseIterator; - /** - * @hidden - */ - private insert_by_val(position, val); - /** - * @hidden - */ - protected _Insert_by_repeating_val(position: DequeIterator, n: number, val: T): DequeIterator; - /** - * @hidden - */ - protected _Insert_by_range>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; - /** - * @hidden - */ - private insert_by_items(position, items); - /** - * @inheritdoc - */ - erase(position: DequeIterator): DequeIterator; - /** - * @inheritdoc - */ - erase(first: DequeIterator, last: DequeIterator): DequeIterator; - /** - * @inheritdoc - */ - erase(position: DequeReverseIterator): DequeReverseIterator; - /** - * @inheritdoc - */ - erase(first: DequeReverseIterator, last: DequeReverseIterator): DequeReverseIterator; - /** - * @hidden - */ - 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; - } -} -declare namespace std { - /** - *

    An iterator of {@link Deque}.

    - * - *

    - * - *

    - * - * @author Jeongho Nam - */ - class DequeIterator extends Iterator implements base.IArrayIterator { - /** - * Sequence number of iterator in the source {@link Deque}. - */ - private index_; - /** - *

    Construct from the source {@link Deque container}.

    - * - *

    Note

    - *

    Do not create the iterator directly, by yourself.

    - *

    Use {@link Deque.begin begin()}, {@link Deque.end end()} in {@link Deque container} instead.

    - * - * @param source The source {@link Deque container} to reference. - * @param index Sequence number of the element in the source {@link Deque}. - */ - constructor(source: Deque, index: number); - /** - * @hidden - */ - private readonly deque; - /** - * @inheritdoc - */ - /** - * Set value of the iterator is pointing to. - * - * @param val Value to set. - */ - value: T; - /** - * @inheritdoc - */ - readonly index: number; - /** - * @inheritdoc - */ - prev(): DequeIterator; - /** - * @inheritdoc - */ - next(): DequeIterator; - /** - * @inheritdoc - */ - advance(n: number): DequeIterator; - /** - * @inheritdoc - */ - equals(obj: DequeIterator): boolean; - /** - * @inheritdoc - */ - swap(obj: DequeIterator): void; - } -} -declare namespace std { - /** - *

    A reverse-iterator of Deque.

    - * - *

    - * - *

    - * - * @param Type of the elements. - * - * @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); - /** - * @hidden - */ - protected _Create_neighbor(base: DequeIterator): DequeReverseIterator; - /** - * @inheritdoc - */ - /** - * Set value of the iterator is pointing to. - * - * @param val Value to set. - */ - value: T; - /** - * Get index. - */ - readonly index: number; - } -} -declare namespace std { - /** - *

    Function handling termination on exception

    - * - *

    Calls the current terminate handler.

    - * - *

    By default, the terminate handler calls abort. But this behavior can be redefined by calling - * {@link set_terminate}.

    - * - *

    This function is automatically called when no catch handler can be found for a thrown exception, - * or for some other exceptional circumstance that makes impossible to continue the exception handling process.

    - * - *

    This function is provided so that the terminate handler can be explicitly called by a program that needs to - * abnormally terminate, and works even if {@link set_terminate} has not been used to set a custom terminate handler - * (calling abort in this case).

    - */ - function terminate(): void; - /** - *

    Set terminate handler function.

    - * - *

    A terminate handler function is a function automatically called when the exception handling process has - * to be abandoned for some reason. This happens when no catch handler can be found for a thrown exception, or for - * some other exceptional circumstance that makes impossible to continue the exception handling process.

    - * - *

    Before this function is called by the program for the first time, the default behavior is to call abort.

    - * - *

    A program may explicitly call the current terminate handler function by calling {@link terminate}.

    - * - * @param f Function that takes no parameters and returns no value (void). - */ - function set_terminate(f: () => void): void; - /** - *

    Get terminate handler function.

    - * - *

    The terminate handler function is automatically called when no catch handler can be found - * for a thrown exception, or for some other exceptional circumstance that makes impossible to continue the exception - * handling process.

    - * - *

    If no such function has been set by a previous call to {@link set_terminate}, the function returns a - * null-pointer.

    - * - * @return If {@link set_terminate} has previously been called by the program, the function returns the current - * terminate handler function. Otherwise, it returns a null-pointer. - */ - function get_terminate(): () => void; - /** - *

    Standard exception class.

    - * - *

    Base class for standard exceptions.

    - * - *

    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 - */ - class Exception extends Error { - /** - * A message representing specification about the Exception. - */ - private description; - /** - * Default Constructor. - */ - constructor(); - /** - *

    Construct from a message.

    - * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - /** - *

    Get string identifying exception.

    - *

    Returns a string that may be used to identify the exception.

    - * - *

    The particular representation pointed by the returned value is implementation-defined. - * As a virtual function, derived classes may redefine this function so that specify value are - * returned.

    - */ - what(): string; - /** - * @inheritdoc - */ - readonly message: string; - /** - * @inheritdoc - */ - readonly name: string; - } - /** - *

    Logic error exception.

    - * - *

    This class defines the type of objects thrown as exceptions to report errors in the internal - * logical of the program, such as violation of logical preconditions or class invariants.

    - * - *

    These errors are presumably detectable before the program executes.

    - * - *

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

    - * - *

    - *

    - * - * @reference http://www.cplusplus.com/reference/stdexcept/logic_error - * @author Jeongho Nam - */ - class LogicError extends Exception { - /** - *

    Construct from a message.

    - * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } - /** - *

    Domain error exception.

    - * - *

    This class defines the type of objects thrown as exceptions to report domain errors.

    - * - *

    Generally, the domain of a mathematical function is the subset of values that it is defined for. - * For example, the square root function is only defined for non-negative numbers. Thus, a negative number - * for such a function would qualify as a domain error.

    - * - *

    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 - */ - class DomainError extends LogicError { - /** - *

    Construct from a message.

    - * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } - /** - *

    Invalid argument exception.

    - * - *

    This class defines the type of objects thrown as exceptions to report an invalid argument.

    - * - *

    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 - */ - class InvalidArgument extends LogicError { - /** - *

    Construct from a message.

    - * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } - /** - *

    Length error exception.

    - * - *

    This class defines the type of objects thrown as exceptions to report a length error.

    - * - *

    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 - */ - class LengthError extends LogicError { - /** - *

    Construct from a message.

    - * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } - /** - *

    Out-of-range exception.

    - * - *

    This class defines the type of objects thrown as exceptions to report an out-of-range error.

    - * - *

    It is a standard exception that can be thrown by programs. Some components of the standard library, - * 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 - */ - class OutOfRange extends LogicError { - /** - *

    Construct from a message.

    - * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } - /** - *

    Runtime error exception.

    - * - *

    This class defines the type of objects thrown as exceptions to report errors that can only be - * detected during runtime.

    - * - *

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

    - * - *

    - *

    - * - * @reference http://www.cplusplus.com/reference/stdexcept/runtime_error - * @author Jeongho Nam - */ - class RuntimeError extends Exception { - /** - *

    Construct from a message.

    - * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } - /** - *

    Overflow error exception.

    - * - *

    This class defines the type of objects thrown as exceptions to arithmetic overflow errors.

    - * - *

    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 - */ - class OverflowError extends RuntimeError { - /** - *

    Construct from a message.

    - * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } - /** - *

    Underflow error exception.

    - * - *

    This class defines the type of objects thrown as exceptions to arithmetic underflow errors.

    - * - *

    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 - */ - class UnderflowError extends RuntimeError { - /** - *

    Construct from a message.

    - * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } - /** - *

    Range error exception.

    - * - *

    This class defines the type of objects thrown as exceptions to report range errors in internal - * computations.

    - * - *

    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 - */ - class RangeError extends RuntimeError { - /** - *

    Construct from a message.

    - * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } -} -declare namespace std { - /** - *

    Function object class for equality comparison.

    - * - *

    Binary function object class whose call returns whether its two arguments compare equal (as returned by - * operator ==).

    - * - *

    Generically, function objects are instances of a class with member function {@link IComparable.equal_to equal_to} - * defined. This member function allows the object to be used with the same syntax as a function call.

    - * - * @param x First element to compare. - * @param y Second element to compare. - * - * @return Whether the arguments are equal. - */ - function equal_to(x: T, y: T): boolean; - /** - *

    Function object class for non-equality comparison.

    - * - *

    Binary function object class whose call returns whether its two arguments compare not equal (as returned - * by operator operator!=).

    - * - *

    Generically, function objects are instances of a class with member function {@link IComparable.equal_to equal_to} - * defined. This member function allows the object to be used with the same syntax as a function call.

    - * - * @param x First element to compare. - * @param y Second element to compare. - * - * @return Whether the arguments are not equal. - */ - function not_equal_to(x: T, y: T): boolean; - /** - *

    Function for less-than inequality comparison.

    - * - *

    Binary function returns whether the its first argument compares less than the second.

    - * - *

    Generically, function objects are instances of a class with member function {@link IComparable.less less} - * defined. If an object doesn't have the method, then its own uid will be used to compare insteadly. - * This member function allows the object to be used with the same syntax as a function call.

    - * - *

    Objects of this class can be used on standard algorithms such as {@link sort sort()}, - * {@link merge merge()} or {@link TreeMap.lower_bound lower_bound()}.

    - * - * @param Type of arguments to compare by the function call. The type shall supporrt the operation - * operator<() or method {@link IComparable.less less}. - * - * @param x First element, the standard of comparison. - * @param y Second element compare with the first. - * - * @return Whether the first parameter is less than the second. - */ - function less(x: T, y: T): boolean; - /** - *

    Function object class for less-than-or-equal-to comparison.

    - * - *

    Binary function object class whose call returns whether the its first argument compares {@link less less than} or - * {@link equal_to equal to} the second (as returned by operator <=).

    - * - *

    Generically, function objects are instances of a class with member function {@link IComparable.less less} - * and {@link IComparable.equal_to equal_to} defined. This member function allows the object to be used with the same - * syntax as a function call.

    - * - * @param x First element, the standard of comparison. - * @param y Second element compare with the first. - * - * @return Whether the x is {@link less less than} or {@link equal_to equal to} the y. - */ - function less_equal(x: T, y: T): boolean; - /** - *

    Function for greater-than inequality comparison.

    - * - *

    Binary function returns whether the its first argument compares greater than the second.

    - * - *

    Generically, function objects are instances of a class with member function {@link less} and - * {@link equal_to equal_to()} defined. If an object doesn't have those methods, then its own uid will be used - * to compare insteadly. This member function allows the object to be used with the same syntax as a function - * call.

    - * - *

    Objects of this class can be used on standard algorithms such as {@link sort sort()}, - * {@link merge merge()} or {@link TreeMap.lower_bound lower_bound()}.

    - * - * @param Type of arguments to compare by the function call. The type shall supporrt the operation - * operator>() or method {@link IComparable.greater greater}. - * - * @return Whether the x is greater than the y. - */ - function greater(x: T, y: T): boolean; - /** - *

    Function object class for greater-than-or-equal-to comparison.

    - * - *

    Binary function object class whose call returns whether the its first argument compares - * {@link greater greater than} or {@link equal_to equal to} the second (as returned by operator >=).

    - * - *

    Generically, function objects are instances of a class with member function {@link IComparable.less less} - * defined. If an object doesn't have the method, then its own uid will be used to compare insteadly. - * This member function allows the object to be used with the same syntax as a function call.

    - * - * @param x First element, the standard of comparison. - * @param y Second element compare with the first. - * - * @return Whether the x is {@link greater greater than} or {@link equal_to equal to} the y. - */ - function greater_equal(x: T, y: T): boolean; - /** - *

    Logical AND function object class.

    - * - *

    Binary function object class whose call returns the result of the logical "and" operation between its two - * arguments (as returned by operator &&).

    - * - *

    Generically, function objects are instances of a class with member function operator() defined. This member - * function allows the object to be used with the same syntax as a function call.

    - * - * @param x First element. - * @param y Second element. - * - * @return Result of logical AND operation. - */ - function logical_and(x: T, y: T): boolean; - /** - *

    Logical OR function object class.

    - * - *

    Binary function object class whose call returns the result of the logical "or" operation between its two - * arguments (as returned by operator ||).

    - * - *

    Generically, function objects are instances of a class with member function operator() defined. This member - * function allows the object to be used with the same syntax as a function call.

    - * - * @param x First element. - * @param y Second element. - * - * @return Result of logical OR operation. - */ - function logical_or(x: T, y: T): boolean; - /** - *

    Logical NOT function object class.

    - * - *

    Unary function object class whose call returns the result of the logical "not" operation on its argument - * (as returned by operator !).

    - * - *

    Generically, function objects are instances of a class with member function operator() defined. This member - * function allows the object to be used with the same syntax as a function call.

    - * - * @param x Target element. - * - * @return Result of logical NOT operation. - */ - function logical_not(x: T): boolean; - /** - *

    Bitwise AND function object class.

    - * - *

    Binary function object class whose call returns the result of applying the bitwise "and" operation between - * its two arguments (as returned by operator &).

    - * - * @param x First element. - * @param y Second element. - * - * @return Result of bitwise AND operation. - */ - function bit_and(x: number, y: number): number; - /** - *

    Bitwise OR function object class.

    - * - *

    Binary function object class whose call returns the result of applying the bitwise "and" operation between - * its two arguments (as returned by operator &).

    - * - * @param x First element. - * @param y Second element. - * - * @return Result of bitwise OR operation. - */ - function bit_or(x: number, y: number): number; - /** - *

    Bitwise XOR function object class.

    - * - *

    Binary function object class whose call returns the result of applying the bitwise "exclusive or" - * operation between its two arguments (as returned by operator ^).

    - * - * @param x First element. - * @param y Second element. - * - * @return Result of bitwise XOR operation. - */ - function bit_xor(x: number, y: number): number; - /** - *

    Default hash function for number.

    - * - *

    Unary function that defines the default hash function used by the standard library.

    - * - *

    The functional call returns a hash value of its argument: A hash value is a value that depends solely on - * its argument, returning always the same value for the same argument (for a given execution of a program). The - * value returned shall have a small likelihood of being the same as the one returned for a different argument. - *

    - * - * @param val Value to be hashed. - * - * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. - */ - function hash(val: number): number; - /** - *

    Default hash function for string.

    - * - *

    Unary function that defines the default hash function used by the standard library.

    - * - *

    The functional call returns a hash value of its argument: A hash value is a value that depends solely on - * its argument, returning always the same value for the same argument (for a given execution of a program). The - * value returned shall have a small likelihood of being the same as the one returned for a different argument. - *

    - * - * @param str A string to be hashed. - * - * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. - */ - function hash(str: string): number; - /** - *

    Default hash function for Object.

    - * - *

    Unary function that defines the default hash function used by the standard library.

    - * - *

    The functional call returns a hash value of its argument: A hash value is a value that depends solely on - * its argument, returning always the same value for the same argument (for a given execution of a program). The - * value returned shall have a small likelihood of being the same as the one returned for a different argument. - *

    - * - *

    The default {@link hash} function of Object returns a value returned from {@link hash hash(number)} with - * an unique id of each Object. If you want to specify {@link hash} function of a specific class, then - * define a member function public hash(): number in the class.

    - * - * @param obj Object to be hashed. - * - * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. - */ - function hash(obj: Object): number; - /** - *

    Exchange contents of {@link IContainers containers}.

    - * - *

    The contents of container left are exchanged with those of right. Both container objects must have - * same type of elements (same template parameters), although sizes may differ.

    - * - *

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

    - * - *

    This is an overload of the generic algorithm swap that improves its performance by mutually transferring - * ownership over their assets to the other container (i.e., the containers exchange references to their data, without - * actually performing any element copy or movement): It behaves as if left. - * {@link IContainer.swap swap}(right) was called.

    - * - * @param left A {@link IContainer container} to swap its contents. - * @param right A {@link IContainer container} to swap its contents. - */ - function swap(left: base.IContainer, right: base.IContainer): void; - /** - *

    Exchange contents of queues.

    - * - *

    Exchanges the contents of left and right.

    - * - * @param left A {@link Queue} container of the same type. Size may differ. - * @param right A {@link Queue} container of the same type. Size may differ. - */ - function swap(left: Queue, right: Queue): void; - /** - *

    Exchange contents of {@link PriorityQueue PriorityQueues}.

    - * - *

    Exchanges the contents of left and right.

    - * - * @param left A {@link PriorityQueue} container of the same type. Size may differ. - * @param right A {@link PriorityQueue} container of the same type. Size may differ. - */ - function swap(left: PriorityQueue, right: PriorityQueue): void; - /** - *

    Exchange contents of {@link Stack Stacks}.

    - * - *

    Exchanges the contents of left and right.

    - * - * @param left A {@link Stack} container of the same type. Size may differ. - * @param right A {@link Stack} container of the same type. Size may differ. - */ - function swap(left: Stack, right: Stack): void; - /** - *

    Exchanges the contents of two {@link UniqueMap unique maps}.

    - * - *

    The contents of container left are exchanged with those of right. Both container objects must - * be of the same type (same template parameters), although sizes may differ.

    - * - *

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

    - * - *

    This is an overload of the generic algorithm swap that improves its performance by mutually transferring - * ownership over their assets to the other container (i.e., the containers exchange references to their data, - * without actually performing any element copy or movement): It behaves as if - * left.{@link UniqueMap.swap swap}(right) was called.

    - * - * @param left An {@link UniqueMap unique map} to swap its conents. - * @param right An {@link UniqueMap unique map} to swap its conents. - */ - function swap(left: base.UniqueMap, right: base.UniqueMap): void; - /** - *

    Exchanges the contents of two {@link MultiMap multi maps}.

    - * - *

    The contents of container left are exchanged with those of right. Both container objects must - * be of the same type (same template parameters), although sizes may differ.

    - * - *

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

    - * - *

    This is an overload of the generic algorithm swap that improves its performance by mutually transferring - * ownership over their assets to the other container (i.e., the containers exchange references to their data, - * without actually performing any element copy or movement): It behaves as if - * left.{@link MultiMap.swap swap}(right) was called.

    - * - * @param left A {@link MultiMap multi map} to swap its conents. - * @param right A {@link MultiMap multi map} to swap its conents. - */ - function swap(left: base.MultiMap, right: base.MultiMap): void; -} -declare namespace std { - /** - *

    Bind function arguments.

    - * - *

    Returns a function object based on fn, but with its arguments bound to args.

    - * - *

    Each argument may either be bound to a value or be a {@link placeholders placeholder}:

    - *
      - *
    • If bound to a value, calling the returned function object will always use that value as argument.
    • - *
    • - * If a {@link placeholders placeholder}, calling the returned function object forwards an argument passed to the - * call (the one whose order number is specified by the placeholder). - *
    • - *
    - * - *

    Calling the returned object returns the same type as fn.

    - * - * @param fn A function object, pointer to function or pointer to member. - * @param args List of arguments to bind: either values, or {@link placeholders}. - * - * @return A function object that, when called, calls fn with its arguments bound to args. If fn is - * a pointer to member, the first argument expected by the returned function is an object of the class fn - * is a member. - */ - function bind(fn: (...args: any[]) => Ret, ...args: any[]): (...args: any[]) => Ret; - /** - *

    Bind function arguments.

    - * - *

    Returns a function object based on fn, but with its arguments bound to args.

    - * - *

    Each argument may either be bound to a value or be a {@link placeholders placeholder}:

    - *
      - *
    • If bound to a value, calling the returned function object will always use that value as argument.
    • - *
    • - * If a {@link placeholders placeholder}, calling the returned function object forwards an argument passed to the - * call (the one whose order number is specified by the placeholder). - *
    • - *
    - * - *

    Calling the returned object returns the same type as fn.

    - * - * @param fn A function object, pointer to function or pointer to member. - * @param thisArg This argument, owner object of the member method fn. - * @param args List of arguments to bind: either values, or {@link placeholders}. - * - * @return A function object that, when called, calls fn with its arguments bound to args. If fn is - * a pointer to member, the first argument expected by the returned function is an object of the class fn - * is a member. - */ - function bind(fn: (...args: any[]) => Ret, thisArg: T, ...args: any[]): (...args: any[]) => Ret; -} -/** - *

    Bind argument placeholders.

    - * - *
    - * - *

    When the function object returned by bind is called, an argument with placeholder {@link _1} is replaced by the - * first argument in the call, {@link _2} is replaced by the second argument in the call, and so on... For example:

    - * - * - * let vec: Vector = new Vector(); - * - * let bind = std.bind(Vector.insert, _1, vec.end(), _2, _3); - * bind.apply(vec, 5, 1); // vec.insert(vec.end(), 5, 1); - * // [1, 1, 1, 1, 1] - * - * - *

    When a call to {@link bind} is used as a subexpression in another call to bind, the {@link placeholders} - * are relative to the outermost {@link bind} expression.

    - * - * @reference http://www.cplusplus.com/reference/functional/placeholders/ - * @author Jeongho Nam - */ -declare namespace std.placeholders { - /** - * @hidden - */ - class PlaceHolder { - private index_; - constructor(index: number); - readonly index: number; - } - /** - * Replaced by the first argument in the function call. - */ - const _1: PlaceHolder; - /** - * Replaced by the second argument in the function call. - */ - const _2: PlaceHolder; - /** - * Replaced by the third argument in the function call. - */ - const _3: PlaceHolder; - const _4: PlaceHolder; - const _5: PlaceHolder; - const _6: PlaceHolder; - const _7: PlaceHolder; - const _8: PlaceHolder; - const _9: PlaceHolder; - const _10: PlaceHolder; - const _11: PlaceHolder; - const _12: PlaceHolder; - const _13: PlaceHolder; - const _14: PlaceHolder; - const _15: PlaceHolder; - const _16: PlaceHolder; - const _17: PlaceHolder; - const _18: PlaceHolder; - const _19: PlaceHolder; - const _20: PlaceHolder; -} -declare namespace std.HashMap { - type iterator = std.MapIterator; - type reverse_iterator = std.MapReverseIterator; -} -declare namespace std { - /** - *

    Hashed, unordered map.

    - * - *

    {@link HashMap}s are associative containers that store elements formed by the combination of a key value - * and a mapped value, and which allows for fast retrieval of individual elements based on their keys. - *

    - * - *

    In an {@link HashMap}, 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 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).

    - * - *

    {@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

    - *
    - *
    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.
    - * - *
    Map
    - *
    Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value.
    - * - *
    Unique keys
    - *
    No two elements in the container can have equivalent keys.
    - *
    - * - * @param Type of the key values. - * Each element in an {@link HashMap} is uniquely identified by its key value. - * @param Type of the mapped value. - * Each element in an {@link HashMap} is used to store some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/unordered_map/unordered_map - * @author Jeongho Nam - */ - class HashMap extends base.UniqueMap implements base.IHashMap { - /** - * @hidden - */ - private hash_buckets_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from elements. - */ - 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 - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: Key): MapIterator; - /** - * @inheritdoc - */ - begin(): MapIterator; - /** - * @inheritdoc - */ - begin(index: number): MapIterator; - /** - * @inheritdoc - */ - end(): MapIterator; - /** - * @inheritdoc - */ - end(index: number): MapIterator; - /** - * @inheritdoc - */ - rbegin(): MapReverseIterator; - /** - * @inheritdoc - */ - rbegin(index: number): MapReverseIterator; - /** - * @inheritdoc - */ - rend(): MapReverseIterator; - /** - * @inheritdoc - */ - rend(index: number): MapReverseIterator; - /** - * @inheritdoc - */ - bucket_count(): number; - /** - * @inheritdoc - */ - bucket_size(index: number): number; - /** - * @inheritdoc - */ - max_load_factor(): number; - /** - * @inheritdoc - */ - max_load_factor(z: number): void; - /** - * @inheritdoc - */ - bucket(key: Key): number; - /** - * @inheritdoc - */ - reserve(n: number): void; - /** - * @inheritdoc - */ - rehash(n: number): void; - /** - * @hidden - */ - protected _Insert_by_pair(pair: Pair): any; - /** - * @hidden - */ - protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; - /** - * @hidden - */ - protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected _Handle_insert(first: MapIterator, last: MapIterator): void; - /** - * @inheritdoc - */ - 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.IContainer>): void; - } -} -declare namespace std.HashMultiMap { - type iterator = std.MapIterator; - type reverse_iterator = std.MapReverseIterator; -} -declare namespace std { - /** - *

    Hashed, unordered Multimap.

    - * - *

    {@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 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 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).

    - * - *

    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

    - *
    - *
    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.
    - * - *
    Map
    - *
    Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value.
    - * - *
    Multiple equivalent keys
    - *
    The container can hold multiple elements with equivalent keys.
    - *
    - * - * @param Type of the key values. - * Each element in an {@link HashMultiMap} is identified by a key value. - * @param Type of the 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 - */ - class HashMultiMap extends base.MultiMap { - /** - * @hidden - */ - private hash_buckets_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from elements. - */ - 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 - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: Key): MapIterator; - /** - * @inheritdoc - */ - count(key: Key): number; - /** - * @inheritdoc - */ - begin(): MapIterator; - /** - * @inheritdoc - */ - begin(index: number): MapIterator; - /** - * @inheritdoc - */ - end(): MapIterator; - /** - * @inheritdoc - */ - end(index: number): MapIterator; - /** - * @inheritdoc - */ - rbegin(): MapReverseIterator; - /** - * @inheritdoc - */ - rbegin(index: number): MapReverseIterator; - /** - * @inheritdoc - */ - rend(): MapReverseIterator; - /** - * @inheritdoc - */ - rend(index: number): MapReverseIterator; - /** - * @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: Key): number; - /** - * @inheritdoc - */ - reserve(n: number): void; - /** - * @inheritdoc - */ - rehash(n: number): void; - /** - * @hidden - */ - protected _Insert_by_pair(pair: Pair): any; - /** - * @hidden - */ - protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; - /** - * @hidden - */ - protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected _Handle_insert(first: MapIterator, last: MapIterator): void; - /** - * @inheritdoc - */ - 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.IContainer>): void; - } -} -declare namespace std.HashMultiSet { - type iterator = std.SetIterator; - type reverse_iterator = std.SetReverseIterator; -} -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 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 - * identify it. Keys are immutable, therefore, the elements in an {@link HashMultiSet} cannot be - * modified once in the container - they can be inserted and removed, though.

    - * - *

    Internally, the elements in the {@link HashMultiSet} are not sorted in any particular, 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).

    - * - *

    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

    - *
    - *
    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.
    - * - *
    Multiple equivalent keys
    - *
    The container can hold multiple elements with equivalent keys.
    - *
    - * - * @param Type of the elements. - * Each element in an {@link UnorderedMultiSet} is also identified by this value.. - * - * @reference http://www.cplusplus.com/reference/unordered_set/unordered_multiset - * @author Jeongho Nam - */ - class HashMultiSet extends base.MultiSet { - /** - * @hidden - */ - private hash_buckets_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from elements. - */ - constructor(items: T[]); - /** - * Copy Constructor. - */ - constructor(container: HashMultiSet); - /** - * Construct from range iterators. - */ - constructor(begin: Iterator, end: Iterator); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: T): SetIterator; - /** - * @inheritdoc - */ - count(key: T): number; - /** - * @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; - /** - *

    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.IContainer): 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 implements base.IHashSet { - /** - * @hidden - */ - private hash_buckets_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from elements. - */ - constructor(items: T[]); - /** - * Copy Constructor. - */ - constructor(container: HashSet); - /** - * Construct from range iterators. - */ - constructor(begin: Iterator, end: Iterator); - /** - * @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; - /** - *

    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.IContainer): void; - } -} -declare namespace std { - /** - *

    Comparable instance.

    - * - *

    {@link IComparable} is a common interface for objects who can compare each other.

    - * - * @reference https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html - * @author Jeongho Nam - */ - interface IComparable extends Object { - /** - *

    Indicates whether some other object is "equal to" this one.

    - * - *

    The {@link equal_to} method implements an equivalence relation on non-null object references:

    - * - *
      - *
    • - * It is reflexive: for any non-null reference value x, x.equal_to(x) - * should return true. - *
    • - *
    • - * It is symmetric: for any non-null reference values x and y, - * x.equal_to(y) should return true if and only if y.equal_to(x) - * returns true.
    • - *
    • - * It is transitive: for any non-null reference values x, y, and - * z, if x.equal_to(y) returns true and y.equal_to(z) - * returns true, then x.equal_to(z) should return true. - *
    • - *
    • - * It is consistent: for any non-null reference values x and y, multiple - * invocations of x.equal_to(y) consistently return true or consistently return - * false, provided no information used in equal_to comparisons on the objects is modified. - *
    • - *
    • - * For any non-null reference value x, x.equal_to(null) should return - * false. - *
    • - *
    - * - *

    The {@link equal_to} method for interface {@link IComparable} implements the most discriminating possible - * equivalence relation on objects; that is, for any non-null reference values x and - * y, this method returns true if and only if x and y - * refer to the same object (x == y has the value true).

    - * - *

    Note that it is generally necessary to override the {@link hash_code} method whenever this method is - * overridden, so as to maintain the general contract for the {@link hash_code} method, which states that - * equal objects must have equal hash codes.

    - * - *
      - *
    • {@link IComparable.equal_to} is called by {@link std.equal_to}.
    • - *
    - * - * @param obj the reference object with which to compare. - * - * @return true if this object is the same as the obj argument; false otherwise. - */ - equals(obj: T): boolean; - /** - *

    Less-than inequality comparison.

    - * - *

    Binary method returns whether the the instance compares less than the obj.

    - * - *
      - *
    • - * {@link IComparable.less} is called by {@link std.less}. Also, this method can be used on standard - * algorithms such as {@link sort sort()}, {@link merge merge()} or - * {@link TreeMap.lower_bound lower_bound()}. - *
    • - *
    - * - * @param obj the reference object with which to compare. - * - * @return Whether the first parameter is less than the second. - */ - less(obj: T): boolean; - /** - *

    Issue a hash code.

    - * - *

    Returns a hash code value for the object. This method is supported for the benefit of hash tables such - * as those provided by hash containers; {@link HashSet}, {@link HashMap}, {@link MultiHashSet} and - * {@link MultiHashMap}.

    - * - *

    As much as is reasonably practical, the {@link hash_code} method defined by interface - * {@link IComparable} does return distinct integers for distinct objects. (This is typically implemented by - * converting the internal address of the object into an integer, but this implementation technique is not - * required by the JavaScript programming language.)

    - * - *
      - *
    • - * {@link IComparable.hash_code} is called by {@link std.hash_code}. If you want to keep basically - * provided hash function, then returns {@link std.Hash.code}; return std.Hash.code(this); - *
    • - *
    - * - * @return An hash code who represents the object. - */ - hashCode?(): number; - } -} -declare namespace std.List { - type iterator = std.ListIterator; - type reverse_iterator = std.ListReverseIterator; -} -declare namespace std { - /** - *

    Doubly linked list.

    - * - *

    {@link List}s are sequence containers that allow constant time insert and erase operations anywhere within the - * sequence, and iteration in both directions.

    - * - *

    List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they - * contain in different and unrelated storage locations. The ordering is kept internally by the association to each - * element of a link to the element preceding it and a link to the element following it.

    - * - *

    Compared to other base standard sequence containers (array, vector and deque), lists perform generally better - * in inserting, extracting and moving elements in any position within the container for which an iterator has already - * been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms.

    - * - *

    The main drawback of lists and forward_lists compared to these other sequence containers is that they lack - * direct access to the elements by their position; For example, to access the sixth element in a list, one has to - * iterate from a known position (like the beginning or the end) to that position, which takes linear time in the - * 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

    - *
    - *
    Sequence
    - *
    Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by - * their position in this sequence.
    - * - *
    Doubly-linked list
    - *
    Each element keeps information on how to locate the next and the previous elements, allowing constant time - * insert and erase operations before or after a specific element (even of entire ranges), but no direct random - * access.
    - *
    - * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/list/list/ - * @author Jeongho Nam - */ - class List extends base.ListContainer> { - private rend_; - /** - *

    Default Constructor.

    - * - *

    Constructs an empty container, with no elements.

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

    Initializer list Constructor.

    - * - *

    Constructs a container with a copy of each of the elements in array, in the same order.

    - * - * @param array An array containing elements to be copied and contained. - */ - constructor(items: Array); - /** - *

    Fill Constructor.

    - * - *

    Constructs a container with n elements. Each element is a copy of val (if provided).

    - * - * @param n Initial container size (i.e., the number of elements in the container at construction). - * @param val Value to fill the container with. Each of the n elements in the container is - * initialized to a copy of this value. - */ - constructor(size: number, val: T); - /** - *

    Copy Constructor.

    - * - *

    Constructs a container with a copy of each of the elements in container, in the same order.

    - * - * @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: List); - /** - *

    Range Constructor.

    - * - *

    Constructs a container with as many elements as the range (begin, end), with each - * element emplace-constructed from its corresponding element in that range, in the same order.

    - * - * @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); - /** - * @hidden - */ - protected _Create_iterator(prev: ListIterator, next: ListIterator, val: T): ListIterator; - /** - * @hidden - */ - protected _Set_begin(it: ListIterator): void; - /** - * @inheritdoc - */ - assign(n: number, val: T): void; - /** - * @inheritdoc - */ - assign>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - rbegin(): ListReverseIterator; - /** - * @inheritdoc - */ - rend(): ListReverseIterator; - /** - * @inheritdoc - */ - front(): T; - /** - * @inheritdoc - */ - back(): T; - /** - *

    Insert an element.

    - * - *

    The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

    - * - *

    Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

    - * - * @param position Position in the container where the new element is inserted. - * {@link iterator}> is a member type, defined as a - * {@link ListIterator bidirectional iterator} type that points to elements. - * @param val Value to be inserted as an element. - * - * @return An iterator that points to the newly inserted element; val. - */ - insert(position: ListIterator, val: T): ListIterator; - /** - *

    Insert elements by repeated filling.

    - * - *

    The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

    - * - *

    Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

    - * - * @param position Position in the container where the new elements are inserted. The {@link iterator} is a - * member type, defined as a {@link ListIterator bidirectional iterator} type that points to - * elements. - * @param size Number of elements to insert. - * @param val Value to be inserted as an element. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert(position: ListIterator, size: number, val: T): ListIterator; - /** - *

    Insert elements by range iterators.

    - * - *

    The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

    - * - *

    Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

    - * - * @param position Position in the container where the new elements are inserted. The {@link iterator} is a - * member type, defined as a {@link ListIterator bidirectional iterator} type that points to - * elements. - * @param begin An iterator specifying range of the begining element. - * @param end An iterator specifying range of the ending element. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert>(position: ListIterator, begin: InputIterator, end: InputIterator): ListIterator; - /** - *

    Insert an element.

    - * - *

    The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

    - * - *

    Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

    - * - * @param position Position in the container where the new element is inserted. - * {@link iterator}> is a member type, defined as a - * {@link ListReverseIterator bidirectional iterator} type that points to elements. - * @param val Value to be inserted as an element. - * - * @return An iterator that points to the newly inserted element; val. - */ - insert(position: ListReverseIterator, val: T): ListReverseIterator; - /** - *

    Insert elements by repeated filling.

    - * - *

    The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

    - * - *

    Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

    - * - * @param position Position in the container where the new elements are inserted. The {@link iterator} is a - * member type, defined as a {@link ListReverseIterator bidirectional iterator} type that points to - * elements. - * @param size Number of elements to insert. - * @param val Value to be inserted as an element. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert(position: ListReverseIterator, size: number, val: T): ListReverseIterator; - /** - *

    Insert elements by range iterators.

    - * - *

    The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

    - * - *

    Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

    - * - * @param position Position in the container where the new elements are inserted. The {@link iterator} is a - * member type, defined as a {@link ListReverseIterator bidirectional iterator} type that points to - * elements. - * @param begin An iterator specifying range of the begining element. - * @param end An iterator specifying range of the ending element. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert>(position: ListReverseIterator, begin: InputIterator, end: InputIterator): ListReverseIterator; - /** - *

    Erase an element.

    - * - *

    Removes from the {@link List} either a single element; position.

    - * - *

    This effectively reduces the container size by the number of element removed.

    - * - *

    Unlike other standard sequence containers, {@link List} objects are specifically designed to be - * efficient inserting and removing elements in any position, even in the middle of the sequence.

    - * - * @param position Iterator pointing to a single element to be removed from the {@link List}. - * - * @return An iterator pointing to the element that followed the last element erased by the function call. - * This is the {@link end end()} if the operation erased the last element in the sequence. - */ - erase(position: ListIterator): ListIterator; - /** - *

    Erase elements.

    - * - *

    Removes from the {@link List} container a range of elements.

    - * - *

    This effectively reduces the container {@link size} by the number of elements removed.

    - * - *

    Unlike other standard sequence containers, {@link List} objects are specifically designed to be - * efficient inserting and removing elements in any position, even in the middle of the sequence.

    - * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - * - * @return An iterator pointing to the element that followed the last element erased by the function call. - * This is the {@link end end()} if the operation erased the last element in the sequence. - */ - erase(begin: ListIterator, end: ListIterator): ListIterator; - /** - *

    Erase an element.

    - * - *

    Removes from the {@link List} either a single element; position.

    - * - *

    This effectively reduces the container size by the number of element removed.

    - * - *

    Unlike other standard sequence containers, {@link List} objects are specifically designed to be - * efficient inserting and removing elements in any position, even in the middle of the sequence.

    - * - * @param position Iterator pointing to a single element to be removed from the {@link List}. - * - * @return An iterator pointing to the element that followed the last element erased by the function call. - * This is the {@link rend rend()} if the operation erased the last element in the sequence. - */ - erase(position: ListReverseIterator): ListReverseIterator; - /** - *

    Erase elements.

    - * - *

    Removes from the {@link List} container a range of elements.

    - * - *

    This effectively reduces the container {@link size} by the number of elements removed.

    - * - *

    Unlike other standard sequence containers, {@link List} objects are specifically designed to be - * efficient inserting and removing elements in any position, even in the middle of the sequence.

    - * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - * - * @return An iterator pointing to the element that followed the last element erased by the function call. - * This is the {@link rend rend()} if the operation erased the last element in the sequence. - */ - erase(begin: ListReverseIterator, end: ListReverseIterator): ListReverseIterator; - /** - *

    Remove duplicate values.

    - * - *

    Removes all but the first element from every consecutive group of equal elements in the

    - * - *

    Notice that an element is only removed from the {@link List} container if it compares equal to the - * element immediately preceding it. Thus, this function is especially useful for sorted lists.

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

    Remove duplicate values.

    - * - *

    Removes all but the first element from every consecutive group of equal elements in the

    - * - *

    The argument binary_pred is a specific comparison function that determine the uniqueness - * of an element. In fact, any behavior can be implemented (and not only an equality comparison), but notice - * that the function will call binary_pred(it.value, it.prev().value) for all pairs of elements - * (where it is an iterator to an element, starting from the second) and remove it - * from the {@link List} if the predicate returns true. - * - *

    Notice that an element is only removed from the {@link List} container if it compares equal to the - * element immediately preceding it. Thus, this function is especially useful for sorted lists.

    - * - * @param binary_pred Binary predicate that, taking two values of the same type than those contained in the - * {@link List}, returns true to remove the element passed as first argument - * from the container, and false otherwise. This shall be a function pointer - * or a function object. - */ - unique(binary_pred: (left: T, right: T) => boolean): void; - /** - *

    Remove elements with specific value.

    - * - *

    Removes from the container all the elements that compare equal to val. This calls the - * destructor of these objects and reduces the container {@link size} by the number of elements removed.

    - * - *

    Unlike member function {@link List.erase}, which erases elements by their position (using an - * iterator), this function ({@link List.remove}) removes elements by their value.

    - * - *

    A similar function, {@link List.remove_if}, exists, which allows for a condition other than an - * equality comparison to determine whether an element is removed.

    - * - * @param val Value of the elements to be removed. - */ - remove(val: T): void; - /** - *

    Remove elements fulfilling condition.

    - * - *

    Removes from the container all the elements for which pred returns true. This - * calls the destructor of these objects and reduces the container {@link size} by the number of elements - * removed.

    - * - *

    The function calls pred(it.value) for each element (where it is an iterator - * to that element). Any of the elements in the list for which this returns true, are removed - * from the

    - * - * @param pred Unary predicate that, taking a value of the same type as those contained in the forward_list - * object, returns true for those values to be removed from the container, and - * false for those remaining. This can either be a function pointer or a function - * object. - */ - remove_if(pred: (val: T) => boolean): void; - /** - *

    Merge sorted {@link List Lists}.

    - * - *

    Merges obj into the {@link List} by transferring all of its elements at their respective - * ordered positions into the container (both containers shall already be ordered). - *

    - * - *

    This effectively removes all the elements in obj (which becomes {@link empty}), and inserts - * them into their ordered position within container (which expands in {@link size} by the number of elements - * transferred). The operation is performed without constructing nor destroying any element: they are - * transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type supports - * move-construction or not.

    - * - *

    This function requires that the {@link List} containers have their elements already ordered by value - * ({@link less}) before the call. For an alternative on unordered {@link List Lists}, see - * {@link List.splice}.

    - * - *

    Assuming such ordering, each element of obj is inserted at the position that corresponds to its - * value according to the strict weak ordering defined by {@link less}. The resulting order of equivalent - * elements is stable (i.e., equivalent elements preserve the relative order they had before the call, and - * existing elements precede those equivalent inserted from obj).

    - * - * The function does nothing if this == obj. - * - * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). - * Note that this function modifies obj no matter whether an lvalue or rvalue reference is - * passed. - */ - merge(obj: List): void; - /** - *

    Merge sorted {@link List Lists}.

    - * - *

    Merges obj into the {@link List} by transferring all of its elements at their respective - * ordered positions into the container (both containers shall already be ordered). - *

    - * - *

    This effectively removes all the elements in obj (which becomes {@link empty}), and inserts - * them into their ordered position within container (which expands in {@link size} by the number of elements - * transferred). The operation is performed without constructing nor destroying any element: they are - * transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type supports - * move-construction or not.

    - * - *

    The argument compare is a specific predicate to perform the comparison operation between - * elements. This comparison shall produce a strict weak ordering of the elements (i.e., a consistent - * transitive comparison, without considering its reflexiveness). - * - *

    This function requires that the {@link List} containers have their elements already ordered by - * compare before the call. For an alternative on unordered {@link List Lists}, see - * {@link List.splice}.

    - * - *

    Assuming such ordering, each element of obj is inserted at the position that corresponds to its - * value according to the strict weak ordering defined by compare. The resulting order of equivalent - * elements is stable (i.e., equivalent elements preserve the relative order they had before the call, and - * existing elements precede those equivalent inserted from obj).

    - * - * The function does nothing if this == obj. - * - * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). - * Note that this function modifies obj no matter whether an lvalue or rvalue reference is - * passed. - * @param compare Binary predicate that, taking two values of the same type than those contained in the - * {@link list}, returns true if the first argument is considered to go before - * the second in the strict weak ordering it defines, and false otherwise. - * This shall be a function pointer or a function object. - */ - merge(obj: List, compare: (left: T, right: T) => boolean): void; - /** - *

    Transfer elements from {@link List} to {@link List}.

    - * - *

    Transfers elements from obj into the container, inserting them at position.

    - * - *

    This effectively inserts all elements into the container and removes them from obj, altering - * the sizes of both containers. The operation does not involve the construction or destruction of any - * element. They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the - * value_type supports move-construction or not.

    - * - *

    This first version (1) transfers all the elements of obj into the

    - * - * @param position Position within the container where the elements of obj are inserted. - * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). - */ - splice(position: ListIterator, obj: List): void; - /** - *

    Transfer an element from {@link List} to {@link List}.

    - * - *

    Transfers an element from obj, which is pointed by an {@link ListIterator iterator} it, - * into the container, inserting the element at specified position.

    - * - *

    This effectively inserts an element into the container and removes it from obj, altering the - * sizes of both containers. The operation does not involve the construction or destruction of any element. - * They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type - * supports move-construction or not.

    - * - *

    This second version (2) transfers only the element pointed by it from obj into the - *

    - * - * @param position Position within the container where the element of obj is inserted. - * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). - * This parameter may be this if position points to an element not actually - * being spliced. - * @param it {@link ListIterator Iterator} to an element in obj. Only this single element is - * transferred. - */ - splice(position: ListIterator, obj: List, it: ListIterator): void; - /** - *

    Transfer elements from {@link List} to {@link List}.

    - * - *

    Transfers elements from obj into the container, inserting them at position.

    - * - *

    This effectively inserts those elements into the container and removes them from obj, altering - * the sizes of both containers. The operation does not involve the construction or destruction of any - * element. They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the - * value_type supports move-construction or not.

    - * - *

    This third version (3) transfers the range [begin, end) from obj into the - *

    - * - * @param position Position within the container where the elements of obj are inserted. - * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). - * This parameter may be this if position points to an element not actually - * being spliced. - * @param begin {@link ListIterator An Iterator} specifying initial position of a range of elements in - * obj. Transfers the elements in the range [begin, end) to - * position. - * @param end {@link ListIterator An Iterator} specifying final position of a range of elements in - * obj. Transfers the elements in the range [begin, end) to - * position. Notice that the range includes all the elements between begin and - * end, including the element pointed by begin but not the one pointed by end. - */ - splice(position: ListIterator, obj: List, begin: ListIterator, end: ListIterator): void; - /** - *

    Sort elements in

    - * - *

    Sorts the elements in the {@link List}, altering their position within the

    - * - *

    The sorting is performed by applying an algorithm that uses {@link less}. This comparison shall - * produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without - * considering its reflexiveness).

    - * - *

    The resulting order of equivalent elements is stable: i.e., equivalent elements preserve the relative - * order they had before the call.

    - * - *

    The entire operation does not involve the construction, destruction or copy of any element object. - * Elements are moved within the

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

    Sort elements in

    - * - *

    Sorts the elements in the {@link List}, altering their position within the

    - * - *

    The sorting is performed by applying an algorithm that uses compare. This comparison shall - * produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without - * considering its reflexiveness).

    - * - *

    The resulting order of equivalent elements is stable: i.e., equivalent elements preserve the relative - * order they had before the call.

    - * - *

    The entire operation does not involve the construction, destruction or copy of any element object. - * Elements are moved within the

    - * - * @param compare Binary predicate that, taking two values of the same type of those contained in the - * {@link List}, returns true if the first argument goes before the second - * argument in the strict weak ordering it defines, and false otherwise. This - * 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); - /** - *

    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; - } -} -declare namespace std { - /** - *

    An iterator, node of a List.

    - * - *

    - * - *

    - * - * @author Jeongho Nam - */ - class ListIterator extends base.ListIteratorBase { - /** - * Initializer Constructor. - * - * #### Note - * Do not create the iterator directly, by yourself. - * - * Use {@link List.begin begin()}, {@link List.end end()} in {@link List container} instead. - * - * @param source The source {@link List container} to reference. - * @param prev A refenrece of previous node ({@link ListIterator iterator}). - * @param next A refenrece of next node ({@link ListIterator iterator}). - * @param value Value to be stored in the node (iterator). - */ - constructor(source: List, prev: ListIterator, next: ListIterator, value: T); - /** - * @inheritdoc - */ - prev(): ListIterator; - /** - * @inheritdoc - */ - next(): ListIterator; - /** - * @inheritdoc - */ - advance(step: number): ListIterator; - /** - * @inheritdoc - */ - /** - * Set value of the iterator is pointing to. - * - * @param val Value to set. - */ - value: T; - /** - * @inheritdoc - */ - equals(obj: ListIterator): boolean; - /** - * @inheritdoc - */ - swap(obj: ListIterator): void; - } -} -declare namespace std { - /** - *

    A reverse-iterator of List.

    - * - *

    - * - *

    - * - * @param Type of the elements. - * - * @author Jeongho Nam - */ - class ListReverseIterator extends ReverseIterator, ListReverseIterator> implements base.ILinearIterator { - /** - * Construct from base iterator. - * - * @param base A reference of the base iterator, which iterates in the opposite direction. - */ - constructor(base: ListIterator); - /** - * @hidden - */ - protected _Create_neighbor(base: ListIterator): ListReverseIterator; - /** - * @inheritdoc - */ - /** - * Set value of the iterator is pointing to. - * - * @param val Value to set. - */ - value: T; - } -} -declare namespace std.Vector { - type iterator = std.VectorIterator; - type reverse_iterator = std.VectorReverseIterator; -} -declare namespace std { - /** - *

    Vector, the dynamic array.

    - * - *

    {@link Vector}s are sequence containers representing arrays that can change in size.

    - * - *

    Just like arrays, {@link Vector}s use contiguous storage locations for their elements, which means that - * their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently - * as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled - * automatically by the container.

    - * - *

    Internally, {@link Vector}s use a dynamically allocated array to store their elements. This array may need - * to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new - * array and moving all elements to it. This is a relatively expensive task in terms of processing time, and - * thus, {@link Vector}s do not reallocate each time an element is added to the container.

    - * - *

    Instead, {@link Vector} containers may allocate some extra storage to accommodate for possible growth, and - * thus the container may have an actual {@link capacity} greater than the storage strictly needed to contain its - * elements (i.e., its {@link size}). Libraries can implement different strategies for growth to balance between - * memory usage and reallocations, but in any case, reallocations should only happen at logarithmically growing - * intervals of {@link size} so that the insertion of individual elements at the end of the {@link Vector} can be - * provided with amortized constant time complexity (see {@link push_back push_back()}).

    - * - *

    Therefore, compared to arrays, {@link Vector}s consume more memory in exchange for the ability to manage - * storage and grow dynamically in an efficient way.

    - * - *

    Compared to the other dynamic sequence containers ({@link Deque}s, {@link List}s), {@link Vector Vectors} - * are very efficient accessing its elements (just like arrays) and relatively efficient adding or removing - * elements from its end. For operations that involve inserting or removing elements at positions other than the - * end, they perform worse than the others, and have less consistent iterators and references than {@link List}s. - *

    - * - *

    - * - *

    - * - *

    Container properties

    - *
    - *
    Sequence
    - *
    - * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are - * accessed by their position in this sequence. - *
    - * - *
    Dynamic array
    - *
    - * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides - * relatively fast addition/removal of elements at the end of the sequence. - *
    - *
    - * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/vector/vector - * @author Jeongho Nam - */ - class Vector extends Array implements base.IContainer, base.IArrayContainer { - /** - * @hidden - */ - private end_; - /** - * @hidden - */ - private rend_; - /** - *

    Default Constructor.

    - * - *

    Constructs an empty container, with no elements.

    - */ - constructor(); - /** - * @inheritdoc - */ - constructor(array: Array); - /** - *

    Initializer list Constructor.

    - * - *

    Constructs a container with a copy of each of the elements in array, in the same order.

    - * - * @param array An array containing elements to be copied and contained. - */ - constructor(n: number); - /** - *

    Fill Constructor.

    - * - *

    Constructs a container with n elements. Each element is a copy of val (if provided).

    - * - * @param n Initial container size (i.e., the number of elements in the container at construction). - * @param val Value to fill the container with. Each of the n elements in the container is - * initialized to a copy of this value. - */ - constructor(n: number, val: T); - /** - *

    Copy Constructor.

    - * - *

    Constructs a container with a copy of each of the elements in container, in the same order.

    - * - * @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: Vector); - /** - *

    Range Constructor.

    - * - *

    Constructs a container with as many elements as the range (begin, end), with each - * element emplace-constructed from its corresponding element in that range, in the same order.

    - * - * @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); - /** - * @inheritdoc - */ - assign>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - assign(n: number, val: T): void; - /** - * @inheritdoc - */ - reserve(size: number): void; - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - begin(): VectorIterator; - /** - * @inheritdoc - */ - end(): VectorIterator; - /** - * @inheritdoc - */ - rbegin(): VectorReverseIterator; - /** - * @inheritdoc - */ - rend(): VectorReverseIterator; - /** - * @inheritdoc - */ - size(): number; - /** - * @inheritdoc - */ - capacity(): number; - /** - * @inheritdoc - */ - empty(): boolean; - /** - * @inheritdoc - */ - at(index: number): T; - /** - * @inheritdoc - */ - set(index: number, val: T): T; - /** - * @inheritdoc - */ - front(): T; - /** - * @inheritdoc - */ - back(): T; - /** - * @inheritdoc - */ - push_back(val: T): void; - /** - *

    Insert an element.

    - * - *

    The {@link Vector} is extended by inserting new element before the element at the specified - * position, effectively increasing the container size by one.

    - * - *

    This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

    - * - *

    Because {@link Vector}s use an Array as their underlying storage, inserting element in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to its new position. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

    - * - * @param position Position in the {@link Vector} where the new element is inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param val Value to be copied to the inserted element. - * - * @return An iterator that points to the newly inserted element. - */ - insert(position: VectorIterator, val: T): VectorIterator; - /** - *

    Insert elements by repeated filling.

    - * - *

    The {@link Vector} is extended by inserting new elements before the element at the specified - * position, effectively increasing the container size by the number of elements inserted.

    - * - *

    This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

    - * - *

    Because {@link Vector}s use an Array as their underlying storage, inserting elements in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to their new positions. This is generally an inefficient operation compared to the - * one performed for the same operation by other kinds of sequence containers (such as {@link List}). - * - * @param position Position in the {@link Vector} where the new elements are inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param n Number of elements to insert. Each element is initialized to a copy of val. - * @param val Value to be copied (or moved) to the inserted elements. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert(position: VectorIterator, n: number, val: T): VectorIterator; - /** - *

    Insert elements by range iterators.

    - * - *

    The {@link Vector} is extended by inserting new elements before the element at the specified - * position, effectively increasing the container size by the number of elements inserted by range - * iterators.

    - * - *

    This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

    - * - *

    Because {@link Vector}s use an Array as their underlying storage, inserting elements in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to their new positions. This is generally an inefficient operation compared to the - * one performed for the same operation by other kinds of sequence containers (such as {@link List}). - * - * @param position Position in the {@link Vector} where the new elements are inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert>(position: VectorIterator, begin: InputIterator, end: InputIterator): VectorIterator; - /** - *

    Insert an element.

    - * - *

    The {@link Vector} is extended by inserting new element before the element at the specified - * position, effectively increasing the container size by one.

    - * - *

    This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

    - * - *

    Because {@link Vector}s use an Array as their underlying storage, inserting element in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to its new position. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

    - * - * @param position Position in the {@link Vector} where the new element is inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param val Value to be copied to the inserted element. - * - * @return An iterator that points to the newly inserted element. - */ - insert(position: VectorReverseIterator, val: T): VectorReverseIterator; - /** - *

    Insert elements by repeated filling.

    - * - *

    The {@link Vector} is extended by inserting new elements before the element at the specified - * position, effectively increasing the container size by the number of elements inserted.

    - * - *

    This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

    - * - *

    Because {@link Vector}s use an Array as their underlying storage, inserting elements in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to their new positions. This is generally an inefficient operation compared to the - * one performed for the same operation by other kinds of sequence containers (such as {@link List}). - * - * @param position Position in the {@link Vector} where the new elements are inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param n Number of elements to insert. Each element is initialized to a copy of val. - * @param val Value to be copied (or moved) to the inserted elements. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert(position: VectorReverseIterator, n: number, val: T): VectorReverseIterator; - /** - *

    Insert elements by range iterators.

    - * - *

    The {@link Vector} is extended by inserting new elements before the element at the specified - * position, effectively increasing the container size by the number of elements inserted by range - * iterators.

    - * - *

    This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

    - * - *

    Because {@link Vector}s use an Array as their underlying storage, inserting elements in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to their new positions. This is generally an inefficient operation compared to the - * one performed for the same operation by other kinds of sequence containers (such as {@link List}). - * - * @param position Position in the {@link Vector} where the new elements are inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert>(position: VectorReverseIterator, begin: InputIterator, end: InputIterator): VectorReverseIterator; - /** - * @hidden - */ - private insert_by_val(position, val); - /** - * @hidden - */ - protected _Insert_by_repeating_val(position: VectorIterator, n: number, val: T): VectorIterator; - /** - * @hidden - */ - protected _Insert_by_range>(position: VectorIterator, first: InputIterator, last: InputIterator): VectorIterator; - /** - * @inheritdoc - */ - pop_back(): void; - /** - *

    Erase element.

    - * - *

    Removes from the {@link Vector} either a single element; position.

    - * - *

    This effectively reduces the container size by the number of element removed.

    - * - *

    Because {@link Vector}s use an Array as their underlying storage, erasing an element in - * position other than the {@link end end()} causes the container to relocate all the elements after the - * segment erased to their new positions. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

    - * - * @param position Iterator pointing to a single element to be removed from the {@link Vector}. - * - * @return An iterator pointing to the new location of the element that followed the last element erased by - * the function call. This is the {@link end end()} if the operation erased the last element in the - * sequence. - */ - erase(position: VectorIterator): VectorIterator; - /** - *

    Erase element.

    - * - *

    Removes from the Vector either a single element; position.

    - * - *

    This effectively reduces the container size by the number of elements removed.

    - * - *

    Because {@link Vector}s use an Array as their underlying storage, erasing elements in - * position other than the {@link end end()} causes the container to relocate all the elements after the - * segment erased to their new positions. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

    - * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - * - * @return An iterator pointing to the new location of the element that followed the last element erased by - * the function call. This is the {@link rend rend()} if the operation erased the last element in the - * sequence. - */ - erase(first: VectorIterator, last: VectorIterator): VectorIterator; - /** - *

    Erase element.

    - * - *

    Removes from the {@link Vector} either a single element; position.

    - * - *

    This effectively reduces the container size by the number of element removed.

    - * - *

    Because {@link Vector}s use an Array as their underlying storage, erasing an element in - * position other than the {@link end end()} causes the container to relocate all the elements after the - * segment erased to their new positions. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

    - * - * @param position Iterator pointing to a single element to be removed from the {@link Vector}. - * - * @return An iterator pointing to the new location of the element that followed the last element erased by - * the function call. This is the {@link rend rend()} if the operation erased the last element in the - * sequence. - */ - erase(position: VectorReverseIterator): VectorReverseIterator; - /** - *

    Erase element.

    - * - *

    Removes from the Vector either a single element; position.

    - * - *

    This effectively reduces the container size by the number of elements removed.

    - * - *

    Because {@link Vector}s use an Array as their underlying storage, erasing elements in - * position other than the {@link end end()} causes the container to relocate all the elements after the - * segment erased to their new positions. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

    - * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - * - * @return An iterator pointing to the new location of the element that followed the last element erased by - * the function call. This is the {@link end end()} if the operation erased the last element in the - * sequence. - */ - erase(first: VectorReverseIterator, last: VectorReverseIterator): VectorReverseIterator; - /** - * @hidden - */ - 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}. - */ - swap(obj: Vector): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer): void; - } -} -declare namespace std { - /** - *

    An iterator of Vector.

    - * - *

    - * - *

    - * - * @param Type of the elements. - * - * @author Jeongho Nam - */ - class VectorIterator extends Iterator implements base.IArrayIterator { - /** - * Sequence number of iterator in the source {@link Vector}. - */ - private index_; - /** - *

    Construct from the source {@link Vector container}.

    - * - *

    Note

    - *

    Do not create the iterator directly, by yourself.

    - *

    Use {@link Vector.begin begin()}, {@link Vector.end end()} in {@link Vector container} instead.

    - * - * @param source The source {@link Vector container} to reference. - * @param index Sequence number of the element in the source {@link Vector}. - */ - constructor(source: Vector, index: number); - /** - * @hidden - */ - private readonly vector; - /** - * @inheritdoc - */ - /** - * Set value of the iterator is pointing to. - * - * @param val Value to set. - */ - value: T; - /** - * Get index. - */ - readonly index: number; - /** - * @inheritdoc - */ - prev(): VectorIterator; - /** - * @inheritdoc - */ - next(): VectorIterator; - /** - * @inheritdoc - */ - advance(n: number): VectorIterator; - /** - * @inheritdoc - */ - equals(obj: VectorIterator): boolean; - /** - * @inheritdoc - */ - swap(obj: VectorIterator): void; - toString(): number; - } -} -declare namespace std { - /** - *

    A reverse-iterator of Vector.

    - * - *

    - * - *

    - * - * @param Type of the elements. - * - * @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); - /** - * @hidden - */ - protected _Create_neighbor(base: VectorIterator): VectorReverseIterator; - /** - * @inheritdoc - */ - /** - * Set value of the iterator is pointing to. - * - * @param val Value to set. - */ - value: T; - /** - * Get index. - */ - readonly index: number; - } -} -declare namespace std { - /** - *

    FIFO queue.

    - * - *

    {@link Queue}s are a type of container adaptor, specifically designed to operate in a FIFO context - * (first-in first-out), where elements are inserted into one end of the container and extracted from the other. - *

    - * - *

    {@link Queue}s are implemented as containers adaptors, which are classes that use an encapsulated object of - * a specific container class as its underlying container, providing a specific set of member functions to access - * its elements. Elements are pushed into the {@link IDeque.back back()} of the specific container and popped from - * its {@link IDeque.front front()}.

    - * - *

    {@link container_ The underlying container} may be one of the standard container class template or some - * other specifically designed container class. This underlying container shall support at least the following - * operations:

    - * - *
      - *
    • empty
    • - *
    • size
    • - *
    • front
    • - *
    • back
    • - *
    • push_back
    • - *
    • pop_front
    • - *
    - * - *

    The standard container classes {@link Deque} and {@link List} fulfill these requirements. - * 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. - * - * @reference http://www.cplusplus.com/reference/queue/queue - * @author Jeongho Nam - */ - class Queue { - /** - * The underlying object for implementing the FIFO - */ - private container_; - /** - * Default Constructor. - */ - constructor(); - /** - * Copy Constructor. - */ - constructor(container: Queue); - /** - *

    Return size.

    - *

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

    - * - *

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

    - * - * @return The number of elements in the {@link container_ underlying container}. - */ - size(): number; - /** - *

    Test whether container is empty.

    - *

    returns whether the {@link Queue} is empty: i.e. whether its size is zero.

    - * - *

    This member function efeectively calls member {@link IDeque.empty empty()} of the - * {@link container_ underlying container} object.

    - * - * @return true if the {@link container_ underlying container}'s size is 0, - * false otherwise.

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

    Access next element.

    - *

    Returns a value of the next element in the {@link Queue}.

    - * - *

    The next element is the "oldest" element in the {@link Queue} and the same element that is popped out - * from the queue when {@link pop Queue.pop()} is called.

    - * - *

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

    - * - * @return A value of the next element in the {@link Queue}. - */ - front(): T; - /** - *

    Access last element.

    - * - *

    Returns a vaue of the last element in the queue. This is the "newest" element in the queue (i.e. the - * last element pushed into the queue).

    - * - *

    This member function effectively calls the member function {@link IDeque.back back()} of the - * {@link container_ underlying container} object.

    - * - * @return A value of the last element in the {@link Queue}. - */ - back(): T; - /** - *

    Insert element.

    - * - *

    Inserts a new element at the end of the {@link Queue}, after its current last element. - * The content of this new element is initialized to val.

    - * - *

    This member function effectively calls the member function {@link IDeque.push_back push_back()} of the - * {@link container_ underlying container} object.

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

    Remove next element.

    - * - *

    Removes the next element in the {@link Queue}, effectively reducing its size by one.

    - * - *

    The element removed is the "oldest" element in the {@link Queue} whose value can be retrieved by calling - * member {@link front Queue.front()}

    . - * - *

    This member function effectively calls the member function {@link IDeque.pop_front pop_front()} of the - * {@link container_ underlying container} object.

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

    Swap contents.

    - * - *

    Exchanges the contents of the container adaptor (this) by those of obj.

    - * - *

    This member function calls the non-member function {@link IContainer.swap swap} (unqualified) to swap - * the {@link container_ underlying containers}.

    - * - * @param obj Another {@link Queue} container adaptor of the same type (i.e., instantiated with the same - * template parameter, T). Sizes may differ.

    - */ - 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.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 { - /** - *

    LIFO stack.

    - * - *

    {@link Stack}s are a type of container adaptor, specifically designed to operate in a LIFO context - * (last-in first-out), where elements are inserted and extracted only from one end of the

    - * - *

    {@link Stack}s are implemented as containers adaptors, which are classes that use an encapsulated object of - * a specific container class as its underlying container, providing a specific set of member functions to - * access its elements. Elements are pushed/popped from the {@link ILinearContainer.back back()} of the - * {@link ILinearContainer specific container}, which is known as the top of the {@link Stack}.

    - * - *

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

    - * - *
      - *
    • empty
    • - *
    • size
    • - *
    • front
    • - *
    • back
    • - *
    • push_back
    • - *
    • pop_back
    • - *
    - * - *

    The standard container classes {@link Vector}, {@link Deque} and {@link List} fulfill these requirements. - * 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. - * - * @reference http://www.cplusplus.com/reference/stack/stack - * @author Jeongho Nam - */ - class Stack { - /** - * The underlying object for implementing the LIFO - */ - private container_; - /** - * Default Constructor. - */ - constructor(); - /** - * Copy Constructor. - */ - constructor(stack: Stack); - /** - *

    Return size.

    - * - *

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

    - * - *

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

    - * - * @return The number of elements in the {@link container_ underlying container}. - */ - size(): number; - /** - *

    Test whether container is empty.

    - * - *

    returns whether the {@link Stack} is empty: i.e. whether its size is zero.

    - * - *

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

    - * - * @return true if the underlying container's size is 0, - * false otherwise.

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

    Access next element.

    - * - *

    Returns a value of the top element in the {@link Stack}

    . - * - *

    Since {@link Stack}s are last-in first-out containers, the top element is the last element inserted into - * the {@link Stack}.

    - * - *

    This member function effectively calls member {@link ILinearContainer.back back()} of the - * {@link container_ underlying container} object.

    - * - * @return A value of the top element in the {@link Stack}. - */ - top(): T; - /** - *

    Insert element.

    - * - *

    Inserts a new element at the top of the {@link Stack}, above its current top element.

    - * - *

    This member function effectively calls the member function - * {@link ILinearContainer.push_back push_back()} of the {@link container_ underlying container} object.

    - * - * @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 Stack}, effectively reducing its size by one.

    - * - *

    The element removed is the latest element inserted into the {@link Stack}, whose value can be retrieved - * by calling member {@link top Stack.top()}

    . - * - *

    This member function effectively calls the member function {@link ILinearContainer.pop_back pop_back()} - * of the {@link container_ underlying container} object.

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

    Swap contents.

    - * - *

    Exchanges the contents of the container adaptor (this) by those of obj.

    - * - *

    This member function calls the non-member function {@link IContainer.swap swap} (unqualified) to swap - * the {@link container_ underlying containers}.

    - * - * @param obj Another {@link Stack} container adaptor of the same type (i.e., instantiated with the same - * template parameter, T). Sizes may differ.

    - */ - swap(obj: Stack): void; - } -} -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 container.

    - * - *

    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: TreeMultiSet); - /** - * Copy Constructor with compare. - * - * @param container A container to be copied. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: TreeMultiSet, 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); - /** - * 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. - * @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; - /** - *

    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.IContainer): void; - } -} -declare namespace std.TreeMap { - type iterator = std.MapIterator; - type reverse_iterator = std.MapReverseIterator; -} -declare namespace std { - /** - *

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

    - * - *

    {@link TreeMap TreeMaps} are associative containers that store elements formed by a combination of a - * key value (Key) and a mapped value (T), following order.

    - * - *

    In a {@link TreeMap}, the key values are generally used to sort and uniquely identify the elements, - * while the mapped values store the content associated to this key. The types of key and - * mapped value may differ, and are grouped together in member type value_type, which is a {@link Pair} - * type combining both:

    - * - *

    typedef Pair value_type;

    - * - *

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

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

    - * - *

    {@link TreeMap}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.
    - * - *
    Map
    - *
    Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value.
    - * - *
    Unique keys
    - *
    No two elements in the container can have equivalent keys.
    - *
    - * - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/map/map - * @author Jeongho Nam - */ - class TreeMap extends base.UniqueMap implements base.ITreeMap { - /** - * @hidden - */ - private tree_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from compare. - * - * @param compare A binary predicate determines order of elements. - */ - constructor(compare: (x: Key, y: Key) => boolean); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - */ - constructor(array: Array>); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array>, compare: (x: Key, y: Key) => boolean); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - */ - constructor(array: Array<[Key, T]>); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array<[Key, T]>, compare: (x: Key, y: Key) => boolean); - /** - * Copy Constructor. - * - * @param container Another map to copy. - */ - constructor(container: TreeMap); - /** - * Copy Constructor. - * - * @param container Another map to copy. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: TreeMap, compare: (x: Key, y: Key) => boolean); - /** - * Range Constructor. - * - * @param begin nput 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. - * - * @param begin nput 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: Key, y: Key) => boolean); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: Key): MapIterator; - /** - * @inheritdoc - */ - key_comp(): (x: Key, y: Key) => boolean; - /** - * @inheritdoc - */ - value_comp(): (x: Pair, y: Pair) => boolean; - /** - * @inheritdoc - */ - lower_bound(key: Key): MapIterator; - /** - * @inheritdoc - */ - upper_bound(key: Key): MapIterator; - /** - * @inheritdoc - */ - equal_range(key: Key): Pair, MapIterator>; - /** - * @hidden - */ - protected _Insert_by_pair(pair: Pair): any; - /** - * @hidden - */ - protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; - /** - * @hidden - */ - protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected _Handle_insert(first: MapIterator, last: MapIterator): void; - /** - * @inheritdoc - */ - 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.IContainer>): void; - } -} -declare namespace std.TreeMultiSet { - type iterator = std.SetIterator; - type reverse_iterator = std.SetReverseIterator; -} -declare namespace std { - /** - *

    Tree-structured multiple-key set.

    - * - *

    {@link TreeMultiSet TreeMultiSets} are containers that store elements following a specific order, and - * where multiple elements can have equivalent values.

    - * - *

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

    - * - *

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

    - * - *

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

    - * - *

    {@link TreeMultiSet TreeMultiSets} 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.
    - * - *
    Multiple equivalent keys
    - *
    Multiple elements in the container can have equivalent keys.
    - *
    - * - * @param Type of the elements. Each element in a {@link TreeMultiSet} container is also identified - * by this value (each value is itself also the element's key). - * - * @reference http://www.cplusplus.com/reference/set/multiset - * @author Jeongho Nam - */ - class TreeMultiSet extends base.MultiSet 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: TreeMultiSet); - /** - * Copy Constructor with compare. - * - * @param container A container to be copied. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: TreeMultiSet, 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); - /** - * 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. - * @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 - */ - count(val: T): number; - /** - * @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; - /** - * @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; - /** - *

    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.TreeMultiMap { - type iterator = std.MapIterator; - type reverse_iterator = std.MapReverseIterator; -} -declare namespace std { - /** - *

    Tree-structured multiple-key map.

    - * - *

    {@link TreeMultiMap TreeMultiMaps} are associative containers that store elements formed by a combination of - * a key value and a mapped value, following a specific order, and where multiple elements can - * have equivalent keys.

    - * - *

    In a {@link TreeMultiMap}, the key values are generally used to sort and uniquely identify - * the elements, while the mapped values store the content associated to this key. The types of - * key and mapped value may differ, and are grouped together in member type - * value_type, which is a {@link Pair} type combining both:

    - * - *

    typedef Pair value_type;

    - * - *

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

    - * - *

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

    - * - *

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

    - * - *

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

    - * - *

    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. - *
    - * - *
    Map
    - *
    - * Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value. - *
    - * - *
    Multiple equivalent keys
    - *
    Multiple elements in the container can have equivalent keys.
    - *
    - * - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/map/multimap - * @author Jeongho Nam - */ - class TreeMultiMap extends base.MultiMap implements base.ITreeMap { - /** - * @hidden - */ - private tree_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from compare. - * - * @param compare A binary predicate determines order of elements. - */ - constructor(compare: (x: Key, y: Key) => boolean); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - */ - constructor(array: Array>); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array>, compare: (x: Key, y: Key) => boolean); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - */ - constructor(array: Array<[Key, T]>); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array<[Key, T]>, compare: (x: Key, y: Key) => boolean); - /** - * Copy Constructor. - * - * @param container Another map to copy. - */ - constructor(container: TreeMultiMap); - /** - * Copy Constructor. - * - * @param container Another map to copy. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: TreeMultiMap, compare: (x: Key, y: Key) => boolean); - /** - * Range Constructor. - * - * @param begin nput 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. - * - * @param begin nput 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: Key, y: Key) => boolean); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: Key): MapIterator; - /** - * @inheritdoc - */ - count(key: Key): number; - /** - * @inheritdoc - */ - key_comp(): (x: Key, y: Key) => boolean; - /** - * @inheritdoc - */ - value_comp(): (x: Pair, y: Pair) => boolean; - /** - * @inheritdoc - */ - lower_bound(key: Key): MapIterator; - /** - * @inheritdoc - */ - upper_bound(key: Key): MapIterator; - /** - * @inheritdoc - */ - equal_range(key: Key): Pair, MapIterator>; - /** - * @hidden - */ - protected _Insert_by_pair(pair: Pair): any; - /** - * @hidden - */ - protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; - /** - * @hidden - */ - protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected _Handle_insert(first: MapIterator, last: MapIterator): void; - /** - * @inheritdoc - */ - 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.IContainer>): void; - } -} -declare namespace std { - /** - *

    System error exception.

    - * - *

    This class defines the type of objects thrown as exceptions to report conditions originating during - * runtime from the operating system or other low-level application program interfaces which have an - * associated {@link ErrorCode}.

    - * - *

    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 { - /** - * @hidden - */ - protected code_: ErrorCode; - /** - * Construct from an error code. - * - * @param code An {@link ErrorCode} object. - */ - constructor(code: ErrorCode); - /** - * Construct from an error code and message. - * - * @param code An {@link ErrorCode} object. - * @param message A message incorporated in the string returned by member {@link what what()}. - */ - constructor(code: ErrorCode, message: string); - /** - * Construct from a numeric value and error category. - * - * @param val A numerical value identifying an error code. - * @param category A reference to an {@link ErrorCode} object. - */ - constructor(val: number, category: ErrorCategory); - /** - * Construct from a numeric value, error category and message. - * - * @param val A numerical value identifying an error code. - * @param category A reference to an {@link ErrorCode} object. - * @param message A message incorporated in the string returned by member {@link what what()}. - */ - constructor(val: number, category: ErrorCategory, message: string); - /** - *

    Get error code.

    - * - *

    Returns the {@link ErrorCode} object associated with the exception.

    - * - *

    This value is either the {@link ErrorCode} passed to the construction or its equivalent - * (if constructed with a value and a {@link category}.

    - * - * @return The {@link ErrorCode} associated with the object. - */ - code(): ErrorCode; - } -} -declare namespace std { - /** - *

    Error category.

    - * - *

    This type serves as a base class for specific category types.

    - * - *

    Category types are used to identify the source of an error. They also define the relation between - * {@link ErrorCode} and {@link ErrorCondition}objects of its category, as well as the message set for {@link ErrorCode} - * objects. - * - *

    Objects of these types have no distinct values and are not-copyable and not-assignable, and thus can only be - * 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 - */ - abstract class ErrorCategory { - /** - * Default Constructor. - */ - constructor(); - /** - *

    Return category name.

    - * - *

    In derived classes, the function returns a string naming the category.

    - * - *

    In {@link ErrorCategory}, it is a pure virtual member function.

    - * - *
      - *
    • In the {@link GenericCategory} object, it returns "generic".
    • - *
    • In the {@link SystemCategory} object, it returns "system".
    • - *
    • In the {@link IOStreamCategory} object, it returns "iostream".
    • - *
    - * - * @return The category name. - */ - abstract name(): string; - /** - *

    Error message.

    - * - *

    In derived classes, the function returns a string object with a message describing the error condition - * denoted by val.

    - * - *

    In {@link ErrorCategory}, it is a pure virtual member function.

    - * - *

    This function is called both by {@link ErrorCode.message ErrorCode.message()} and - * {@link ErrorCondition.message ErrorCondition.message()} to obtain the corresponding message in the - * {@link category}. Therefore, numerical values used by custom error codes and - * {@link ErrorCondition error conditions} should only match for a category if they describe the same error.

    - * - * @param val A numerical value identifying an error condition. - * If the {@link ErrorCategory} object is the {@link GenericCategory}, this argument is equivalent to an - * {@link errno} value. - * - * @return A string object with the message. - */ - abstract message(val: number): string; - /** - *

    Default error condition.

    - * - *

    Returns the default {@link ErrorCondition}object of this category that is associated with the - * {@link ErrorCode} identified by a value of val.

    - * - *

    Its definition in the base class {@link ErrorCategory} returns the same as constructing an - * {@link ErrorCondition} object with: - * - *

    new ErrorCondition(val, *this);

    - * - *

    As a virtual member function, this behavior can be overriden in derived classes.

    - * - *

    This function is called by the default definition of member {@link equivalent equivalent()}, which is used to - * compare {@link ErrorCondition error conditions} with error codes.

    - * - * @param val A numerical value identifying an error condition. - * - * @return The default {@link ErrorCondition}object associated with condition value val for this category. - */ - default_error_condition(val: number): ErrorCondition; - /** - *

    Check error code equivalence.

    - * - *

    Checks whether, for the category, an {@link ErrorCode error code} is equivalent to an - * {@link ErrorCondition error condition.

    - * - *

    This function is called by the overloads of comparison operators when an {@link ErrorCondition} object is - * compared to an {@link ErrorCode} object to check for equality or inequality. If either one of those objects' - * {@link ErrorCategory categories} considers the other equivalent using this function, they are considered - * equivalent by the operator.

    - * - *

    As a virtual member function, this behavior can be overridden in derived classes to define a different - * correspondence mechanism for each {@link ErrorCategory} type.

    - * - * @param val_code A numerical value identifying an error code. - * @param cond An object of an {@link ErrorCondition} type. - * - * @return true if the arguments are considered equivalent. false otherwise. - */ - equivalent(val_code: number, cond: ErrorCondition): boolean; - /** - *

    Check error code equivalence.

    - * - *

    Checks whether, for the category, an {@link ErrorCode error code} is equivalent to an - * {@link ErrorCondition error condition.

    - * - *

    This function is called by the overloads of comparison operators when an {@link ErrorCondition} object is - * compared to an {@link ErrorCode} object to check for equality or inequality. If either one of those objects' - * {@link ErrorCategory categories} considers the other equivalent using this function, they are considered - * equivalent by the operator.

    - * - *

    As a virtual member function, this behavior can be overridden in derived classes to define a different - * correspondence mechanism for each {@link ErrorCategory} type.

    - * - * @param code An object of an {@link ErrorCode} type. - * @param val_cond A numerical value identifying an error code. - * - * @return true if the arguments are considered equivalent. false otherwise. - */ - equivalent(code: ErrorCode, val_cond: number): boolean; - } -} -declare namespace std { - /** - *

    Error condition.

    - * - *

    Objects of this type hold a condition {@link value} associated with a {@link category}.

    - * - *

    Objects of this type describe errors in a generic way so that they may be portable across different - * systems. This is in contrast with {@link ErrorCode} objects, that may contain system-specific - * information.

    - * - *

    Because {@link ErrorCondition}objects can be compared with error_code objects directly by using - * relational operators, {@link ErrorCondition}objects are generally used to check whether - * a particular {@link ErrorCode} obtained from the system matches a specific error condition no matter - * the system.

    - * - *

    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 - */ - class ErrorCondition extends base.ErrorInstance { - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from a numeric value and error category. - * - * @param val A numerical value identifying an error condition. - * @param category A reference to an {@link ErrorCategory} object. - */ - constructor(val: number, category: ErrorCategory); - } -} -declare namespace std { - /** - *

    Error code.

    - * - *

    Objects of this type hold an error code {@link value} associated with a {@link category}.

    - * - *

    The operating system and other low-level applications and libraries generate numerical error codes to - * represent possible results. These numerical values may carry essential information for a specific platform, - * but be non-portable from one platform to another.

    - * - *

    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 - */ - class ErrorCode extends base.ErrorInstance { - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from a numeric value and error category. - * - * @param val A numerical value identifying an error code. - * @param category A reference to an {@link ErrorCategory} object. - */ - constructor(val: number, category: ErrorCategory); - } -} -declare namespace std { - /** - *

    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; - /** - *

    Pair of values.

    - * - *

    This class couples together a pair of values, which may be of different types (T1 and - * T2). The individual values can be accessed through its public members {@link first} and - * {@link second}.

    - * - * @param Type of member {@link first}. - * @param Type of member {@link second}. - * - * @reference http://www.cplusplus.com/reference/utility/pair - * @author Jeongho Nam - */ - class Pair implements IComparable> { - /** - *

    A first value in the Pair.

    - */ - first: T1; - /** - *

    A second value in the Pair.

    - */ - second: T2; - /** - *

    Construct from pair values.

    - * - * @param first The first value of the Pair - * @param second The second value of the Pair - */ - constructor(first: T1, second: T2); - /** - *

    Whether a Pair is equal with the Pair.

    - *

    Compare each first and second value of two Pair(s) and returns whether they are equal or not.

    - * - *

    If stored key and value in a Pair are not number or string but an object like a class or struct, - * the comparison will be executed by a member method (SomeObject)::equal_to(). If the object does not have - * the member method equal_to(), only address of pointer will be compared.

    - * - * @param obj A Map to compare - * @return Indicates whether equal or not. - */ - equals(pair: Pair): boolean; - /** - * @inheritdoc - */ - less(pair: Pair): boolean; - } - /** - *

    Construct {@link Pair} object.

    - * - *

    Constructs a {@link Pair} object with its {@link Pair.first first} element set to x and its - * {@link Pair.second second} element set to y.

    - * - *

    The template types can be implicitly deduced from the arguments passed to {@link make_pair}.

    - * - *

    {@link Pair} objects can be constructed from other {@link Pair} objects containing different types, if the - * respective types are implicitly convertible.

    - * - * @param x Value for member {@link Pair.first first}. - * @param y Value for member {@link Pair.second second}. - * - * @return A {@link Pair} object whose elements {@link Pair.first first} and {@link Pair.second second} are set to - * x and y respectivelly. - */ - function make_pair(x: T1, y: T2): Pair; -} -declare namespace std { - /** - * Type definition of {@link Vector} and it's the original name used in C++. - */ - export import vector = Vector; - /** - * Type definition of {@link List} and it's the original name used in C++. - */ - export import list = List; - /** - * Type definition of {@link Deque} and it's the original name used in C++. - */ - export import deque = Deque; - /** - * Type definition of {@link Stack} and it's the original name used in C++. - */ - type stack = Stack; - /** - * Type definition of {@link Queue} and it's the original name used in C++. - */ - type queue = Queue; - /** - * Type definition of {@link PriorityQueue} and it's the original name used in C++. - */ - type priority_queue = PriorityQueue; - var stack: typeof Stack; - var queue: typeof Queue; - var priority_queue: typeof PriorityQueue; - /** - * Type definition of {@link TreeSet} and it's the original name used in C++. - */ - export import set = TreeSet; - /** - * Type definition of {@link TreeMultiSet} and it's the original name used in C++. - */ - export import multiset = TreeMultiSet; - /** - * Type definition of {@link HashSet} and it's the original name used in C++. - */ - export import unordered_set = HashSet; - /** - * Type definition of {@link HashMultiSet} and it's the original name used in C++. - */ - export import unordered_multiset = HashMultiSet; - /** - * Type definition of {@link TreeMap} and it's the original name used in C++. - */ - export import map = TreeMap; - /** - * Type definition of {@link TreeMultiMap} and it's the original name used in C++. - */ - export import multimap = TreeMultiMap; - /** - * Type definition of {@link HashMap} and it's the original name used in C++. - */ - export import unordered_map = HashMap; - /** - * Type definition of {@link HashMultiMap} and it's the original name used in C++. - */ - export import unordered_multimap = HashMultiMap; - type exception = Exception; - type logic_error = LogicError; - type domain_error = DomainError; - type invalid_argument = InvalidArgument; - type length_error = LengthError; - type out_of_range = OutOfRange; - type runtime_error = RuntimeError; - type overflow_error = OverflowError; - type underflow_error = UnderflowError; - type range_error = RangeError; - type system_error = SystemError; - type error_category = ErrorCategory; - type error_condition = ErrorCondition; - type error_code = ErrorCode; - var exception: typeof Exception; - var logic_error: typeof LogicError; - var domain_error: typeof DomainError; - var invalid_argument: typeof InvalidArgument; - var length_error: typeof LengthError; - var out_of_range: typeof OutOfRange; - var runtime_error: typeof RuntimeError; - var overflow_error: typeof OverflowError; - var underflow_error: typeof UnderflowError; - var range_error: typeof RangeError; - var system_error: typeof SystemError; - var error_category: typeof ErrorCategory; - var error_condition: typeof ErrorCondition; - var error_code: typeof ErrorCode; -} +} \ No newline at end of file diff --git a/uikit/tslint.json b/uikit/tslint.json index 192203ab54..377cc837d4 100644 --- a/uikit/tslint.json +++ b/uikit/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/uikit/uikit-tests.ts b/uikit/uikit-tests.ts index 200a7a470f..5a28b61682 100644 --- a/uikit/uikit-tests.ts +++ b/uikit/uikit-tests.ts @@ -2,7 +2,7 @@ function testDropdown() { UIkit.dropdown("#parent"); UIkit.dropdown($("#parent")); - let options: UIkit.DropdownOptions = { + const options: UIkit.DropdownOptions = { pos: 'bottom-center', mode: 'click', remaintime: 150, @@ -24,7 +24,7 @@ function testDropdown() { function testModal() { UIkit.modal.alert("Attention!"); - let options: UIkit.ModalOptions = { + const options: UIkit.ModalOptions = { keyboard: true, bgclose: true, minScrollHeight: 150, @@ -37,7 +37,7 @@ function testModal() { UIkit.modal.confirm("Are you sure?", () => {}, () => {}, {}); UIkit.modal.confirm("Are you sure?", () => {}, {}); - UIkit.modal.prompt("Name:", 'value', function (newvalue:string) { + UIkit.modal.prompt("Name:", 'value', (newvalue: string) => { // will be executed on submit. }); var modal = UIkit.modal.blockUI("Any content..."); @@ -62,11 +62,11 @@ function testLightBox() { var element = "#group"; var lightbox = UIkit.lightbox(element, {/* options */}); var lightbox2 = UIkit.lightbox.create([ - {source: 'http://url/to/video.mp4', 'type': 'video'}, - {'source': 'http://url/to/image.jpg', 'type': 'image'} + {source: 'http://url/to/video.mp4', type: 'video'}, + {source: 'http://url/to/image.jpg', type: 'image'} ]); lightbox2.show(); - var lightbox3 = UIkit.lightbox(element) + var lightbox3 = UIkit.lightbox(element); } function testAutoComplete() { @@ -83,20 +83,20 @@ function testHtmlEditor() { } function testSlider() { - var slider = UIkit.slider("element", {}) + var slider = UIkit.slider("element", {}); } function testSlideSet() { - var slideset = UIkit.slideset("element", {}) + var slideset = UIkit.slideset("element", {}); } function testSlideShow() { - var slideshow = UIkit.slideshow("element", {}) + var slideshow = UIkit.slideshow("element", {}); } function testParallax() { - var parallax = UIkit.parallax("element", {}) + var parallax = UIkit.parallax("element", {}); } function testAccordion() { - var accordion = UIkit.accordion("element", {}) + var accordion = UIkit.accordion("element", {}); } @@ -121,7 +121,7 @@ function testNotify() { function testSearch() { - var search = UIkit.search("element", {}) + var search = UIkit.search("element", {}); } function testNestable() { @@ -134,15 +134,15 @@ function testStick() { var sticky = UIkit.sticky('element', {}); } function testTimePicker() { - var timepicker = UIkit.timepicker('element', {}) + var timepicker = UIkit.timepicker('element', {}); } function testTooltip() { - var tooltip = UIkit.tooltip('element', {}) + var tooltip = UIkit.tooltip('element', {}); } function testUpload() { - $(function(){ + $(() => { var progressbar = $("#progressbar"), bar = progressbar.find('.uk-progress-bar'), @@ -152,25 +152,25 @@ function testUpload() { allow : '*.(jpg|jpeg|gif|png)', // allow only images - loadstart: function() { + loadstart() { bar.css("width", "0%").text("0%"); progressbar.removeClass("uk-hidden"); }, - progress: function(percent: number) { + progress(percent: number) { percent = Math.ceil(percent); - bar.css("width", percent+"%").text(percent+"%"); + bar.css("width", percent + "%").text(percent + "%"); }, - allcomplete: function(response: any) { + allcomplete(response: any) { bar.css("width", "100%").text("100%"); - setTimeout(function(){ + setTimeout(() => { progressbar.addClass("uk-hidden"); }, 250); - alert("Upload Completed") + alert("Upload Completed"); } }; @@ -185,15 +185,15 @@ function testUpload() { allow: '*.(jpg|jpeg|gif|png)', // allow only images - loadstart: function () { + loadstart: () => { }, - progress: function (percent:number) { + progress: (percent: number) => { }, - allcomplete: function (response:any) { + allcomplete: (response: any) => { } }); @@ -203,15 +203,15 @@ function testUpload() { allow: '*.(jpg|jpeg|gif|png)', // allow only images - loadstart: function () { + loadstart: () => { }, - progress: function (percent:number) { + progress: (percent: number) => { }, - allcomplete: function (response:any) { + allcomplete: (response: any) => { } }); diff --git a/universal-router/index.d.ts b/universal-router/index.d.ts index 6acba5c179..e9f64a1846 100644 --- a/universal-router/index.d.ts +++ b/universal-router/index.d.ts @@ -1,70 +1,68 @@ -// Type definitions for universal-router +// Type definitions for universal-router 1.2 // Project: https://github.com/kriasoft/universal-router -// Definitions by: Jack Moore +// 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; - } +/** + * 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; - } +/** + * 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; - } +/** + * 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; - } +/** + * 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[]; +/** + * 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 = Array>; - /** - * 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 +/** + * 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; diff --git a/universal-router/tsconfig.json b/universal-router/tsconfig.json index 18025f5a22..ca76eb8955 100644 --- a/universal-router/tsconfig.json +++ b/universal-router/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/universal-router/tslint.json b/universal-router/tslint.json new file mode 100644 index 0000000000..f05741c59b --- /dev/null +++ b/universal-router/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/universal-router/universal-router-tests.ts b/universal-router/universal-router-tests.ts index 2d8870952c..5964ee1a90 100644 --- a/universal-router/universal-router-tests.ts +++ b/universal-router/universal-router-tests.ts @@ -59,7 +59,7 @@ const routes5 = [ async action(ctx: ActionContext, { username }: Params) { const waitable = async (name: string) => { console.log(`Welcome ${name}`); - } + }; await waitable(username); } } diff --git a/update-notifier/tslint.json b/update-notifier/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/update-notifier/tslint.json +++ b/update-notifier/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/url-join/index.d.ts b/url-join/index.d.ts index 82715e643e..3dc87d456f 100644 --- a/url-join/index.d.ts +++ b/url-join/index.d.ts @@ -1,12 +1,15 @@ // Type definitions for url-join v0.8.3 // Project: https://github.com/jfromaniello/url-join -// Definitions by: Rogier Schouten +// Definitions by: Rogier Schouten , Mike Deverell // Definitions: https://github.com/borisyankov/DefinitelyTyped /** * Join all arguments together and normalize the resulting url. * This works similar to path.join but you shouldn't use path.join for urls since it will work different depending of the operative systems but also doesn't work for some cases. - */ -declare function urljoin(...parts: string[]): string; + */ -export = urljoin; +declare var urljoin: (...parts: string[]) => string; + +declare module "url-join" { + export = urljoin; +} diff --git a/url-join/url-join-tests.ts b/url-join/url-join-tests.ts index 182b44359e..2b512bc6d4 100644 --- a/url-join/url-join-tests.ts +++ b/url-join/url-join-tests.ts @@ -1,4 +1,5 @@ - import urljoin = require("url-join"); +import * as urljoin2 from "url-join"; const s: string = urljoin("foo", "bar", "baz"); +const s2: string = urljoin2("foo", "bar", "baz"); diff --git a/usb/tslint.json b/usb/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/usb/tslint.json +++ b/usb/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/usb/usb-tests.ts b/usb/usb-tests.ts index f1963307fc..31e287c5b8 100644 --- a/usb/usb-tests.ts +++ b/usb/usb-tests.ts @@ -81,7 +81,7 @@ inEndpoint.direction = "in"; inEndpoint.transferType = 1; inEndpoint.timeout = 1; inEndpoint.descriptor = endpointDesc; -const xferInEndpoint: usb.InEndpoint = inEndpoint.transfer(1, (error: string, data: Buffer) => { return inEndpoint; }); +const xferInEndpoint: usb.InEndpoint = inEndpoint.transfer(1, (error: string, data: Buffer) => inEndpoint); inEndpoint.startPoll(1, 1); inEndpoint.stopPoll(() => null); @@ -95,7 +95,7 @@ outEndpoint.transferWithZLP(new Buffer([]), (error: string) => null); const findByDevice: usb.Device = usb.findByIds(1, 1); usb.on("hey", (device: usb.Device) => null); -const deviceList: Array = usb.getDeviceList(); +const deviceList: usb.Device[] = usb.getDeviceList(); usb.setDebugLevel(1); const CHECK_LIBUSB_CLASS_PER_INTERFACE: number = usb.LIBUSB_CLASS_PER_INTERFACE; diff --git a/user-home/user-home-tests.ts b/user-home/user-home-tests.ts index 41ef1e31a8..056a31095e 100644 --- a/user-home/user-home-tests.ts +++ b/user-home/user-home-tests.ts @@ -1,4 +1,4 @@ import userHome = require('user-home'); console.log(userHome); -//=> '/Users/sindresorhus' \ No newline at end of file +// => '/Users/sindresorhus' \ No newline at end of file diff --git a/vectorious/index.d.ts b/vectorious/index.d.ts index 63b53d20bf..c68e87236c 100644 --- a/vectorious/index.d.ts +++ b/vectorious/index.d.ts @@ -269,6 +269,8 @@ export class Vector { export class Matrix { T: Matrix; + + shape: number[]; /** * @method constructor @@ -586,4 +588,4 @@ export class Matrix { public toArray (): number[][]; } -export class BLAS {} \ No newline at end of file +export class BLAS {} diff --git a/verror/tslint.json b/verror/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/verror/tslint.json +++ b/verror/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/videojs/index.d.ts b/videojs/index.d.ts index 9e4156ece6..5b894b0912 100644 --- a/videojs/index.d.ts +++ b/videojs/index.d.ts @@ -1,63 +1,62 @@ -// Type definitions for Video.js +// Type definitions for Video.js 5.16 // Project: https://github.com/zencoder/video-js // Definitions by: Vincent Bortone // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// The Video.js API allows you to interact with the video through Javascript, whether the browser is playing the video through HTML5 video, Flash, or any other supported playback technologies. +// The Video.js API allows you to interact with the video through +// Javascript, whether the browser is playing the video through HTML5 +// video, Flash, or any other supported playback technologies. -interface VideoJSOptions { - techOrder?: string[]; - html5?: Object; - width?: number; - height?: number; - defaultVolume?: number; - children?: Object; - controls?: boolean; - src?: string; - autoplay?: boolean; - preload?: string; +declare function videojs(id: any, options?: videojs.PlayerOptions, ready?: () => void): videojs.Player; +export = videojs; +export as namespace videojs; + +declare namespace videojs { + + interface PlayerOptions { + techOrder?: string[]; + html5?: any; + width?: number; + height?: number; + defaultVolume?: number; + children?: string[]; + controls?: boolean; + src?: string; + autoplay?: boolean; + preload?: string; + } + + interface Source { + type: string; + src: string; + } + + interface Player { + play(): Player; + pause(): Player; + paused(): boolean; + src(newSource: string | Source | Source[]): Player; + currentTime(seconds: number): Player; + currentTime(): number; + duration(): number; + buffered(): TimeRanges; + bufferedPercent(): number; + volume(percentAsDecimal: number): TimeRanges; + volume(): number; + width(): number; + width(pixels: number): Player; + height(): number; + height(pixels: number): Player; + size(width: number, height: number): Player; + requestFullScreen(): Player; + cancelFullScreen(): Player; + ready(callback: (this: Player) => void ): Player; + on(eventName: string, callback: (eventObject: Event) => void ): void; + off(eventName?: string, callback?: (eventObject: Event) => void ): void; + dispose(): void; + addRemoteTextTrack(options: {}): HTMLTrackElement; + removeRemoteTextTrack(track: HTMLTrackElement): void; + poster(val?: string): string | Player; + playbackRate(rate?: number): number; + } } - -interface VideoJSSource { - type: string; - src: string; -} - -interface VideoJSPlayer { - play(): VideoJSPlayer; - pause(): VideoJSPlayer; - paused(): boolean; - src(newSource: string): VideoJSPlayer; - src(newSource: VideoJSSource): VideoJSPlayer; - src(newSource: VideoJSSource[]): VideoJSPlayer; - currentTime(seconds: number): VideoJSPlayer; - currentTime(): number; - duration(): number; - buffered(): TimeRanges; - bufferedPercent(): number; - volume(percentAsDecimal: number): TimeRanges; - volume(): number; - width(): number; - width(pixels: number): VideoJSPlayer; - height(): number; - height(pixels: number): VideoJSPlayer; - size(width: number, height: number): VideoJSPlayer; - requestFullScreen(): VideoJSPlayer; - cancelFullScreen(): VideoJSPlayer; - 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; - poster(val?: string) : string|VideoJSPlayer; - playbackRate(rate?: number) : number; -} - -interface VideoJSStatic { - (id: any, options?: VideoJSOptions, ready?: () => void): VideoJSPlayer; -} - -declare var videojs:VideoJSStatic; diff --git a/videojs/tsconfig.json b/videojs/tsconfig.json index b9feff990e..f8dd93e0df 100644 --- a/videojs/tsconfig.json +++ b/videojs/tsconfig.json @@ -6,8 +6,8 @@ "dom" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/videojs/tslint.json b/videojs/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/videojs/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/videojs/videojs-tests.ts b/videojs/videojs-tests.ts index 6b2c90184e..6f9907ea1c 100644 --- a/videojs/videojs-tests.ts +++ b/videojs/videojs-tests.ts @@ -1,35 +1,33 @@ // Tests for Video.js API +import * as videojs from 'videojs'; -videojs("example_video_1").ready(function(){ - - var myPlayer:VideoJSPlayer = this; - +videojs("example_video_1").ready(function() { // EXAMPLE: Start playing the video. - myPlayer.play(); + this.play(); - myPlayer.pause(); + this.pause(); - var isPaused: boolean = myPlayer.paused(); - var isPlaying: boolean = !myPlayer.paused(); + var isPaused: boolean = this.paused(); + var isPlaying: boolean = !this.paused(); - myPlayer.src("http://www.example.com/path/to/video.mp4"); + this.src("http://www.example.com/path/to/video.mp4"); - myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }); + this.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }); - myPlayer.src([ + this.src([ { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }, { type: "video/webm", src: "http://www.example.com/path/to/video.webm" }, { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" } ]); - var whereYouAt: number = myPlayer.currentTime(); + var whereYouAt: number = this.currentTime(); - myPlayer.currentTime(120); // 2 minutes into the video + this.currentTime(120); // 2 minutes into the video - var howLongIsThis: number = myPlayer.duration(); + var howLongIsThis: number = this.duration(); - var bufferedTimeRange: TimeRanges = myPlayer.buffered(); + var bufferedTimeRange: TimeRanges = this.buffered(); // Number of different ranges of time have been buffered. Usually 1. var numberOfRanges: number = bufferedTimeRange.length; @@ -43,31 +41,44 @@ videojs("example_video_1").ready(function(){ // Length in seconds of the first time range var firstRangeLength: number = firstRangeEnd - firstRangeStart; - var howMuchIsDownloaded: number = myPlayer.bufferedPercent(); + var howMuchIsDownloaded: number = this.bufferedPercent(); - var howLoudIsIt: number = myPlayer.volume(); + var howLoudIsIt: number = this.volume(); - myPlayer.volume(0.5); // Set volume to half + this.volume(0.5); // Set volume to half - var howWideIsIt: number = myPlayer.width(); + var howWideIsIt: number = this.width(); - myPlayer.width(640); + this.width(640); - var howTallIsIt: number = myPlayer.height(); + var howTallIsIt: number = this.height(); - myPlayer.height(480); + this.height(480); - myPlayer.size(640,480); + this.size(640, 480); - myPlayer.requestFullScreen(); + this.requestFullScreen(); - myPlayer.cancelFullScreen(); + testEvents(this); +}); - - var myFunc = function(){ - var myPlayer: VideoJSPlayer = this; +function testEvents(myPlayer: videojs.Player) { + const myFunc = function(this: videojs.Player) { // Do something when the event is fired }; - //myPlayer.addEvent("volumechange", myFunc); - //myPlayer.removeEvent("volumechange", myFunc); -}); + myPlayer.on("error", myFunc); + // Removes the specified listener only. + myPlayer.off("error", myFunc); + + + const myFuncWithArg = function(this: videojs.Player, e: Event) { + // Do something when the event is fired + }; + myPlayer.on("volumechange", myFuncWithArg); + // Removes all listeners for the given event type. + myPlayer.off("volumechange"); + + myPlayer.on("loadeddata", () => { /* Some handler. */ }); + // Removes all listeners. + myPlayer.off(); +} diff --git a/vinyl-fs/.editorconfig b/vinyl-fs/.editorconfig new file mode 100644 index 0000000000..831139084b --- /dev/null +++ b/vinyl-fs/.editorconfig @@ -0,0 +1,3 @@ +[*.ts] +indent_style = space +indent_size = 3 diff --git a/vinyl-fs/index.d.ts b/vinyl-fs/index.d.ts index 350ee527b5..4fa6101b69 100644 --- a/vinyl-fs/index.d.ts +++ b/vinyl-fs/index.d.ts @@ -1,25 +1,26 @@ -// Type definitions for vinyl-fs +// Type definitions for vinyl-fs 2.4 // Project: https://github.com/wearefractal/vinyl-fs // Definitions by: vvakame // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// -/// declare global { namespace NodeJS { interface WritableStream { - write(buffer: any/* Vinyl.File */, cb?: Function): boolean; + write(buffer: any/* Vinyl.File */, cb?: (err?: Error) => void): boolean; } } } -import _events = require("events"); -import File = require("vinyl"); -import globStream = require("glob-stream"); +import * as _events from 'events'; +import * as File from 'vinyl'; +import * as globStream from 'glob-stream'; + +interface SrcOptions extends globStream.Options { + /** Prevents stream from emitting an error when file not found. */ + allowEmpty?: boolean; -interface ISrcOptions extends globStream.Options { /** Specifies the working directory the folder is relative to */ cwd?: string; @@ -62,7 +63,7 @@ interface ISrcOptions extends globStream.Options { * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) * @param opt Options Vinyl source options, changes the way the files are read, found, or stored in the vinyl stream */ -declare function src(globs: string|string[], opt?: ISrcOptions): NodeJS.ReadWriteStream; +declare function src(globs: string|string[], opt?: SrcOptions): NodeJS.ReadWriteStream; /** * This is just a glob-watcher @@ -80,7 +81,15 @@ declare function watch(globs: string|string[], cb?: (outEvt: { type: any; path: * Globs are executed in order, so negations should follow positive globs * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) */ -declare function watch(globs: string|string[], opt?: { interval?: number; debounceDelay?: number; cwd?: string; maxListeners?: Function; }, cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; +declare function watch( + globs: string|string[], + opt?: { + interval?: number; + debounceDelay?: number; + cwd?: string; + maxListeners?: () => number; + }, + cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; /** * On write the stream will save the vinyl File to disk at the folder/cwd specified. diff --git a/vinyl-fs/tsconfig.json b/vinyl-fs/tsconfig.json index 60247086b9..d8cea65d47 100644 --- a/vinyl-fs/tsconfig.json +++ b/vinyl-fs/tsconfig.json @@ -1,22 +1,22 @@ { - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "vinyl-fs-tests.ts" - ] -} \ No newline at end of file + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "vinyl-fs-tests.ts" + ] +} diff --git a/vinyl-fs/tslint.json b/vinyl-fs/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/vinyl-fs/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/vinyl-fs/vinyl-fs-tests.ts b/vinyl-fs/vinyl-fs-tests.ts index 795b38b4aa..33d031f521 100644 --- a/vinyl-fs/vinyl-fs-tests.ts +++ b/vinyl-fs/vinyl-fs-tests.ts @@ -1,12 +1,9 @@ -/// -/// - // from src -import vfs = require('vinyl-fs'); +import * as vfs from 'vinyl-fs'; -import path = require('path'); -import fs = require('fs'); // require('graceful-fs'); +import * as path from 'path'; +import * as fs from 'fs'; // require('graceful-fs'); // import bufEqual = require('buffer-equal'); declare var bufEqual: any; @@ -16,22 +13,22 @@ import File = require('vinyl'); // var spies = require('./spy'); declare var spies: any; -import should = require('should'); -require('mocha'); +import * as should from 'should'; +import 'mocha'; declare var gulp: any; declare var bufferStream: any; -var dataWrap = function (fn: any) { - return function (data: any, enc: any, cb: any) { +var dataWrap = (fn: any) => { + return (data: any, enc: any, cb: any) => { fn(data); cb(); }; }; -describe('source stream', function () { +describe('source stream', () => { - it('should explode on invalid glob (empty)', function (done) { + it('should explode on invalid glob (empty)', done => { var stream: any; try { stream = gulp.src(); @@ -42,7 +39,7 @@ describe('source stream', function () { } }); - it('should explode on invalid glob (number)', function (done) { + it('should explode on invalid glob (number)', done => { var stream: any; try { stream = gulp.src(123); @@ -53,7 +50,7 @@ describe('source stream', function () { } }); - it('should explode on invalid glob (empty array)', function (done) { + it('should explode on invalid glob (empty array)', done => { var stream: any; try { stream = gulp.src([]); @@ -64,7 +61,7 @@ describe('source stream', function () { } }); - it('should pass through writes', function (done) { + it('should pass through writes', done => { var expectedPath = path.join(__dirname, "./fixtures/test.coffee"); var expectedContent = fs.readFileSync(expectedPath); @@ -75,7 +72,7 @@ describe('source stream', function () { contents: expectedContent }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); bufEqual(buffered[0].contents, expectedContent).should.equal(true); @@ -91,11 +88,11 @@ describe('source stream', function () { stream.end(); }); - it('should glob a file with default settings', function (done) { + it('should glob a file with default settings', done => { var expectedPath = path.join(__dirname, "./fixtures/test.coffee"); var expectedContent = fs.readFileSync(expectedPath); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); should.exist(buffered[0].stat); buffered[0].path.should.equal(expectedPath); @@ -111,11 +108,11 @@ describe('source stream', function () { stream.pipe(bufferStream); }); - it('should glob a file with default settings and relative cwd', function (done) { + it('should glob a file with default settings and relative cwd', done => { var expectedPath = path.join(__dirname, "./fixtures/test.coffee"); var expectedContent = fs.readFileSync(expectedPath); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); should.exist(buffered[0].stat); buffered[0].path.should.equal(expectedPath); @@ -131,10 +128,10 @@ describe('source stream', function () { stream.pipe(bufferStream); }); - it('should glob a directory with default settings', function (done) { + it('should glob a directory with default settings', done => { var expectedPath = path.join(__dirname, "./fixtures/wow"); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].path.should.equal(expectedPath); buffered[0].isNull().should.equal(true); @@ -149,11 +146,11 @@ describe('source stream', function () { stream.pipe(bufferStream); }); - it('should glob a file with with no contents', function (done) { + it('should glob a file with with no contents', done => { var expectedPath = path.join(__dirname, "./fixtures/test.coffee"); var expectedContent = fs.readFileSync(expectedPath); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].path.should.equal(expectedPath); buffered[0].isNull().should.equal(true); @@ -168,22 +165,22 @@ describe('source stream', function () { stream.pipe(bufferStream); }); - it('should glob a file with streaming contents', function (done) { + it('should glob a file with streaming contents', done => { var expectedPath = path.join(__dirname, "./fixtures/test.coffee"); var expectedContent = fs.readFileSync(expectedPath); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); should.exist(buffered[0].stat); buffered[0].path.should.equal(expectedPath); buffered[0].isStream().should.equal(true); var contentBuffer = new Buffer([]); - var contentBufferStream = through(dataWrap(function (data: any) { + var contentBufferStream = through(dataWrap((data: any) => { contentBuffer = Buffer.concat([contentBuffer, data]); })); buffered[0].contents.pipe(contentBufferStream); - buffered[0].contents.once('end', function () { + buffered[0].contents.once('end', () => { bufEqual(contentBuffer, expectedContent); done(); }); @@ -210,28 +207,28 @@ import rimraf = require('rimraf'); // var File = require('vinyl'); // var should = require('should'); -require('mocha'); +// require('mocha'); -var wipeOut = function (cb: any) { +var wipeOut = (cb: any) => { rimraf(path.join(__dirname, "./out-fixtures/"), cb); }; -var dataWrap = function (fn: any) { - return function (data: any, enc: any, cb: any) { +var dataWrap = (fn: any) => { + return (data: any, enc: any, cb: any) => { fn(data); cb(); }; }; -var realMode = function (n: any) { +var realMode = (n: any) => { return n & parseInt("07777", 8); }; -describe('dest stream', function () { +describe('dest stream', () => { beforeEach(wipeOut); afterEach(wipeOut); - it('should explode on invalid folder', function (done) { + it('should explode on invalid folder', done => { var stream: any; try { stream = gulp.dest(); @@ -242,7 +239,7 @@ describe('dest stream', function () { } }); - it('should pass through writes with cwd', function (done) { + it('should pass through writes with cwd', done => { var inputPath = path.join(__dirname, "./fixtures/test.coffee"); var expectedFile = new File({ @@ -252,7 +249,7 @@ describe('dest stream', function () { contents: null }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); done(); @@ -267,7 +264,7 @@ describe('dest stream', function () { stream.end(); }); - it('should pass through writes with default cwd', function (done) { + it('should pass through writes with default cwd', done => { var inputPath = path.join(__dirname, "./fixtures/test.coffee"); var expectedFile = new File({ @@ -277,7 +274,7 @@ describe('dest stream', function () { contents: null }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); done(); @@ -292,7 +289,7 @@ describe('dest stream', function () { stream.end(); }); - it('should not write null files', function (done) { + it('should not write null files', done => { var inputPath = path.join(__dirname, "./fixtures/test.coffee"); var inputBase = path.join(__dirname, "./fixtures/"); var expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); @@ -306,7 +303,7 @@ describe('dest stream', function () { contents: null }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); @@ -325,7 +322,7 @@ describe('dest stream', function () { stream.end(); }); - it('should write buffer files to the right folder with relative cwd', function (done) { + it('should write buffer files to the right folder with relative cwd', done => { var inputPath = path.join(__dirname, "./fixtures/test.coffee"); var inputBase = path.join(__dirname, "./fixtures/"); var expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); @@ -340,7 +337,7 @@ describe('dest stream', function () { contents: expectedContents }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); @@ -360,7 +357,7 @@ describe('dest stream', function () { stream.end(); }); - it('should write buffer files to the right folder', function (done) { + it('should write buffer files to the right folder', done => { var inputPath = path.join(__dirname, "./fixtures/test.coffee"); var inputBase = path.join(__dirname, "./fixtures/"); var expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); @@ -374,12 +371,12 @@ describe('dest stream', function () { cwd: __dirname, path: inputPath, contents: expectedContents, - stat: { + stat: { mode: expectedMode } }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); @@ -400,7 +397,7 @@ describe('dest stream', function () { stream.end(); }); - it('should write streaming files to the right folder', function (done) { + it('should write streaming files to the right folder', done => { var inputPath = path.join(__dirname, "./fixtures/test.coffee"); var inputBase = path.join(__dirname, "./fixtures/"); var expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); @@ -415,12 +412,12 @@ describe('dest stream', function () { cwd: __dirname, path: inputPath, contents: contentStream, - stat: { + stat: { mode: expectedMode } }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); @@ -438,14 +435,14 @@ describe('dest stream', function () { bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); stream.pipe(bufferStream); stream.write(expectedFile); - setTimeout(function () { + setTimeout(() => { contentStream.write(expectedContents); contentStream.end(); }, 100); stream.end(); }); - it('should write directories to the right folder', function (done) { + it('should write directories to the right folder', done => { var inputPath = path.join(__dirname, "./fixtures/test"); var inputBase = path.join(__dirname, "./fixtures/"); var expectedPath = path.join(__dirname, "./out-fixtures/test"); @@ -458,15 +455,13 @@ describe('dest stream', function () { cwd: __dirname, path: inputPath, contents: null, - stat: { - isDirectory: function () { - return true; - }, + stat: { + isDirectory: () => true, mode: expectedMode } }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); @@ -487,7 +482,7 @@ describe('dest stream', function () { stream.end(); }); - it('should allow piping multiple dests in streaming mode', function (done) { + it('should allow piping multiple dests in streaming mode', done => { var inputPath1 = path.join(__dirname, "./out-fixtures/multiple-first"); var inputPath2 = path.join(__dirname, "./out-fixtures/multiple-second"); var inputBase = path.join(__dirname, "./out-fixtures/"); @@ -495,20 +490,20 @@ describe('dest stream', function () { var stream1 = vfs.dest('./out-fixtures/', { cwd: __dirname }); var stream2 = vfs.dest('./out-fixtures/', { cwd: __dirname }); var content = fs.readFileSync(srcPath); - var rename = through.obj(function (file: any, _: any, next: any) { + var rename = through.obj((file: any, _: any, next: any) => { file.path = inputPath2; this.push(file); next(); }); - stream1.on('data', function (file: any) { + stream1.on('data', (file: any) => { file.path.should.equal(inputPath1); - }) + }); stream1.pipe(rename).pipe(stream2); - stream2.on('data', function (file: any) { + stream2.on('data', (file: any) => { file.path.should.equal(inputPath2); - }).once('end', function () { + }).once('end', () => { fs.readFileSync(inputPath1, 'utf8').should.equal(content.toString()); fs.readFileSync(inputPath2, 'utf8').should.equal(content.toString()); done(); @@ -519,11 +514,11 @@ describe('dest stream', function () { path: inputPath1, cwd: __dirname, contents: content - }) + }); stream1.write(file); stream1.end(); - }) + }); }); @@ -535,29 +530,29 @@ describe('dest stream', function () { var chmodSpy = spies.chmodSpy; var statSpy = spies.statSpy; -var wipeOut = function (cb: any) { +var wipeOut = (cb: any) => { rimraf(path.join(__dirname, './out-fixtures/'), cb); spies.setError('false'); statSpy.reset(); chmodSpy.reset(); }; -var dataWrap = function (fn: any) { - return function (data: any, enc: any, cb: any) { +var dataWrap = (fn: any) => { + return (data: any, enc: any, cb: any) => { fn(data); cb(); }; }; -var realMode = function (n: any) { +var realMode = (n: any) => { return n & parseInt("07777", 8); }; -describe('symlink stream', function () { +describe('symlink stream', () => { beforeEach(wipeOut); afterEach(wipeOut); - it('should explode on invalid folder', function (done: any) { + it('should explode on invalid folder', (done: any) => { var stream: any; try { stream = gulp.symlink(); @@ -568,7 +563,7 @@ describe('symlink stream', function () { } }); - it('should pass through writes with cwd', function (done) { + it('should pass through writes with cwd', done => { var inputPath = path.join(__dirname, './fixtures/test.coffee'); var expectedFile = new File({ @@ -578,7 +573,7 @@ describe('symlink stream', function () { contents: null }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); done(); @@ -593,7 +588,7 @@ describe('symlink stream', function () { stream.end(); }); - it('should pass through writes with default cwd', function (done) { + it('should pass through writes with default cwd', done => { var inputPath = path.join(__dirname, './fixtures/test.coffee'); var expectedFile = new File({ @@ -603,7 +598,7 @@ describe('symlink stream', function () { contents: null }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); done(); @@ -618,7 +613,7 @@ describe('symlink stream', function () { stream.end(); }); - it('should make link to the right folder with relative cwd', function (done) { + it('should make link to the right folder with relative cwd', done => { var inputPath = path.join(__dirname, './fixtures/test.coffee'); var inputBase = path.join(__dirname, './fixtures/'); var expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); @@ -633,7 +628,7 @@ describe('symlink stream', function () { contents: expectedContents }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); @@ -654,7 +649,7 @@ describe('symlink stream', function () { stream.end(); }); - it('should write buffer files to the right folder with function and relative cwd', function (done) { + it('should write buffer files to the right folder with function and relative cwd', done => { var inputPath = path.join(__dirname, './fixtures/test.coffee'); var inputBase = path.join(__dirname, './fixtures/'); var expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); @@ -669,7 +664,7 @@ describe('symlink stream', function () { contents: expectedContents }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); @@ -681,7 +676,7 @@ describe('symlink stream', function () { done(); }; - var stream = vfs.symlink(function (file) { + var stream = vfs.symlink(file => { should.exist(file); file.should.equal(expectedFile); return './out-fixtures'; @@ -694,7 +689,7 @@ describe('symlink stream', function () { stream.end(); }); - it('should write buffer files to the right folder', function (done) { + it('should write buffer files to the right folder', done => { var inputPath = path.join(__dirname, './fixtures/test.coffee'); var inputBase = path.join(__dirname, './fixtures/'); var expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); @@ -708,12 +703,12 @@ describe('symlink stream', function () { cwd: __dirname, path: inputPath, contents: expectedContents, - stat: { + stat: { mode: expectedMode } }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); @@ -734,7 +729,7 @@ describe('symlink stream', function () { stream.end(); }); - it('should write streaming files to the right folder', function (done) { + it('should write streaming files to the right folder', done => { var inputPath = path.join(__dirname, './fixtures/test.coffee'); var inputBase = path.join(__dirname, './fixtures/'); var expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); @@ -749,12 +744,12 @@ describe('symlink stream', function () { cwd: __dirname, path: inputPath, contents: contentStream, - stat: { + stat: { mode: expectedMode } }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); @@ -772,14 +767,14 @@ describe('symlink stream', function () { bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); stream.pipe(bufferStream); stream.write(expectedFile); - setTimeout(function () { + setTimeout(() => { contentStream.write(expectedContents); contentStream.end(); }, 100); stream.end(); }); - it('should write directories to the right folder', function (done) { + it('should write directories to the right folder', done => { var inputPath = path.join(__dirname, './fixtures/wow'); var inputBase = path.join(__dirname, './fixtures/'); var expectedPath = path.join(__dirname, './out-fixtures/wow'); @@ -792,15 +787,13 @@ describe('symlink stream', function () { cwd: __dirname, path: inputPath, contents: null, - stat: { - isDirectory: function () { - return true; - }, + stat: { + isDirectory: () => true, mode: expectedMode } }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); @@ -821,7 +814,7 @@ describe('symlink stream', function () { stream.end(); }); - it('should use different modes for files and directories', function (done) { + it('should use different modes for files and directories', done => { var inputBase = path.join(__dirname, './fixtures'); var inputPath = path.join(__dirname, './fixtures/wow/suchempty'); var expectedBase = path.join(__dirname, './out-fixtures/wow'); @@ -835,7 +828,7 @@ describe('symlink stream', function () { stat: fs.statSync(inputPath) }); - var onEnd = function () { + var onEnd = () => { realMode(fs.lstatSync(expectedBase).mode).should.equal(expectedDirMode); realMode(buffered[0].stat.mode).should.equal(expectedFileMode); done(); @@ -855,7 +848,7 @@ describe('symlink stream', function () { stream.end(); }); - it('should report IO errors', function (done) { + it('should report IO errors', done => { var inputPath = path.join(__dirname, './fixtures/test.coffee'); var inputBase = path.join(__dirname, './fixtures/'); var expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); @@ -869,7 +862,7 @@ describe('symlink stream', function () { cwd: __dirname, path: inputPath, contents: expectedContents, - stat: { + stat: { mode: expectedMode } }); @@ -878,19 +871,19 @@ describe('symlink stream', function () { fs.chmodSync(expectedBase, 0); var stream = vfs.symlink('./out-fixtures/', { cwd: __dirname }); - stream.on('error', function (err:any) { + stream.on('error', (err: any) => { err.code.should.equal('EACCES'); done(); }); stream.write(expectedFile); }); - ['end', 'finish'].forEach(function (eventName) { - it('should emit ' + eventName + ' event', function (done) { + ['end', 'finish'].forEach(eventName => { + it('should emit ' + eventName + ' event', done => { var srcPath = path.join(__dirname, './fixtures/test.coffee'); var stream = vfs.symlink('./out-fixtures/', { cwd: __dirname }); - stream.on(eventName, function () { + stream.on(eventName, () => { done(); }); @@ -904,7 +897,7 @@ describe('symlink stream', function () { stream.end(); }); }); - it('should check if it"s a vinyl file', function () { + it('should check if it"s a vinyl file', () => { var srcPath = path.join(__dirname, './fixtures/test.coffee'); var options = { path: srcPath, @@ -914,5 +907,5 @@ describe('symlink stream', function () { var file = new File(options); File.isVinyl(file).should.equal(true); File.isVinyl(options).should.equal(false); - }) + }); }); diff --git a/vis/index.d.ts b/vis/index.d.ts index 3ee00ba03a..b4e4c61923 100644 --- a/vis/index.d.ts +++ b/vis/index.d.ts @@ -1,6 +1,10 @@ // Type definitions for vis.js 4.17 // Project: https://github.com/almende/vis -// Definitions by: Michaël Bitard , Adrian Caballero , Severin , kaktus40 , Matthieu Maitre +// Definitions by: Michaël Bitard +// Adrian Caballero +// Severin +// kaktus40 +// Matthieu Maitre // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped type IdType = string | number; diff --git a/vis/tslint.json b/vis/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/vis/tslint.json +++ b/vis/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/vis/vis-tests.ts b/vis/vis-tests.ts index 804e69d96e..2b3b28fb7b 100644 --- a/vis/vis-tests.ts +++ b/vis/vis-tests.ts @@ -34,7 +34,7 @@ data.add([ ]); // subscribe to any change in the DataSet -data.on('*', function (event, properties, senderId) { +data.on('*', (event, properties, senderId) => { console.log('event', event, properties); }); @@ -54,8 +54,8 @@ console.log('item1', item1); // retrieve a filtered subset of the data var items = data.get({ - filter: function (item) { - return item.group == 1; + filter: (item) => { + return item.group === 1; } }); console.log('filtered items', items); @@ -77,7 +77,7 @@ console.log('formatted items', items); var data = new vis.DataSet(); // subscribe to any change in the DataSet -data.on('*', function (event, properties, senderId) { +data.on('*', (event, properties, senderId) => { console.log('event:', event, 'properties:', properties, 'senderId:', senderId); }); @@ -132,14 +132,14 @@ var dataset = new vis.DataSet(); // retrieve all items having a property group with value 2 var group2 = dataset.get({ - filter: function (item) { - return (item.group == 2); + filter: (item) => { + return (item.group === 2); } }); // retrieve all items having a property balance with a value above zero var positiveBalance = dataset.get({ - filter: function (item) { + filter: (item) => { return (item.balance > 0); } }); @@ -166,13 +166,10 @@ var edges = new vis.DataSet([ ]); // create a network -var container = document.getElementById('mynetwork'); +var container = document.getElementById('mynetwork'); // provide the data in the vis format -var data2 = { - nodes: nodes, - edges: edges -}; +var data2 = { nodes, edges }; var options = {}; // initialize your network! @@ -187,9 +184,9 @@ var options2 = { configure: { enabled: true, filter: 'nodes,edges', - container: container, + container, showButton: true } -} +}; network.setOptions(options2); \ No newline at end of file diff --git a/vkbeautify/tsconfig.json b/vkbeautify/tsconfig.json index 91709c37ae..2e38ec1be6 100644 --- a/vkbeautify/tsconfig.json +++ b/vkbeautify/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, diff --git a/vkbeautify/vkbeautify-tests.ts b/vkbeautify/vkbeautify-tests.ts index bc91ffad01..a7fd0c4839 100644 --- a/vkbeautify/vkbeautify-tests.ts +++ b/vkbeautify/vkbeautify-tests.ts @@ -2,21 +2,21 @@ import VKBeautify from 'vkbeautify'; /* * Beautifying - * + * * vkbeautify.xml(text [,indent_pattern]); * vkbeautify.json(text [,indent_pattern]); * vkbeautify.css(text [,indent_pattern]); * vkbeautify.sql(text [,indent_pattern]); - * + * * @text - String; text to beatufy; * @indent_pattern - Integer | String; * Integer: number of white spaces; * String: character string to visualize indentation ( can also be a set of white spaces ) */ -let exampleContent = "here-be-xml-json-css-or-sql-content-that-is-about-to-get-formatted"; +const exampleContent = "here-be-xml-json-css-or-sql-content-that-is-about-to-get-formatted"; -//xml +// xml function xmlWithDefault() { VKBeautify.xml(exampleContent); } @@ -29,7 +29,7 @@ function xmlWithStringPattern() { VKBeautify.xml(exampleContent, ' '); } -//json +// json function jsonWithDefault() { VKBeautify.json(exampleContent); } @@ -42,7 +42,7 @@ function jsonWithStringPattern() { VKBeautify.json(exampleContent, ' '); } -//css +// css function cssWithDefault() { VKBeautify.css(exampleContent); } @@ -55,7 +55,7 @@ function cssWithStringPattern() { VKBeautify.css(exampleContent, ' '); } -//sql +// sql function sqlWithDefault() { VKBeautify.sql(exampleContent); } @@ -71,18 +71,18 @@ function sqlWithStringPattern() { /* * Minifying - * + * * vkbeautify.xmlmin(text [,preserve_comments]); * vkbeautify.jsonmin(text); * vkbeautify.cssmin(text [,preserve_comments]); * vkbeautify.sqlmin(text); - * + * * @text - String; text to minify; * @preserve_comments - Bool; [optional]; * Set this flag to true to prevent removing comments from @text ( minxml and mincss functions only. ) */ -//xml +// xml function xmlminWithDefault() { VKBeautify.xmlmin(exampleContent); } @@ -95,12 +95,12 @@ function xmlminAndRemoveComments() { VKBeautify.xmlmin(exampleContent, false); } -//json +// json function jsonmin() { VKBeautify.jsonmin(exampleContent); } -//css +// css function cssminWithDefault() { VKBeautify.cssmin(exampleContent); } @@ -113,7 +113,7 @@ function cssminAndRemoveComments() { VKBeautify.cssmin(exampleContent, false); } -//sql +// sql function sqlmin() { VKBeautify.sqlmin(exampleContent); } \ No newline at end of file diff --git a/voca/voca-tests.ts b/voca/voca-tests.ts index 3fb9d100c3..5c6f1f4bc9 100644 --- a/voca/voca-tests.ts +++ b/voca/voca-tests.ts @@ -1,7 +1,7 @@ import v = require('voca'); var str: string; -var num: number +var num: number; var bool: boolean; var strAry: string[]; var numAry: number[]; @@ -128,7 +128,7 @@ str = v.chain('<p>wonderful world</p>').unescapeHtml().value(); str = v.sprintf(); str = v.sprintf('%s, %s!', 'Hello', 'World'); str = v.sprintf('%s costs $%d', 'coffee', 2); -str = v.sprintf('%1$s %2$s %1$s %2$s, watcha gonna %3$s', 'bad', 'boys', 'do') +str = v.sprintf('%1$s %2$s %1$s %2$s, watcha gonna %3$s', 'bad', 'boys', 'do'); str = v.sprintf('% 6s', 'bird'); str = v.sprintf('%d %i %+d', 15, -2, 25); str = v.sprintf("%06d", 15); @@ -137,7 +137,7 @@ str = v('%s, %s!').sprintf('Hello', 'World').value(); str = v.chain('%s, %s!').sprintf('Hello', 'World').value(); str = v.vprintf(); -str = v.vprintf('%s', ['Welcome']) +str = v.vprintf('%s', ['Welcome']); str = v.vprintf('%s has %d apples', ['Alexandra', 3]); str = v('%s').vprintf(['Welcome']).value(); str = v.chain('%s').vprintf(['Welcome']).value(); @@ -328,4 +328,4 @@ str = v.stripTags('Sun
    set', '', '-'); // Util var voca: v.VocaStatic = v.noConflict(); -var version: String = v.version; +var version: string = v.version; diff --git a/watchpack/watchpack-tests.ts b/watchpack/watchpack-tests.ts index 77b78d8c23..7ae28bc514 100644 --- a/watchpack/watchpack-tests.ts +++ b/watchpack/watchpack-tests.ts @@ -3,5 +3,5 @@ const watch = new Watchpack({}); watch.watch(['test.js'], ['lib/'], 1000); -let time: number -time = watch.getTimes()['test.js'] +let time: number; +time = watch.getTimes()['test.js']; diff --git a/web-bluetooth/index.d.ts b/web-bluetooth/index.d.ts index 219dd65f5e..f30269239c 100644 --- a/web-bluetooth/index.d.ts +++ b/web-bluetooth/index.d.ts @@ -17,7 +17,7 @@ interface BluetoothRequestDeviceFilter { interface RequestDeviceOptions { filters: BluetoothRequestDeviceFilter[]; - optionalServices?: number[]; + optionalServices?: BluetoothServiceUUID[]; acceptAllDevices?: boolean; } diff --git a/webappsec-credential-management/webappsec-credential-management-tests.ts b/webappsec-credential-management/webappsec-credential-management-tests.ts index 2a13e943c3..69cae46daf 100644 --- a/webappsec-credential-management/webappsec-credential-management-tests.ts +++ b/webappsec-credential-management/webappsec-credential-management-tests.ts @@ -70,7 +70,7 @@ function passwordPostSignInConfirmation() { if (navigator.credentials) { e.preventDefault(); - let formElem = (e.target as HTMLFormElement); + const formElem = (e.target as HTMLFormElement); var c = new PasswordCredential(formElem); fetch(formElem.action, {method: 'POST', credentials: c}).then(r => { if (r.status === 200) { diff --git a/webmidi/index.d.ts b/webmidi/index.d.ts index 351a20c58a..a103ea77dd 100644 --- a/webmidi/index.d.ts +++ b/webmidi/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Web MIDI API +// Type definitions for Web MIDI API 2.0 // Project: http://www.w3.org/TR/webmidi/ // Definitions by: six a // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,7 +8,7 @@ interface Navigator { * When invoked, returns a Promise object representing a request for access to MIDI * devices on the user's system. */ - requestMIDIAccess(options?: WebMidi.MIDIOptions) : Promise; + requestMIDIAccess(options?: WebMidi.MIDIOptions): Promise; } declare namespace WebMidi { @@ -17,7 +17,7 @@ declare namespace WebMidi { * This member informs the system whether the ability to send and receive system * exclusive messages is requested or allowed on a given MIDIAccess object. */ - sysex : boolean; + sysex: boolean; } /** @@ -36,24 +36,24 @@ declare namespace WebMidi { /** * The MIDI input ports available to the system. */ - inputs : MIDIInputMap; + inputs: MIDIInputMap; /** * The MIDI output ports available to the system. */ - outputs : MIDIOutputMap; + outputs: MIDIOutputMap; /** * The handler called when a new port is connected or an existing port changes the * state attribute. */ - onstatechange : (e : MIDIConnectionEvent) => void; + onstatechange: (e: MIDIConnectionEvent) => void; /** * This attribute informs the user whether system exclusive support is enabled on * this MIDIAccess. */ - sysexEnabled : boolean; + sysexEnabled: boolean; } export type MIDIPortType = "input" | "output"; @@ -67,44 +67,44 @@ declare namespace WebMidi { * A unique ID of the port. This can be used by developers to remember ports the * user has chosen for their application. */ - id : string; + id: string; /** * The manufacturer of the port. */ - manufacturer? : string; + manufacturer?: string; /** * The system name of the port. */ - name? : string; + name?: string; /** * A descriptor property to distinguish whether the port is an input or an output * port. */ - type : MIDIPortType; + type: MIDIPortType; /** * The version of the port. */ - version? : string; + version?: string; /** * The state of the device. */ - state : MIDIPortDeviceState; + state: MIDIPortDeviceState; /** * The state of the connection to the device. */ - connection : MIDIPortConnectionState; + connection: MIDIPortConnectionState; /** * The handler called when an existing port changes its state or connection * attributes. */ - onstatechange : (e : MIDIConnectionEvent) => void; + onstatechange: (e: MIDIConnectionEvent) => void; /** * Makes the MIDI device corresponding to the MIDIPort explicitly available. Note @@ -115,7 +115,7 @@ declare namespace WebMidi { * When invoked, this method returns a Promise object representing a request for * access to the given MIDI port on the user's system. */ - open() : Promise; + open(): Promise; /** * Makes the MIDI device corresponding to the MIDIPort @@ -130,11 +130,11 @@ declare namespace WebMidi { * other applications), the vended Promise is resolved. If the port is * disconnected, the Promise is rejected. */ - close() : Promise; + close(): Promise; } export interface MIDIInput extends MIDIPort { - onmidimessage : (e : MIDIMessageEvent) => void; + onmidimessage: (e: MIDIMessageEvent) => void; } export interface MIDIOutput extends MIDIPort { @@ -145,7 +145,7 @@ declare namespace WebMidi { * to zero (or another time in the past), the data is to be sent as soon as * possible. */ - send(data : number[], timestamp? : number) : void; + send(data: number[], timestamp?: number): void; /** * Clears any pending send data that has not yet been sent from the MIDIOutput 's @@ -153,44 +153,44 @@ declare namespace WebMidi { * state, so if the output port is in the middle of a sysex message, a sysex * termination byte (0xf7) should be sent. */ - clear() : void; + clear(): void; } export interface MIDIMessageEvent extends Event { /** * A timestamp specifying when the event occurred. */ - receivedTime : number; + receivedTime: number; /** * A Uint8Array containing the MIDI data bytes of a single MIDI message. */ - data : Uint8Array; + data: Uint8Array; } export interface MIDIMessageEventInit extends EventInit { /** * A timestamp specifying when the event occurred. */ - receivedTime : number; + receivedTime: number; /** * A Uint8Array containing the MIDI data bytes of a single MIDI message. */ - data : Uint8Array; + data: Uint8Array; } export interface MIDIConnectionEvent extends Event { /** * The port that has been connected or disconnected. */ - port : MIDIPort; + port: MIDIPort; } export interface MIDIConnectionEventInit extends EventInit { /** * The port that has been connected or disconnected. */ - port : MIDIPort; + port: MIDIPort; } } diff --git a/webmidi/tsconfig.json b/webmidi/tsconfig.json index e7957af823..2d4444827a 100644 --- a/webmidi/tsconfig.json +++ b/webmidi/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/webmidi/tslint.json b/webmidi/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/webmidi/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/webmidi/webmidi-tests.ts b/webmidi/webmidi-tests.ts index f6b5546abd..f361202895 100644 --- a/webmidi/webmidi-tests.ts +++ b/webmidi/webmidi-tests.ts @@ -3,7 +3,7 @@ var onFulfilled = (item: WebMidi.MIDIAccess) => { this._midiPort = item; - item.onstatechange = (event : WebMidi.MIDIConnectionEvent) => { + item.onstatechange = (event: WebMidi.MIDIConnectionEvent) => { console.log("onstatechange"); console.log(event); }; @@ -11,27 +11,27 @@ var onFulfilled = (item: WebMidi.MIDIAccess) => { console.log("sysexenabled"); console.log(item.sysexEnabled); - var inputs = this._midiPort.inputs.values(); + var inputs = this._midiPort.inputs.values(); - for(const o of inputs){ + for (const o of inputs) { this._inputs.push(o); console.log(o); } var outputs = item.outputs.values(); - for(const op of outputs){ + for (const op of outputs) { this._outputs.push(op); op.send([ 0x90, 0x45, 0x7f ] ); } - for(var cnt = 0; cnt < this._inputs.length; cnt++){ - this._inputs[cnt].onmidimessage = (event: WebMidi.MIDIMessageEvent)=>{ + for (const input of this._inputs) { + input.onmidimessage = (event: WebMidi.MIDIMessageEvent) => { this.onMidiMessage(event.data); }; } }; -var onRejected = (e: Error)=>{ console.error(e) }; +var onRejected = (e: Error) => { console.error(e); }; if (navigator.requestMIDIAccess !== undefined) { navigator.requestMIDIAccess().then(onFulfilled, onRejected); diff --git a/webpack-dev-middleware/webpack-dev-middleware-tests.ts b/webpack-dev-middleware/webpack-dev-middleware-tests.ts index 63d32332b5..3764a6b9aa 100644 --- a/webpack-dev-middleware/webpack-dev-middleware-tests.ts +++ b/webpack-dev-middleware/webpack-dev-middleware-tests.ts @@ -31,6 +31,6 @@ app.use(webpackDevMiddlewareInstance); webpackDevMiddlewareInstance.close(); webpackDevMiddlewareInstance.invalidate(); -webpackDevMiddlewareInstance.waitUntilValid(function(){ +webpackDevMiddlewareInstance.waitUntilValid(() => { console.log('Package is in a valid state'); }); diff --git a/webpack/index.d.ts b/webpack/index.d.ts index 8b5a4d9938..d21716a6e8 100644 --- a/webpack/index.d.ts +++ b/webpack/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for webpack 2.2 // Project: https://github.com/webpack/webpack -// Definitions by: Qubo , Matt Lewis , Benjamin Lim , Boris Cherny +// Definitions by: Qubo , Matt Lewis , Benjamin Lim , Boris Cherny , Tommy Troy Lin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -27,7 +27,13 @@ declare namespace webpack { context?: string; entry?: string | string[] | Entry; /** Choose a style of source mapping to enhance the debugging process. These values can affect build and rebuild speed dramatically. */ - devtool?: 'eval' | 'inline-source-map' | 'cheap-eval-source-map' | 'cheap-source-map' | 'cheap-module-eval-source-map' | 'cheap-module-source-map' | 'eval-source-map' | 'source-map' | 'nosources-source-map' | 'hidden-source-map' | 'nosources-source-map' | '@eval' | '@inline-source-map' | '@cheap-eval-source-map' | '@cheap-source-map' | '@cheap-module-eval-source-map' | '@cheap-module-source-map' | '@eval-source-map' | '@source-map' | '@nosources-source-map' | '@hidden-source-map' | '@nosources-source-map' | '#eval' | '#inline-source-map' | '#cheap-eval-source-map' | '#cheap-source-map' | '#cheap-module-eval-source-map' | '#cheap-module-source-map' | '#eval-source-map' | '#source-map' | '#nosources-source-map' | '#hidden-source-map' | '#nosources-source-map' | '#@eval' | '#@inline-source-map' | '#@cheap-eval-source-map' | '#@cheap-source-map' | '#@cheap-module-eval-source-map' | '#@cheap-module-source-map' | '#@eval-source-map' | '#@source-map' | '#@nosources-source-map' | '#@hidden-source-map' | '#@nosources-source-map' | boolean; + // tslint:disable-next-line:max-line-length + devtool?: 'eval' | 'inline-source-map' | 'cheap-eval-source-map' | 'cheap-source-map' | 'cheap-module-eval-source-map' | 'cheap-module-source-map' | 'eval-source-map' | 'source-map' | + 'nosources-source-map' | 'hidden-source-map' | 'nosources-source-map' | '@eval' | '@inline-source-map' | '@cheap-eval-source-map' | '@cheap-source-map' | '@cheap-module-eval-source-map' | + '@cheap-module-source-map' | '@eval-source-map' | '@source-map' | '@nosources-source-map' | '@hidden-source-map' | '@nosources-source-map' | '#eval' | '#inline-source-map' | + '#cheap-eval-source-map' | '#cheap-source-map' | '#cheap-module-eval-source-map' | '#cheap-module-source-map' | '#eval-source-map' | '#source-map' | '#nosources-source-map' | + '#hidden-source-map' | '#nosources-source-map' | '#@eval' | '#@inline-source-map' | '#@cheap-eval-source-map' | '#@cheap-source-map' | '#@cheap-module-eval-source-map' | + '#@cheap-module-source-map' | '#@eval-source-map' | '#@source-map' | '#@nosources-source-map' | '#@hidden-source-map' | '#@nosources-source-map' | boolean; /** Options affecting the output. */ output?: Output; /** Options affecting the normal modules (NormalModuleFactory) */ @@ -422,7 +428,8 @@ declare namespace webpack { /** * An object with parser options. All applied parser options are merged. * - * For each different parser options object a new parser is created and plugins can apply plugins depending on the parser options. Many of the default plugins apply their parser plugins only if a property in the parser options is not set or true. + * For each different parser options object a new parser is created and plugins can apply plugins depending on the parser options. + * Many of the default plugins apply their parser plugins only if a property in the parser options is not set or true. */ parser?: { [optName: string]: any }; /** An array of Rules that is also used when the Rule matches. */ @@ -654,7 +661,20 @@ declare namespace webpack { */ class BannerPlugin extends Plugin { - constructor(banner: any, options: any); + constructor(options: string | BannerPlugin.Options); + } + + namespace BannerPlugin { + type Filter = string | RegExp; + + interface Options { + banner: string; + entryOnly?: boolean; + exclude?: Filter | Filter[]; + include?: Filter | Filter[]; + raw?: boolean; + test?: Filter | Filter[]; + } } class ContextReplacementPlugin extends Plugin { @@ -759,7 +779,10 @@ declare namespace webpack { namespace optimize { class AggressiveMergingPlugin extends Plugin { - constructor(options: any); + constructor(options?: { + minSize?: number; + maxSize?: number; + }); } class CommonsChunkPlugin extends Plugin { diff --git a/webpack/webpack-tests.ts b/webpack/webpack-tests.ts index ffa69e90f2..8ab05c1de4 100644 --- a/webpack/webpack-tests.ts +++ b/webpack/webpack-tests.ts @@ -103,7 +103,7 @@ configuration = { } }; -let CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin; +const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin; configuration = { entry: { p1: "./page1", @@ -208,7 +208,7 @@ declare var path: any; configuration = { plugins: [ function(this: webpack.Compiler) { - this.plugin("done", function(stats: any) { + this.plugin("done", stats => { require("fs").writeFileSync( path.join(__dirname, "...", "stats.json"), JSON.stringify(stats.toJson())); @@ -221,22 +221,22 @@ configuration = { // https://webpack.github.io/docs/list-of-plugins.html // -let resourceRegExp: any; -let newResource: any; -let contextRegExp: any; -let newContentResource: any; -let newContentRecursive: any; -let newContentRegExp: any; -let requestRegExp: any; -let options: any; -let definitions: any; -let paths: any; -let preferEntry = true; -let context: any; -let request: any; -let types: any; -let banner: any; -let plugins: webpack.Plugin[] = []; +declare const resourceRegExp: any; +declare const newResource: any; +declare const contextRegExp: any; +declare const newContentResource: any; +declare const newContentRecursive: any; +declare const newContentRegExp: any; +declare const requestRegExp: any; +declare const options: any; +declare const definitions: any; +declare const paths: any; +const preferEntry = true; +declare const context: any; +declare const request: any; +declare const types: any; +declare const banner: any; +const plugins: webpack.Plugin[] = []; plugin = new webpack.NormalModuleReplacementPlugin(resourceRegExp, newResource); plugin = new webpack.ContextReplacementPlugin( @@ -257,7 +257,18 @@ plugin = new webpack.IgnorePlugin(requestRegExp, contextRegExp); plugin = new webpack.PrefetchPlugin(context, request); plugin = new webpack.PrefetchPlugin(request); -plugin = new webpack.BannerPlugin(banner, options); +plugin = new webpack.BannerPlugin('banner'); +plugin = new webpack.BannerPlugin({ + banner: 'banner' +}); +plugin = new webpack.BannerPlugin({ + banner: 'banner', + entryOnly: true, + exclude: /index/, + include: 'test', + raw: false, + test: ['test', /index/] +}); plugin = new webpack.optimize.DedupePlugin(); plugin = new webpack.optimize.LimitChunkCountPlugin(options); plugin = new webpack.optimize.MinChunkSizePlugin(options); @@ -284,9 +295,7 @@ plugin = new webpack.optimize.UglifyJsPlugin({ } }); plugin = new webpack.optimize.UglifyJsPlugin({ - comments: function(astNode: any, comment: any) { - return false; - } + comments: (astNode: any, comment: any) => false }); plugin = new webpack.optimize.CommonsChunkPlugin(options); plugin = new CommonsChunkPlugin({ @@ -328,9 +337,9 @@ plugin = new CommonsChunkPlugin({ plugin = new webpack.optimize.AggressiveMergingPlugin(options); plugin = new webpack.DefinePlugin(definitions); plugin = new webpack.DefinePlugin({ - VERSION: JSON.stringify("5fa3b9"), - BROWSER_SUPPORTS_HTML5: true, - TWO: "1+1", + "VERSION": JSON.stringify("5fa3b9"), + "BROWSER_SUPPORTS_HTML5": true, + "TWO": "1+1", "typeof window": JSON.stringify("object") }); plugin = new webpack.ProvidePlugin(definitions); @@ -340,17 +349,17 @@ plugin = new webpack.ProvidePlugin({ plugin = new webpack.SourceMapDevToolPlugin({ //// asset matching test: /\.js$/, - //include: Condition | Condition[], + // include: Condition | Condition[], exclude: [ /node_modules/ ], // //// file and reference filename: null, // | string - //append: false | string, + // append: false | string, //// sources naming - //moduleFilenameTemplate: string, - //fallbackModuleFilenameTemplate: string, + // moduleFilenameTemplate: string, + // fallbackModuleFilenameTemplate: string, // //// quality/performance module: true, @@ -374,7 +383,7 @@ plugin = new webpack.LoaderOptionsPlugin({ // returns a Compiler instance webpack({ // configuration -}, function(err, stats) { +}, (err, stats) => { // ... }); @@ -383,7 +392,7 @@ var compiler = webpack({ // configuration }); -compiler.run(function(err, stats) { +compiler.run((err, stats) => { // ... }); // or @@ -391,19 +400,19 @@ compiler.watch({ // watch options: aggregateTimeout: 300, // wait so long for more changes poll: true // use polling instead of native watchers // pass a number to set the polling interval -}, function(err, stats) { +}, (err, stats) => { // ... }); // or compiler.watch({ // watch options: ignored: 'foo/**/*' -}, function(err, stats) { +}, (err, stats) => { // ... }); // or compiler.watch({ // watch options: ignored: /node_modules/ -}, function(err, stats) { +}, (err, stats) => { // ... }); @@ -414,8 +423,8 @@ declare function successfullyCompiled(): void; webpack({ // configuration -}, function(err, stats) { - if(err) +}, (err, stats) => { + if (err) return handleFatalError(err); var jsonStats = stats.toJson(); var jsonStatsWithAllOptions = stats.toJson({ @@ -440,9 +449,9 @@ webpack({ version: true, warnings: true }); - if(jsonStats.errors.length > 0) + if (jsonStats.errors.length > 0) return handleSoftErrors(jsonStats.errors); - if(jsonStats.warnings.length > 0) + if (jsonStats.warnings.length > 0) handleWarnings(jsonStats.warnings); successfullyCompiled(); }); @@ -451,7 +460,7 @@ declare var fs: any; compiler = webpack({ }); compiler.outputFileSystem = fs; -compiler.run(function(err, stats) { +compiler.run((err, stats) => { // ... var fileContent = fs.readFileSync("..."); }); @@ -469,7 +478,7 @@ rule = { }, loader: "./loader", options: "third" -} +}; configuration = { module: { @@ -499,7 +508,7 @@ configuration = { { loader: "./loader", options: { - get: function() { return "second-3"; } + get: () => "second-3" } } ] @@ -517,19 +526,17 @@ configuration = { ]} ] } -} +}; const resolve: webpack.Resolve = { cachePredicate: 'boo' // why does this test _not_ fail!? -} +}; const performance: webpack.Options.Performance = { hints: 'error', maxEntrypointSize: 400000, maxAssetSize: 100000, - assetFilter: function(assetFilename) { - return assetFilename.endsWith('.js'); - }, + assetFilter: assetFilename => assetFilename.endsWith('.js'), }; configuration = { @@ -550,7 +557,7 @@ function loader(this: webpack.loader.LoaderContext, source: string, sourcemap: s this.callback(null, source); } -module loader { +namespace loader { export const raw: boolean = true; export const pitch = (remainingRequest: string, precedingRequest: string, data: any) => {}; } diff --git a/websocket/index.d.ts b/websocket/index.d.ts index ea8af308d2..83d127c599 100644 --- a/websocket/index.d.ts +++ b/websocket/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for websocket // Project: https://github.com/theturtle32/WebSocket-Node -// Definitions by: Paul Loyd +// Definitions by: Paul Loyd , +// Kay Schecker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -8,6 +9,7 @@ import events = require('events'); import http = require('http'); +import https = require('https'); import net = require('net'); import url = require('url'); @@ -534,6 +536,13 @@ export interface IClientConfig extends IConfig { * @default 8MiB */ maxReceivedMessageSize?: number; + + /** + * Options to pass to https.request if connecting via TLS. + * See Node's HTTPS documentation + * @see https://nodejs.org/api/https.html#https_https_request_options_callback + */ + tlsOptions?: https.RequestOptions; } declare class client extends events.EventEmitter { diff --git a/webtorrent/index.d.ts b/webtorrent/index.d.ts index 207015f871..22c9417edd 100644 --- a/webtorrent/index.d.ts +++ b/webtorrent/index.d.ts @@ -144,10 +144,16 @@ declare namespace WebTorrent { getBuffer(callback: (err: string | Error | undefined, buffer?: Buffer) => void): void; - appendTo(rootElement: HTMLElement | string, opts?: { autoplay?: boolean, controls?: boolean, maxBlobLength?: number }, callback?: (err: Error | undefined, element: HTMLMediaElement) => void): void; + appendTo( + rootElement: HTMLElement | string, + opts?: { autoplay?: boolean, controls?: boolean, maxBlobLength?: number }, + callback?: (err: Error | undefined, element: HTMLMediaElement) => void): void; appendTo(rootElement: HTMLElement | string, callback?: (err: Error | undefined, element: HTMLMediaElement) => void): void; - renderTo(rootElement: HTMLMediaElement | string, opts?: { autoplay?: boolean, controls?: boolean, maxBlobLength?: number }, callback?: (err: Error | undefined, element: HTMLMediaElement) => void): void; + renderTo( + rootElement: HTMLMediaElement | string, + opts?: { autoplay?: boolean, controls?: boolean, maxBlobLength?: number }, + callback?: (err: Error | undefined, element: HTMLMediaElement) => void): void; renderTo(rootElement: HTMLMediaElement | string, callback?: (err: Error | undefined, element: HTMLMediaElement) => void): void; getBlob(callback: (err: string | Error | undefined, blob?: Blob) => void): void; diff --git a/webtorrent/tslint.json b/webtorrent/tslint.json index ec365f164b..377cc837d4 100644 --- a/webtorrent/tslint.json +++ b/webtorrent/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/webtorrent/webtorrent-tests.ts b/webtorrent/webtorrent-tests.ts index ba08944d58..f0f80cb1b3 100644 --- a/webtorrent/webtorrent-tests.ts +++ b/webtorrent/webtorrent-tests.ts @@ -4,26 +4,26 @@ import * as fs from 'fs'; var client = new WebTorrent(); var magnetURI = '...'; -client.add(magnetURI, {}, function(torrent) { +client.add(magnetURI, {}, torrent => { // Got torrent metadata! console.log('Client is downloading:', torrent.infoHash); - torrent.files.forEach(function(file) { + torrent.files.forEach(file => { // Display the file by appending it to the DOM. Supports video, audio, images, and // more. Specify a container element (CSS selector or reference to DOM node). file.appendTo('body'); - file.getBuffer(function(err, buffer) { + file.getBuffer((err, buffer) => { if (err) throw err; - console.log(buffer); // + console.log(buffer); // }); - file.appendTo('#containerElement', function(err, elem) { + file.appendTo('#containerElement', (err, elem) => { if (err) throw err; // file failed to download or display in the DOM console.log('New DOM node with the content', elem); }); - file.getBlobURL(function(err, url) { + file.getBlobURL((err, url) => { if (err) throw err; var a = document.createElement('a'); // a.download = file.name @@ -35,14 +35,14 @@ client.add(magnetURI, {}, function(torrent) { }); }); - torrent.on('done', function() { + torrent.on('done', () => { console.log('torrent finished downloading'); - torrent.files.forEach(function(file) { + torrent.files.forEach(file => { // do something with file }); }); - torrent.on('download', function(chunkSize) { + torrent.on('download', chunkSize => { console.log('chunk size: ' + chunkSize); console.log('total downloaded: ' + torrent.downloaded); console.log('download speed: ' + torrent.downloadSpeed); @@ -50,16 +50,16 @@ client.add(magnetURI, {}, function(torrent) { console.log('======'); }); - torrent.on('wire', function(wire, addr) { + torrent.on('wire', (wire, addr) => { console.log('connected to peer with address ' + addr); }); }); -client.seed('./file.txt', {}, function(torrent) { +client.seed('./file.txt', {}, torrent => { console.log('Client is seeding:', torrent.infoHash); }); -client.add(magnetURI, function(torrent) { +client.add(magnetURI, torrent => { // create HTTP server for this torrent var server = torrent.createServer(); server.listen(1234); // start the server listening to a port diff --git a/wu/index.d.ts b/wu/index.d.ts index 90f6475ee8..3de797c454 100644 --- a/wu/index.d.ts +++ b/wu/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for wu.js v2.1.0 +// Type definitions for wu.js 2.1 // Project: https://fitzgen.github.io/wu.js/ // Definitions by: phiresky // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,7 +10,7 @@ declare namespace Wu { export interface WuStatic { (iterable: Iterable): WuIterable; // only static - chain(...iters: Iterable[]): WuIterable; + chain(...iters: Array>): WuIterable; count(start?: number, step?: number): WuIterable; curryable(fun: (...x: any[]) => T, expected?: number): any; entries(obj: { [i: string]: T }): WuIterable<[string, T]>; @@ -24,7 +24,6 @@ declare namespace Wu { cycle(iter: Iterable): Iterable; chunk(n: number, iter: Iterable): WuIterable; concatMap(fn: (t: T) => Iterable, iter: Iterable): WuIterable; - dropWhile(fn: Filter, iter: Iterable): WuIterable; enumerate(iter: Iterable): Iterable<[number, T]>; every(fn: Filter, iter: Iterable): boolean; filter(fn: Filter, iter: Iterable): WuIterable; @@ -60,8 +59,8 @@ declare namespace Wu { zipLongest(iter2: Iterable, iter: Iterable): WuIterable<[T, U]>; zipWith: any; unzip: any; - tee(iter: Iterable): WuIterable[]; - tee(n: number, iter: Iterable): WuIterable[]; + tee(iter: Iterable): Array>; + tee(n: number, iter: Iterable): Array>; } export interface WuIterable extends IterableIterator { // generated from section "copied to WuIterable" above via @@ -74,13 +73,11 @@ declare namespace Wu { cycle(): Iterable; chunk(n: number): WuIterable; concatMap(fn: (t: T) => Iterable): WuIterable; - dropWhile(fn: Filter): WuIterable; enumerate(): Iterable<[number, T]>; every(fn: Filter): boolean; filter(fn: Filter): WuIterable; find(fn: Filter): T; - flatten(): WuIterable; - flatten(shallow: boolean): WuIterable; + flatten(shallow?: boolean): WuIterable; forEach(fn: Consumer): void; has(t: T): boolean; // invoke(name:string, ...t:T[], iter: Iterable<(t:T)=>U>): WuIterable; @@ -88,18 +85,12 @@ declare namespace Wu { map(fn: (t: T) => U): WuIterable; // pluck(attribute:string, iter: Iterable<{[attribute]: T}>): WuIterable; pluck(attribute: string): WuIterable; - reduce(fn: (a: T, b: T) => T): T; - reduce(fn: (a: T, b: T) => T, initial: T): T; - reduce(fn: (a: U, b: T) => U): U; - reduce(fn: (a: U, b: T) => U, initial: U): U; - reductions(fn: (a: T, b: T) => T): WuIterable; - reductions(fn: (a: T, b: T) => T, initial: T): WuIterable; - reductions(fn: (a: U, b: T) => U): WuIterable; - reductions(fn: (a: U, b: T) => U, initial: U): WuIterable; + reduce(fn: (a: T, b: T) => T, initial?: T): T; + reduce(fn: (a: U, b: T) => U, initial?: U): U; + reductions(fn: (a: T, b: T) => T, initial?: T): WuIterable; + reductions(fn: (a: U, b: T) => U, initial?: U): WuIterable; reject(fn: Filter): WuIterable; - slice(): WuIterable; - slice(start: number): WuIterable; - slice(start: number, stop: number): WuIterable; + slice(start?: number, stop?: number): WuIterable; some(fn: Filter): boolean; spreadMap(fn: (...x: any[]) => T, iter: Iterable): WuIterable; take(n: number): WuIterable; @@ -110,8 +101,7 @@ declare namespace Wu { zipLongest(iter2: Iterable): WuIterable<[T, U]>; zipWith: any; unzip: any; - tee(): WuIterable[]; - tee(n: number): WuIterable[]; + tee(n?: number): Array>; } } declare var wu: Wu.WuStatic; diff --git a/wu/tsconfig.json b/wu/tsconfig.json index d416f96d9a..e165aee3c4 100644 --- a/wu/tsconfig.json +++ b/wu/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6" ], diff --git a/wu/tslint.json b/wu/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/wu/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/wu/wu-tests.ts b/wu/wu-tests.ts index 3dcb11abb1..e96324274b 100644 --- a/wu/wu-tests.ts +++ b/wu/wu-tests.ts @@ -1,13 +1,13 @@ // adapted from `cat wu.js/test/* |sed '/= require/d'> wu-tests.ts` declare var describe: any, it: any, mocha: any, assert: { - iterable:any; - eqSet(expected:Set, actual: Iterable): any; - ok:any; - equal(x:T, y:T): any; - eqArray(x:T[], y:Iterable): any; - deepEqual(x:T, y:T): any; -} + iterable: any; + eqSet(expected: Set, actual: Iterable): any; + ok: any; + equal(x: T, y: T): any; + eqArray(x: T[], y: Iterable): any; + deepEqual(x: T, y: T): any; +}; // Helper for asserting that the given thing is iterable. assert.iterable = (thing: any) => { @@ -59,8 +59,8 @@ describe("wu.chain", () => { }); describe("wu.chunk", () => { it("should chunk items into tuples", () => { - assert.eqArray([[1,2,3], [4,5,6]], - wu.chunk(3, [1,2,3,4,5,6])); + assert.eqArray([[1, 2, 3], [4, 5, 6]], + wu.chunk(3, [1, 2, 3, 4, 5, 6])); }); }); describe("wu.concatMap", () => { @@ -121,7 +121,7 @@ describe("wu.cycle", () => { it("should keep yielding items from the original iterable", () => { let i = 0; const arr = [1, 2, 3]; - for (let x of wu.cycle(arr)) { + for (const x of wu.cycle(arr)) { assert.equal(x, arr[i % 3]); if (i++ > 9) { break; @@ -144,7 +144,7 @@ describe("wu.dropWhile", () => { describe("wu.entries", () => { it("should iterate over entries", () => { const expected = new Map([["foo", 1], ["bar", 2], ["baz", 3]]); - for (let [k, v] of wu.entries({ foo: 1, bar: 2, baz: 3 })) { + for (const [k, v] of wu.entries({ foo: 1, bar: 2, baz: 3 })) { assert.equal(expected.get(k), v); } }); @@ -183,7 +183,7 @@ describe("wu.find", () => { it("should return undefined if no items match the predicate", () => { assert.equal(undefined, - wu.find(x => (x) === "raekwon", + wu.find(x => ( x) === "raekwon", [{ name: "odb" }, { name: "method man" }, { name: "rza" }, @@ -204,25 +204,25 @@ describe("wu.flatten", () => { describe("wu.forEach", () => { it("should iterate over every item", () => { const items: any[] = []; - wu.forEach(x => items.push(x), [1,2,3]); - assert.eqArray([1,2,3], items); + wu.forEach(x => items.push(x), [1, 2, 3]); + assert.eqArray([1, 2, 3], items); }); }); describe("wu.has", () => { it("should return true if the item is in the iterable", () => { - assert.ok(wu.has(3, [1,2,3])); + assert.ok(wu.has(3, [1, 2, 3])); }); it("should return false if the item is not in the iterable", () => { - assert.ok(!wu.has("36 chambers", [1,2,3])); + assert.ok(!wu.has( "36 chambers", [1, 2, 3])); }); }); describe("wu.invoke", () => { it("should yield the method invokation on each item", () => { function Greeter(name: string) { - this.name = name + this.name = name; } - Greeter.prototype.greet = function (tail: string) { + Greeter.prototype.greet = function(tail: string) { return "hello " + this.name + tail; }; assert.eqArray(["hello world!", "hello test!"], @@ -250,11 +250,11 @@ describe("wu.pluck", () => { }); describe("wu.reduce", () => { it("should reduce the iterable with the function", () => { - assert.equal(6, wu([1,2,3]).reduce((x, y) => x + y)); + assert.equal(6, wu([1, 2, 3]).reduce((x, y) => x + y)); }); it("should accept an initial state for the reducer function", () => { - assert.equal(16, wu.reduce((x, y) => x + y, 10, [1,2,3])); + assert.equal(16, wu.reduce((x, y) => x + y, 10, [1, 2, 3])); }); }); describe("wu.reductions", () => { @@ -305,11 +305,11 @@ describe("wu.slice", () => { }); describe("wu.some", () => { it("should return true if any item matches the predicate", () => { - assert.ok(wu.some(x => x % 2 === 0, [1,2,3])); + assert.ok(wu.some(x => x % 2 === 0, [1, 2, 3])); }); it("should return false if no items match the predicate", () => { - assert.ok(!wu.some(x => x % 5 === 0, [1,2,3])); + assert.ok(!wu.some(x => x % 5 === 0, [1, 2, 3])); }); }); describe("wu.spreadMap", () => { @@ -357,7 +357,7 @@ describe("wu.tee", () => { describe("wu.unique", () => { it("should yield only the unique items from the iterable", () => { assert.eqArray([1, 2, 3], - wu.unique([1,1,2,2,1,1,3,3])); + wu.unique([1, 1, 2, 2, 1, 1, 3, 3])); }); }); describe("wu.unzip", () => { diff --git a/xdg-basedir/tsconfig.json b/xdg-basedir/tsconfig.json index 44428e6cc7..60be2ca765 100644 --- a/xdg-basedir/tsconfig.json +++ b/xdg-basedir/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "xdg-basedir-tests.ts" ] -} +} \ No newline at end of file diff --git a/xdg-basedir/xdg-basedir-tests.ts b/xdg-basedir/xdg-basedir-tests.ts index a6b7073c18..35eaa1551f 100644 --- a/xdg-basedir/xdg-basedir-tests.ts +++ b/xdg-basedir/xdg-basedir-tests.ts @@ -1,3 +1,3 @@ import * as xdg from 'xdg-basedir'; -console.log(JSON.stringify(xdg, undefined, 2)); +JSON.stringify(xdg, undefined, 2); diff --git a/xml/index.d.ts b/xml/index.d.ts index 8c5d5179ca..357c3f5b16 100644 --- a/xml/index.d.ts +++ b/xml/index.d.ts @@ -6,16 +6,16 @@ /// interface Option { - /** - * String used for tab, defaults to no tabs (compressed) + /** + * String used for tab, defaults to no tabs (compressed) */ indent?: string; /** - * Return the result as a `stream` (default false) + * Return the result as a `stream` (default false) */ stream?: boolean; /** - * Add default xml declaration (default false) + * Add default xml declaration (default false) */ declaration?: boolean | { encoding?: string; diff --git a/xml/xml-tests.ts b/xml/xml-tests.ts index df8acf6ef9..7bc3cd61c0 100644 --- a/xml/xml-tests.ts +++ b/xml/xml-tests.ts @@ -85,7 +85,9 @@ test('supports cdata', t => { _cdata: 'This is some CDATA' } }]), 'CDATA]]>'); - t.is(xml([{a: {_cdata: 'This is some CDATA with ]]> and then again ]]>'}}]), 'CDATA with ]]]]> and then again ]]]]>]]>'); + t.is( + xml([{a: {_cdata: 'This is some CDATA with ]]> and then again ]]>'}}]), + 'CDATA with ]]]]> and then again ]]]]>]]>'); }); test('supports encoding', t => { @@ -132,7 +134,7 @@ test('streams end properly', t => { elem.push({ toy: 'Transformers' }); elem.push({ toy: 'GI Joe' }); - elem.push({ toy: [{name:'He-man'}] }); + elem.push({ toy: [{name: 'He-man'}] }); elem.close(); xmlStream.on('data', (data: any) => { diff --git a/xml2json/tslint.json b/xml2json/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/xml2json/tslint.json +++ b/xml2json/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/xml2json/xml2json-tests.ts b/xml2json/xml2json-tests.ts index ede4486f2c..409fc5f27e 100644 --- a/xml2json/xml2json-tests.ts +++ b/xml2json/xml2json-tests.ts @@ -1,15 +1,15 @@ -import * as parser from 'xml2json' +import * as parser from 'xml2json'; var xml = "bar"; -// xml to json +// xml to json var jsonString: string = parser.toJson(xml); -// json to xml +// json to xml var xml: string = parser.toXml(jsonString); // xml to json in object mode and JsonOptions -var jsonObject: Object = parser.toJson(xml, { +var jsonObject: {} = parser.toJson(xml, { object: true, reversible: false, coerce: false, diff --git a/xmlrpc/index.d.ts b/xmlrpc/index.d.ts index b962be4324..8425d4672c 100644 --- a/xmlrpc/index.d.ts +++ b/xmlrpc/index.d.ts @@ -84,6 +84,13 @@ declare module 'xmlrpc' { decodeIso8601(time: string): Date; encodeIso8601(date: Date): string; } + + export class CustomType { + tagName: string; + raw: string; + constructor(raw: string); + serialize(xml: any): any; // XMLElementOrXMLNode declared by xmlbuilder + } } export = xmlrpc; diff --git a/xmlrpc/xmlrpc-tests.ts b/xmlrpc/xmlrpc-tests.ts index a7e8dcffbe..b9cdff2e3f 100644 --- a/xmlrpc/xmlrpc-tests.ts +++ b/xmlrpc/xmlrpc-tests.ts @@ -23,4 +23,14 @@ const server = xmlrpc.createServer(serverOpts, () => { client.methodCall('hello', ['world'], (err, val) => { console.log(val); }); + + class Value extends xmlrpc.CustomType { + constructor(value: any) { + super(value); + this.tagName = 'Value'; + } + } + client.methodCall('hello', [new Value('custom_string_value')], (err, val) => { + console.log(val); + }); }); diff --git a/xmpp-jid/index.d.ts b/xmpp-jid/index.d.ts new file mode 100644 index 0000000000..678e306abc --- /dev/null +++ b/xmpp-jid/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for @xmpp/jid 0.0 +// Project: github.com/node-xmpp/node-xmpp/ +// Definitions by: PJakcson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 +import {JID} from './lib/JID'; + +export declare function createJID(local: string, domain: string, resource: string): JID; + +export {JID} from './lib/JID'; + +export declare function equal(a: JID, b: JID): boolean; +export declare function is(a: any): boolean; diff --git a/xmpp-jid/lib/JID.d.ts b/xmpp-jid/lib/JID.d.ts new file mode 100644 index 0000000000..a1d2558b30 --- /dev/null +++ b/xmpp-jid/lib/JID.d.ts @@ -0,0 +1,46 @@ +/** + * Created by marcneumann on 17.02.17. + */ + +export declare class JID { + local: string; + domain: string; + resource: string; + + constructor(local: string, domain?: string, resource?: string); + + parseJID(jid: string): void; + + toString(unescape?: any): string; + + /** + * Convenience method to distinguish users + **/ + bare(): JID; + + /** + * Comparison function + **/ + equals(other: JID): boolean; + + /** + * http://xmpp.org/rfcs/rfc6122.html#addressing-localpart + **/ + setLocal(local: string, escape?: any): void; + + getLocal(unescape?: any): string; + + /** + * http://xmpp.org/rfcs/rfc6122.html#addressing-domain + */ + setDomain(value: string): void; + + getDomain(): string; + + /** + * http://xmpp.org/rfcs/rfc6122.html#addressing-resourcepart + */ + setResource(value: string): void; + + getResource(): string; +} diff --git a/xmpp-jid/tsconfig.json b/xmpp-jid/tsconfig.json new file mode 100644 index 0000000000..f4d02187a2 --- /dev/null +++ b/xmpp-jid/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "xmpp-jid-tests.ts" + ] +} \ No newline at end of file diff --git a/xmpp-jid/tslint.json b/xmpp-jid/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/xmpp-jid/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/xmpp-jid/xmpp-jid-tests.ts b/xmpp-jid/xmpp-jid-tests.ts new file mode 100644 index 0000000000..6b33b2c349 --- /dev/null +++ b/xmpp-jid/xmpp-jid-tests.ts @@ -0,0 +1,40 @@ +import {JID} from './index'; + +/* + * All return an instance of JID.JID, the new operator is optional. + */ +let addr = new JID('alice@wonderland.net/rabbithole'); // OK +addr = new JID('alice', 'wonderland.net', 'rabbithole'); // BEST; see section on escaping below + +/* + * local + */ +addr.local = 'alice'; +addr.local; // alice +// same as +addr.setLocal('alice'); +addr.getLocal(); // alice + +/* + * domain + */ +addr.domain = 'wonderland.net'; +addr.domain; // wonderland.net +// same as +addr.setDomain('wonderland.net'); +addr.getDomain(); // wonderland.net + +/* + * resource + */ +addr.resource = 'rabbithole'; +addr.resource; // rabbithole +// same as +addr.setResource('rabbithole'); +addr.getResource(); // rabbithole + +addr.toString(); // alice@wonderland.net/rabbithole +addr.bare(); // returns a JID without resource + +let some_jid = new JID('is', 'a', 'test'); +addr.equals(some_jid); // returns true if the two JIDs are equal, false otherwise diff --git a/xrm/index.d.ts b/xrm/index.d.ts index bd70a6098d..02bce0468e 100644 --- a/xrm/index.d.ts +++ b/xrm/index.d.ts @@ -1,6 +1,10 @@ -// Type definitions for Microsoft Dynamics xRM API v8.2 +// Type definitions for Microsoft Dynamics xRM API 8.2 // Project: http://www.microsoft.com/en-us/download/details.aspx?id=44567 -// Definitions by: David Berry , Matt Ngan , Markus Mauch , Daryl LaBar , Tully H +// Definitions by: David Berry +// Matt Ngan +// Markus Mauch +// Daryl LaBar +// Tully H // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -243,12 +247,12 @@ declare namespace Xrm * Client Types for Xrm.Page.context.getClient(). */ export type Client = "Web" | "Outlook" | "Mobile"; - + /** * Client States for Xrm.Page.context.getClientState(). */ export type ClientState = "Online" | "Offline"; - + /** * Themes for Xrm.Page.context.getCurrentTheme(). */ @@ -391,7 +395,7 @@ declare namespace Xrm /** * Defines save options to control how appointment, recurring appointment, or service activity records are processed. - * + * * @see {@link https://msdn.microsoft.com/en-us/library/dn481607.aspx#Anchor_2} for details. */ export interface SaveOptions @@ -402,7 +406,7 @@ declare namespace Xrm */ UseSchedulingEngine?: boolean; } - + /** * Interface for the Xrm.Page.data object. */ @@ -423,7 +427,7 @@ declare namespace Xrm * @return {Async.XrmPromise} Returns an asynchronous promise. */ save(): Async.XrmPromise; - + /** * Asynchronously saves the record with the option to set callback functions to be executed after the save operation is completed. * @@ -461,11 +465,12 @@ declare namespace Xrm * * @return true if it succeeds, otherwise false. * - * @remarks Values for level are: ERROR Notification will use the system error icon. * WARNING Notification will use the system warning icon. + * @remarks Values for level are: ERROR Notification will use the system error icon. + * WARNING Notification will use the system warning icon. * INFO Notification will use the system info icon. */ setFormNotification( message: string, level: Page.ui.FormNotificationLevel, uniqueId: string ): boolean; - + /** * Clears the form notification described by uniqueId. * @@ -548,7 +553,7 @@ declare namespace Xrm * A reference to the collection of tabs on the form. */ tabs: Collection.ItemCollection; - + /** * A collection of all the quick view controls on a form using the new form rendering engine (also called "turbo forms"). */ @@ -680,7 +685,7 @@ declare namespace Xrm * Called when the operation is successful. */ export type SuccessCallbackDelegate = () => void; - + /** * Called when the operation fails. * @@ -696,7 +701,7 @@ declare namespace Xrm * @see {Xrm.Utility.openQuickCreate} */ export type QuickCreateSuccessCallbackDelegate = ( record: OpenQuickCreateSuccessCallbackObject ) => void; - + /** * Called when the offline operation is successful. * @@ -713,7 +718,7 @@ declare namespace Xrm * * @see {Xrm.Mobile.offline.retrieveMultipleRecords} */ - export type OfflineRetrieveMultipleSuccessCallbackDelegate = (resultSet: { [key: string]: any }[]) => void; + export type OfflineRetrieveMultipleSuccessCallbackDelegate = (resultSet: Array<{ [key: string]: any }>) => void; /** * Called when the operation fails. @@ -766,7 +771,7 @@ declare namespace Xrm */ logicalName: string; } - + /** * Object passed to OfflineErrorCallbackDelegate. */ @@ -905,17 +910,17 @@ declare namespace Xrm * Requirement Level for Xrm.Page.Attribute.getRequiredLevel() and Xrm.Page.Attribute.setRequiredLevel(). */ export type RequirementLevel = "none" | "recommended" | "required"; - + /** * Save Modes for Xrm.Page.Entity.save(). */ export type SaveMode = "saveandclose" | "saveandnew"; - + /** * Status for Xrm.Page.Stage.getStatus(). */ export type Status = "active" | "inactive"; - + /** * Submit Mode for Xrm.Page.Attribute.getSubmitMode() and Xrm.Page.Attribute.setSubmitMode(). */ @@ -925,7 +930,7 @@ declare namespace Xrm * Control type for Xrm.Page.ui.QuickForm.getControlType(). */ export type ControlQuickFormType = "quickform"; - + /** * Control types for Xrm.Page.Control.getControlType(). */ @@ -960,7 +965,7 @@ declare namespace Xrm * Attribute formats for Xrm.Page.Attribute.getFormat(). */ export type AttributeFormat = DateAttributeFormat | IntegerAttributeFormat | OptionSetAttributeFormat | StringAttributeFormat; - + /** * Interface for a CRM Business Process Flow instance. */ @@ -1161,7 +1166,7 @@ declare namespace Xrm * @return The label. */ getLabel(): string; - + /** * Sets the label. * @@ -1182,7 +1187,7 @@ declare namespace Xrm */ getVisible(): boolean; } - + /** * Base interface for standard UI elements. */ @@ -1206,7 +1211,7 @@ declare namespace Xrm */ setFocus(): void; } - + /** * Interface for controls which methods provide immediate feedback or take actions as user types in a control. * Contains methods which can be used to perform data validations in a control even before the user commits (saves) the value in a form. @@ -1390,7 +1395,7 @@ declare namespace Xrm * string */ getAttributeType(): string; - + /** * Gets the attribute format. * @@ -1484,7 +1489,7 @@ declare namespace Xrm * A collection of all the controls on the form that interface with this attribute. */ controls: Collection.ItemCollection; - + /** * Gets the value. * @@ -1516,7 +1521,7 @@ declare namespace Xrm * none */ getFormat(): IntegerAttributeFormat; - + /** * Gets the maximum value allowed. * @@ -1553,7 +1558,7 @@ declare namespace Xrm * @remarks Attributes on Quick Create Forms will not save values set with this method. */ setValue( value: number ): void; - + /** * A collection of all the controls on the form that interface with this attribute. */ @@ -1580,7 +1585,7 @@ declare namespace Xrm * url */ getFormat(): StringAttributeFormat; - + /** * Gets maximum length allowed. * @@ -1671,7 +1676,7 @@ declare namespace Xrm * datetime */ getFormat(): DateAttributeFormat; - + /** * Gets the value. * @@ -1687,7 +1692,7 @@ declare namespace Xrm * @remarks Attributes on Quick Create Forms will not save values set with this method. */ setValue( value: Date ): void; - + /** * A collection of all the controls on the form that interface with this attribute. */ @@ -1710,7 +1715,7 @@ declare namespace Xrm * timezone */ getFormat(): OptionSetAttributeFormat; - + /** * Gets the option matching a value. * @@ -1768,7 +1773,7 @@ declare namespace Xrm * with this method. */ setValue( value: number ): void; - + /** * A collection of all the controls on the form that interface with this attribute. */ @@ -1804,7 +1809,7 @@ declare namespace Xrm * @remarks Attributes on Quick Create Forms will not save values set with this method. */ setValue( value: LookupValue[] ): void; - + /** * A collection of all the controls on the form that interface with this attribute. */ @@ -1993,7 +1998,7 @@ declare namespace Xrm * Use this method to asynchronously retrieve the enabled business process flows that the user can switch to for an * entity. * - * @param {Function} callbackFunction The callback function must accept a parameter that contains an object with + * @param {Function} callbackFunction The callback function must accept a parameter that contains an object with * dictionary properties where the name of the property is the Id of the * business process flow and the value of the property is the name of the * business process flow. @@ -2031,7 +2036,7 @@ declare namespace Xrm * @param {ContextSensitiveHandler} handler The function will be added to the bottom of the event * handler pipeline. The execution context is automatically * set to be the first parameter passed to the event handler. - * + * * Use a reference to a named function rather than an * anonymous function if you may later want to remove the * event handler. @@ -2088,9 +2093,9 @@ declare namespace Xrm /** * Represents a key-value pair, where the key is the Process Flow's ID, and the value is the name thereof. */ - export type ProcessDictionary = { [index: string]: string }; + export interface ProcessDictionary { [index: string]: string; } } - + /** * Interface for Xrm.Page.ui controls. * @@ -2117,7 +2122,7 @@ declare namespace Xrm * customsubgrid: . (A custom dataset control for mobile phone and tablet clients). */ getControlType(): ControlType | string; - + /** * Gets the name of the control on the form. * @@ -2143,7 +2148,7 @@ declare namespace Xrm */ getParent(): Section; } - + /** * Interface for a standard control. * @@ -2161,14 +2166,14 @@ declare namespace Xrm * @remarks If the uniqueId parameter is not used, the current notification shown will be removed. */ clearNotification( uniqueId?: string ): boolean; - + /** * Gets a boolean value, indicating whether the control is disabled. * * @return true if it is disabled, otherwise false. */ getDisabled(): boolean; - + /** * Sets the state of the control to either enabled, or disabled. * @@ -2211,7 +2216,7 @@ declare namespace Xrm * This is not an Entity Lookup, but a control that supports AutoComplete / KeyPress Events (Text or Number) * * @remarks This interface is not supported for CRM mobile clients (phones or tablets) and the interactive service hub. It is only available for Updated entities. - * + * * @sa StandardControl */ export interface AutoLookupControl extends StandardControl, UiKeyPressable @@ -2228,11 +2233,11 @@ declare namespace Xrm * Hides the auto-completion drop-down list configured for a specific text field */ hideAutoComplete(): void; - + /** * Shows upt to 10 matching strings in a drop-down list as users press keys to type charactrer in a specific text field. * On selecting an item in the drop-down list, the value in the text field changes to the selected item, the drop-down list disappears, and the OnChange event for the text field is invoked - * @param resultSet + * @param resultSet */ showAutoComplete(resultSet: AutoCompleteResultSet): void; } @@ -2841,7 +2846,7 @@ declare namespace Xrm * @remarks Constituent controls in a quick view control are read only. */ getControl( controlName: string ): Page.Control; - + /** * Gets a control by index. * @@ -2853,7 +2858,7 @@ declare namespace Xrm * @remarks Constituent controls in a quick view control are read only. */ getControl( index: number ): T; - + /** * Gets a control by index. * @@ -2974,13 +2979,13 @@ declare namespace Xrm /** * Command Bar Display options for Xrm.Url.FormOpenParameters.cmdbar, Xrm.Url.ViewOpenParameters.cmdbar, and Xrm.Utility.FormOpenParameters.cmdbar. */ - + export type CmdBarDisplay = "true" | "false"; /** * Navigation Bar Display options for Xrm.Url.FormOpenParameters.navbar, Xrm.Url.ViewOpenParameters.navbar, and Xrm.Utility.FormOpenParameters.navbar. */ export type NavBarDisplay = "entity" | "off" | "on"; - + /** * Report Open Action options for Xrm.Url.ReportOpenParameters.actions. */ diff --git a/xrm/tslint.json b/xrm/tslint.json index 0e45822b24..a11cf19d39 100644 --- a/xrm/tslint.json +++ b/xrm/tslint.json @@ -1,38 +1,64 @@ -{ - "rules": { - "class-name": true, - "comment-format": [ true, "check-space" ], - "indent": [ true, "spaces" ], - "no-duplicate-variable": true, - "no-eval": true, - "no-internal-module": false, - "no-trailing-whitespace": false, - "no-var-keyword": true, - "one-line": [ true, "check-whitespace" ], - "quotemark": [ true, "double" ], - "semicolon": true, - "triple-equals": [ true, "allow-null-check" ], - "align": [ true, "parameters", "statements" ], - "jsdoc-format": true, - "no-consecutive-blank-lines": true, - "typedef-whitespace": [ - true, - { - "call-signature": "nospace", - "index-signature": "nospace", - "parameter": "nospace", - "property-declaration": "nospace", - "variable-declaration": "nospace" - } - ], - "variable-name": [ true, "ban-keywords" ], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] - } -} \ No newline at end of file +{ + "extends": "../tslint.json", + "rules": { + // TODOs + "callable-types": false, + "unified-signatures": false, + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces" + ], + "no-duplicate-variable": true, + "no-eval": true, + "no-internal-module": false, + "no-trailing-whitespace": false, + "no-var-keyword": true, + "one-line": [ + true, + "check-whitespace" + ], + "quotemark": [ + true, + "double" + ], + "semicolon": true, + "triple-equals": [ + true, + "allow-null-check" + ], + "align": [ + true, + "parameters", + "statements" + ], + "jsdoc-format": true, + "no-consecutive-blank-lines": true, + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + } + ], + "variable-name": [ + true, + "ban-keywords" + ], + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ] + } +} diff --git a/xrm/xrm-tests.ts b/xrm/xrm-tests.ts index 41f06cbf1e..0ef578aac0 100644 --- a/xrm/xrm-tests.ts +++ b/xrm/xrm-tests.ts @@ -4,7 +4,7 @@ window.Xrm.Utility.alertDialog( "message", () => {} ); parent.Xrm.Page.context.getOrgLcid(); -/// Demonstrate clientglobalcontext.d.ts +/// Demonstrate clientglobalcontext.d.ts function _getContext() { @@ -69,7 +69,9 @@ if (Xrm.Page.data.process != null) /// Demonstrate v7.1 Quick Create form -Xrm.Utility.openQuickCreate("account").then(( object ) => { if (object) alert( `Newly created record Id: ${object.savedEntityReference.id}` ); }, (error) => {console.log(`Code: ${error.errorCode}, Message: ${error.message}`); }); +Xrm.Utility.openQuickCreate("account").then( + (object) => { if (object) alert( `Newly created record Id: ${object.savedEntityReference.id}` ); }, + (error) => {console.log(`Code: ${error.errorCode}, Message: ${error.message}`); }); /// Make all controls visible. @@ -117,7 +119,7 @@ optionSetAttribute.controls.get(0).setFocus(); let level: Xrm.Page.ui.FormNotificationLevel; level = "ERROR"; -Xrm.Page.ui.setFormNotification("Test", level, "uniqueId"); +Xrm.Page.ui.setFormNotification("Test", level, "uniqueId"); /// Demonstrate Requirement Level and Submit Mode both via string parameters and String Literal Types @@ -151,7 +153,7 @@ const resultSet: Xrm.Page.AutoCompleteResultSet = { // accounts in CRM. window.open("http://www.microsoft.com/en-us/dynamics/crm-customer-center/create-or-edit-an-account.aspx"); } - } as Xrm.Page.AutoCompleteCommand + } as Xrm.Page.AutoCompleteCommand }; resultSet.results.push({ id: 0, diff --git a/xsd-schema-validator/xsd-schema-validator-tests.ts b/xsd-schema-validator/xsd-schema-validator-tests.ts index f210198ade..d66148d219 100644 --- a/xsd-schema-validator/xsd-schema-validator-tests.ts +++ b/xsd-schema-validator/xsd-schema-validator-tests.ts @@ -2,7 +2,7 @@ import fs = require("fs"); import validator = require("xsd-schema-validator"); -validator.validateXML("", 'resources/foo.xsd', function(err, result) { +validator.validateXML("", 'resources/foo.xsd', (err, result) => { if (err) { throw err; } else return result.valid; diff --git a/yeoman-generator/index.d.ts b/yeoman-generator/index.d.ts index 0110e536d6..5f6e79896a 100644 --- a/yeoman-generator/index.d.ts +++ b/yeoman-generator/index.d.ts @@ -68,6 +68,7 @@ declare class Base extends EventEmitter { appname: string; config: Base.Storage; fs: Base.MemFsEditor; + options: {}; log(message?: string, context?: any): void; argument(name: string, config: Base.ArgumentConfig): this; diff --git a/yeoman-generator/tslint.json b/yeoman-generator/tslint.json index ec365f164b..377cc837d4 100644 --- a/yeoman-generator/tslint.json +++ b/yeoman-generator/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/yeoman-generator/yeoman-generator-tests.ts b/yeoman-generator/yeoman-generator-tests.ts index fb3be4ce05..e54d0aae4a 100644 --- a/yeoman-generator/yeoman-generator-tests.ts +++ b/yeoman-generator/yeoman-generator-tests.ts @@ -5,16 +5,16 @@ import { EventEmitter } from 'events'; class MyES2015Generator extends Base {} const MyGenerator = Base.extend({ - writing: function(this: Base): void { + writing(this: Base): void { this.fs.write('var foo = 1;', this.destinationPath('index.js')); } -}) +}); const generator = new MyES2015Generator(['arg1', 'arg2'], { opt1: 'foo', opt2: 3, opt3: false }); const eventEmitter: EventEmitter = generator; -const env: Object = generator.env; -const args: Object = generator.args; +const env: {} = generator.env; +const args: {} = generator.args; const resolved: string = generator.resolved; const description: string = generator.description; const appname: string = generator.appname; @@ -52,7 +52,7 @@ generator.installDependencies(); generator.installDependencies({ bower: true, npm: true, - callback: function () { + callback() { console.log('Everything is ready!'); } });

    This namespace declares an unspecified number of objects: _1, _2, _3, ..., which are - * used to specify placeholders in calls to function {@link std.bind}.