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 a822c69c47..23bb52f13c 100644 --- a/README.md +++ b/README.md @@ -169,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/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-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/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/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/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/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 b8a1b0dc86..4627c2c5b3 100644 --- a/body-parser/index.d.ts +++ b/body-parser/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for body-parser // Project: http://expressjs.com -// Definitions by: Santi Albo , VILIC VANE , Jonathan Häberle +// Definitions by: Santi Albo , VILIC VANE , Jonathan Häberle , Gevik Babakhani // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -41,7 +41,14 @@ declare function bodyParser(options?: { }): express.RequestHandler; declare namespace bodyParser { - export function json(options?: { + + /** + * Interface for defining the options for the json() middleware + * + * @export + * @interface JsonOptions + */ + export interface JsonOptions { /** * if deflated bodies will be inflated. (default: true) */ @@ -66,9 +73,15 @@ declare namespace bodyParser { * passed to JSON.parse(). */ reviver?: (key: string, value: any) => any; - }): express.RequestHandler; + } - export function raw(options?: { + /** + * Interface for defining the options the raw() middleware + * + * @export + * @interface RawOptions + */ + export interface RawOptions { /** * if deflated bodies will be inflated. (default: true) */ @@ -85,9 +98,15 @@ declare namespace bodyParser { * function to verify body content, the parsing can be aborted by throwing an error. */ verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - }): express.RequestHandler; + } - export function text(options?: { + /** + * Interface for defining the options for the text() middleware + * + * @export + * @interface TextOptions + */ + export interface TextOptions { /** * if deflated bodies will be inflated. (default: true) */ @@ -108,9 +127,15 @@ declare namespace bodyParser { * the default charset to parse as, if not specified in content-type. (default: 'utf-8') */ defaultCharset?: string; - }): express.RequestHandler; + } - export function urlencoded(options: { + /** + * Interface for defining the options for the urlencoded() middleware + * + * @export + * @interface UrlEncodedOptions + */ + export interface UrlEncodedOptions { /** * if deflated bodies will be inflated. (default: true) */ @@ -131,7 +156,47 @@ declare namespace bodyParser { * parse extended syntax with the qs module. */ extended: boolean; - }): express.RequestHandler; + } + + /** + * Returns middleware that only parses json. This parser accepts any Unicode encoding + * of the body and supports automatic inflation of gzip and deflate encodings. + * + * @export + * @param {JsonOptions} [options] + * @returns {express.RequestHandler} + */ + export function json(options?: JsonOptions): express.RequestHandler; + + /** + * Returns middleware that parses all bodies as a Buffer. This parser supports automatic + * inflation of gzip and deflate encodings. + * + * @export + * @param {RawOptions} [options] + * @returns {express.RequestHandler} + */ + export function raw(options?: RawOptions): express.RequestHandler; + + /** + * Returns middleware that parses all bodies as a string. This parser supports + * automatic inflation of gzip and deflate encodings. + * + * @export + * @param {TextOptions} [options] + * @returns {express.RequestHandler} + */ + export function text(options?: TextOptions): express.RequestHandler; + + /** + * Returns middleware that only parses urlencoded bodies. This parser accepts only + * UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings. + * + * @export + * @param {UrlEncodedOptions} [options] + * @returns {express.RequestHandler} + */ + export function urlencoded(options?: UrlEncodedOptions): express.RequestHandler; } export = bodyParser; 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-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/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/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/index.d.ts b/cucumber/index.d.ts index 8c56e3aae4..a8b85539ce 100644 --- a/cucumber/index.d.ts +++ b/cucumber/index.d.ts @@ -208,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/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/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/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/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/japanese-holidays-tests.ts b/japanese-holidays/japanese-holidays-tests.ts index 7a8e243d3a..32f760360e 100644 --- a/japanese-holidays/japanese-holidays-tests.ts +++ b/japanese-holidays/japanese-holidays-tests.ts @@ -1,22 +1,22 @@ -import {isHoliday, isHolidayAt, getHolidaysOf} from 'japanese-holidays' +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 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 noFurikae: string | undefined = isHoliday(date, false); -const hAt = isHolidayAt(date) -if (hAt != undefined) { - hAt.charAt(0) +const hAt = isHolidayAt(date); +if (hAt !== undefined) { + hAt.charAt(0); } -isHolidayAt(date, false) +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 +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 index 49677d134f..11826ce711 100644 --- a/japanese-holidays/tsconfig.json +++ b/japanese-holidays/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", "japanese-holidays-tests.ts" ] -} +} \ No newline at end of file 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..a2a7415093 100644 --- a/jasmine-data_driven_tests/index.d.ts +++ b/jasmine-data_driven_tests/index.d.ts @@ -1,4 +1,4 @@ -// 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 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/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/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/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/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 51c609e296..f38d2e9fdd 100644 --- a/koa-hbs/index.d.ts +++ b/koa-hbs/index.d.ts @@ -37,7 +37,7 @@ declare namespace Hbs { layoutsPath?: string, contentHelperName?: string, blockHelperName?: string, - disableCache?: boolean + disableCache?: boolean } } @@ -50,7 +50,7 @@ declare const hbs: Hbs; export = hbs; declare module "koa" { - export interface Context extends Request, Response { + export interface Context { render(tpl: string, locals?: {[key: string]: any}): Promise; } } \ No newline at end of file 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..4671a672f3 100644 --- a/lodash/index.d.ts +++ b/lodash/index.d.ts @@ -12701,7 +12701,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 +19446,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..ccfc270e10 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 @@ -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,7 +1060,7 @@ 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 * }); * ``` @@ -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 @@ -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 @@ -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,7 +2118,7 @@ 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. @@ -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/ltx/tsconfig.json b/ltx/tsconfig.json new file mode 100644 index 0000000000..28beec26d4 --- /dev/null +++ b/ltx/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", + "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/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/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..0eb949e57b 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 { 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/modesl-tests.ts b/modesl/modesl-tests.ts index 89bc5dcedb..c3788833d0 100644 --- a/modesl/modesl-tests.ts +++ b/modesl/modesl-tests.ts @@ -8,7 +8,7 @@ const freeswitchListener = new modesl.Server(() => { const freeswitchConnection = new modesl.Connection("freeswitch-host", 8021, 'password', () => { // console.log('connection initialized'); - freeswitchConnection.api('conference', ['confname', 'dial', 'user/1006']) + freeswitchConnection.api('conference', ['confname', 'dial', 'user/1006']); freeswitchConnection.bgapi('conference', ['confname', 'dial', 'user/1006'], 'job-id', () => { // console.log('action queued'); 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..7ef5615436 100644 --- a/mongoose/index.d.ts +++ b/mongoose/index.d.ts @@ -2163,6 +2163,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/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-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/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 applications 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 applications 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 applications 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 windows 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 applications 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 applications 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 applications 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 applications 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 windows 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 applications 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/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/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-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/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/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..6c17fb4cee 100644 --- a/react-bootstrap/index.d.ts +++ b/react-bootstrap/index.d.ts @@ -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; diff --git a/react-bootstrap/react-bootstrap-tests.tsx b/react-bootstrap/react-bootstrap-tests.tsx index 00bfae517c..f3772d0fef 100644 --- a/react-bootstrap/react-bootstrap-tests.tsx +++ b/react-bootstrap/react-bootstrap-tests.tsx @@ -528,7 +528,7 @@ export class ReactBootstrapTest extends Component { React-Bootstrap - + {} } />
    - +
    @@ -1227,7 +1227,7 @@ export class ReactBootstrapTest extends Component { Help block message. - + 1 {' '} 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/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-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 6b540a9309..2f95939db6 100644 --- a/react-native/index.d.ts +++ b/react-native/index.d.ts @@ -5533,7 +5533,15 @@ declare module "react" { * is false. */ keyboardShouldPersistTaps?: boolean - + + /** + * 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. * The frequency of the events can be contolled using the scrollEventThrottle prop. 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 bf76875f3a..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.11 +// 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,7 @@ 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; } 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-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-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/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 867e066c7e..25f2264387 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 @@ -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; @@ -2585,6 +2586,7 @@ declare namespace React { // SVG svg: SVGFactory; + animate: SVGFactory; circle: SVGFactory; defs: SVGFactory; ellipse: SVGFactory; @@ -2812,6 +2814,7 @@ declare global { // SVG svg: React.SVGProps; + animate: React.SVGProps; // TODO: It is SVGAnimateElement but is not in TypeScript's lib.dom.d.ts for now. 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 702f1632c9..f0fee7a00b 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(); 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-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..d576c82e3b 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; 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/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/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 85283ff468..fda7cad2f5 100644 --- a/sequelize/index.d.ts +++ b/sequelize/index.d.ts @@ -4768,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; + } /** diff --git a/sequelize/sequelize-tests.ts b/sequelize/sequelize-tests.ts index 9a54ea6d64..20af1246d4 100644 --- a/sequelize/sequelize-tests.ts +++ b/sequelize/sequelize-tests.ts @@ -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 }, diff --git a/service_worker_api/service_worker_api-tests.ts b/service_worker_api/service_worker_api-tests.ts index b2e183aa05..5cfae785cc 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,7 +186,7 @@ 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('/'); })); 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/three/index.d.ts b/three/index.d.ts index 100e3ecf8c..7b76100c17 100644 --- a/three/index.d.ts +++ b/three/index.d.ts @@ -22,6 +22,7 @@ /// /// /// +/// declare namespace THREE { export const REVISION: string; 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; - }; - var xf = t.mapcat(reverse); - t.into([], xf, [[3,2,1],[6,5,4]]); // [1,2,3,4,5,6] +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] } 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/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/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..4f6ae6e211 100644 --- a/webpack/index.d.ts +++ b/webpack/index.d.ts @@ -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. */ @@ -759,7 +766,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..c1369f78bc 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( @@ -284,9 +284,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 +326,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 +338,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 +372,7 @@ plugin = new webpack.LoaderOptionsPlugin({ // returns a Compiler instance webpack({ // configuration -}, function(err, stats) { +}, (err, stats) => { // ... }); @@ -383,7 +381,7 @@ var compiler = webpack({ // configuration }); -compiler.run(function(err, stats) { +compiler.run((err, stats) => { // ... }); // or @@ -391,19 +389,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 +412,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 +438,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 +449,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 +467,7 @@ rule = { }, loader: "./loader", options: "third" -} +}; configuration = { module: { @@ -499,7 +497,7 @@ configuration = { { loader: "./loader", options: { - get: function() { return "second-3"; } + get: () => "second-3" } } ] @@ -517,19 +515,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 +546,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/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!'); } });