diff --git a/.editorconfig b/.editorconfig index 5ebf4a129c..d3bd86c3ba 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,9 +1,9 @@ root = true [*] +indent_size = 4 trim_trailing_whitespace = true insert_final_newline = true [{*.json,*.yml}] indent_style = space -indent_size = 2 diff --git a/notNeededPackages.json b/notNeededPackages.json index 8cf6a8ce83..4a3280ccb0 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -18,6 +18,12 @@ "sourceRepoURL": "https://github.com/doxout/anydb-sql", "asOfVersion": "0.6.46" }, + { + "libraryName": "apn", + "typingsPackageName": "apn", + "sourceRepoURL": "https://github.com/node-apn/node-apn", + "asOfVersion": "2.1.2" + }, { "libraryName": "Argon2", "typingsPackageName": "argon2", diff --git a/types/alexa-sdk/alexa-sdk-tests.ts b/types/alexa-sdk/alexa-sdk-tests.ts index 1454309b93..c384bf194d 100644 --- a/types/alexa-sdk/alexa-sdk-tests.ts +++ b/types/alexa-sdk/alexa-sdk-tests.ts @@ -2,6 +2,7 @@ import * as Alexa from "alexa-sdk"; const handler = (event: Alexa.RequestBody, context: Alexa.Context, callback: () => void) => { let alexa = Alexa.handler(event, context); + alexa.resources = {}; alexa.registerHandlers(handlers); alexa.execute(); }; diff --git a/types/alexa-sdk/index.d.ts b/types/alexa-sdk/index.d.ts index 24baccf484..d5892f6ec7 100644 --- a/types/alexa-sdk/index.d.ts +++ b/types/alexa-sdk/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Pete Beegle // Huw // pascalwhoop +// Ben // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -20,6 +21,7 @@ export interface AlexaObject extends Handler { state: any; appId: any; response: any; + resources: any; dynamoDBTableName: any; saveBeforeResponse: boolean; registerHandlers: (...handlers: Array>) => any; diff --git a/types/angular-clipboard/angular-clipboard-tests.ts b/types/angular-clipboard/angular-clipboard-tests.ts index 00c5074ec5..6df5af0c5e 100644 --- a/types/angular-clipboard/angular-clipboard-tests.ts +++ b/types/angular-clipboard/angular-clipboard-tests.ts @@ -1,5 +1,5 @@ import * as angular from "angular"; -import {ClipboardService} from "angular-clipboard"; +import { ClipboardService } from "angular-clipboard"; interface TestScope extends ng.IScope { [index: string]: any; diff --git a/types/angular/angular-component-router.d.ts b/types/angular/angular-component-router.d.ts index da3afc7a71..b8c939f7c8 100644 --- a/types/angular/angular-component-router.d.ts +++ b/types/angular/angular-component-router.d.ts @@ -15,7 +15,7 @@ declare namespace angular { * ### Example * * ``` - * import {Component} from 'angular2/core'; + * import { Component } from 'angular2/core'; * import {bootstrap} from 'angular2/platform/browser'; * import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig} from 'angular2/router'; * diff --git a/types/apn/apn-tests.ts b/types/apn/apn-tests.ts deleted file mode 100644 index ea4bb34ae3..0000000000 --- a/types/apn/apn-tests.ts +++ /dev/null @@ -1,145 +0,0 @@ -import apn = require("apn"); - -//Hand made TypeScript tests -//========================== - -//Create with a hex string -var device1 = new apn.Device("ca11ab1e"); -//Create with a Buffer -var device2 = new apn.Device(new Buffer("ca55e77e")); - -//Create the notification -var notification = new apn.Notification(); -notification.alert = { - title: "The Title", - body: "This is the body", -}; -notification.badge = 5; -//Fluid api -notification.setAlertTitle("The Title") - .setAlertText("This is the body") - .setLaunchImage("LaunchImage"); - -//Establish the connection -var connection = new apn.Connection({ - cert: "path/to/cert.pem", - key: "path/to/cert.pem" -}); -//Testing some specialized event listeners -connection.on("error", (error) => { - console.log("push error", error.name, error.message); -}); -connection.on("transmissionError", (errorCode, notification, device) => { - console.log("push failed", errorCode, "notification", notification.alert, "device id: ", device.toString()); -}); - -//Send it using hex string -connection.pushNotification(notification, "ba5eba11"); -//Send it using Buffer -connection.pushNotification(notification, new Buffer("5ca1ab1e")); -//Send it using Device -connection.pushNotification(notification, device1); - -//Connecting to feedback service -var feedbackService = new apn.Feedback({ - cert: "path/to/cert.pem", - key: "path/to/cert.pem", - interval: 0 -}); -feedbackService.on("error", (error:Error) => { - console.log("push feedback error", error.name, error.message); -}); -function processFeedbackData(device:apn.Device, time:number) { -} -feedbackService.on("feedback", (feedbackData) => { - feedbackData.forEach((data) => { - processFeedbackData(data.device, data.time); - }) -}); -feedbackService.start(); - - -//Original examples from apn package -//================================== - -//sending-to-multiple-devices.js -//------------------------------ - -var tokens = ["", ""]; - -if(tokens[0] === "") { - console.log("Please set token to a valid device token for the push notification service"); - process.exit(); -} - -// Create a connection to the service using mostly default parameters. - -var service = new apn.connection({ production: false }); - -service.on("connected", function() { - console.log("Connected"); -}); - -service.on("transmitted", function(notification, device) { - console.log("Notification transmitted to:" + device.token.toString("hex")); -}); - -service.on("transmissionError", function(errCode, notification, device) { - console.error("Notification caused error: " + errCode + " for device ", device, notification); - if (errCode === 8) { - console.log("A error code of 8 indicates that the device token is invalid. This could be for a number of reasons - are you using the correct environment? i.e. Production vs. Sandbox"); - } -}); - -service.on("timeout", function () { - console.log("Connection Timeout"); -}); - -service.on("disconnected", function() { - console.log("Disconnected from APNS"); -}); - -service.on("socketError", console.error); - - -// If you plan on sending identical paylods to many devices you can do something like this. -function pushNotificationToMany() { - console.log("Sending the same notification each of the devices with one call to pushNotification."); - var note = new apn.notification(); - note.setAlertText("Hello, from node-apn!"); - note.badge = 1; - - service.pushNotification(note, tokens); -} - -pushNotificationToMany(); - - -// If you have a list of devices for which you want to send a customised notification you can create one and send it to and individual device. -function pushSomeNotifications() { - console.log("Sending a tailored notification to %d devices", tokens.length); - tokens.forEach(function(token, i) { - var note = new apn.notification(); - note.setAlertText("Hello, from node-apn! You are number: " + i); - note.badge = i; - - service.pushNotification(note, token); - }); -} - -pushSomeNotifications(); - -//feedback.js -//----------- - -function handleFeedback(feedbackData:apn.FeedbackData[]) { - feedbackData.forEach(function(feedbackItem) { - console.log("Device: " + feedbackItem.device.toString() + " has been unreachable, since: " + feedbackItem.time); - }); -} - -// Setup a connection to the feedback service using a custom interval (10 seconds) -var feedback = new apn.feedback({ production: false, interval: 10 }); - -feedback.on("feedback", handleFeedback); -feedback.on("feedbackError", console.error); diff --git a/types/apn/index.d.ts b/types/apn/index.d.ts deleted file mode 100644 index 96ce6e9720..0000000000 --- a/types/apn/index.d.ts +++ /dev/null @@ -1,364 +0,0 @@ -// Type definitions for node-apn -// Project: https://github.com/argon/node-apn -// Definitions by: Zenorbi -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -import events = require("events"); -import net = require("net"); -export interface ConnectionOptions { - /** - * The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`) - */ - cert?: string | Buffer; - /** - * The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`) - */ - key?: string | Buffer; - /** - * An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). - */ - ca?: (string | Buffer)[]; - /** - * File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will always be used instead of certificate and key above. - */ - pfx?: string | Buffer; - /** - * The passphrase for the connection key, if required - */ - passphrase?: string; - /** - * Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly) - */ - production?: boolean; - /** - * Enable when you are using a VoIP certificate to enable paylods up to 4096 bytes. - */ - voip?: boolean; - /** - * Gateway port (Defaults to: `2195`) - */ - port?: number; - /** - * Reject Unauthorized property to be passed through to tls.connect() (Defaults to `true`) - */ - rejectUnauthorized?: boolean; - /** - * Number of notifications to cache for error purposes (See "Handling Errors" below, (Defaults to: `1000`) - */ - cacheLength?: number; - /** - * Whether the cache should grow in response to messages being lost after errors. (Will still emit a 'cacheTooSmall' event) (Defaults to: `true`) - */ - autoAdjustCache?: boolean; - /** - * The maximum number of connections to create for sending messages. (Defaults to: `1`) - */ - maxConnections?: number; - /** - * The duration of time the module should wait, in milliseconds, when trying to establish a connection to Apple before failing. 0 = Disabled. {Defaults to: `10000`} - */ - connectTimeout?: number; - /** - * The duration the socket should stay alive with no activity in milliseconds. 0 = Disabled. (Defaults to: `3600000` - 1h) - */ - connectionTimeout?: number; - /** - * The maximum number of connection failures that will be tolerated before `apn` will "terminate". (Defaults to: 10) - */ - connectionRetryLimit?: number; - /** - * Whether to buffer notifications and resend them after failure. (Defaults to: `true`) - */ - buffersNotifications?: number; - /** - * Whether to aggresively empty the notification buffer while connected - if set to true node-apn may enter a tight loop under heavy load while delivering notifications. (Defaults to: `false`) - */ - fastMode?: boolean; -} -export declare class Connection extends events.EventEmitter { - constructor(options: ConnectionOptions); - /** - * This is the business end of the module. Create a `Notification` object and pass it in, along with a single recipient or an array of them and node-apn will take care of the rest, delivering the notification to each recipient. - * - * A "recipient" is either a `Device` object, a `String`, or a `Buffer` containing the device token. `Device` objects are used internally and will be created if necessary. Where applicable, all events will return a `Device` regardless of the type passed to this method. - */ - pushNotification(notification: Notification, recipient: Device | string | Buffer | (Device | string | Buffer)[]): void; - /** - * Used to manually adjust the "cacheLength" property in the options. This is ideal if you choose to use the `cacheTooSmall` event to tweak your environment. It is safe for increasing and reducing cache size. - */ - setCacheLength(newLength: number): void; - /** - * Indicate to node-apn that when the queue of pending notifications is fully drained that it should close all open connections. This will mean that if there are no other pending resources (open sockets, running timers, etc.) the application will terminate. If notifications are pushed after the connection has completely shutdown a new connection will be established and, if applicable, `shutdown` will need to be called again. - */ - shutdown(): void; - /** - * Emitted when an error occurs during initialisation of the module, usually due to a problem with the keys and certificates. - */ - on(event: "error", listener: (error: Error) => void): this; - /** - * Emitted when the connection socket experiences an error. This may be useful for debugging but no action should be necessary. - */ - on(event: "socketError", listener: (error: Error) => void): this; - /** - * Emitted when a notification has been sent to Apple - not a guarantee that it has been accepted by Apple, an error relating to it may occur later on. A notification may also be "transmitted" several times if a preceding notification caused an error requiring retransmission. - */ - on(event: "transmitted", listener: (notification: Notification, decive: Device) => void): this; - /** - * Emitted when all pending notifications have been transmitted to Apple and the pending queue is empty. This may be called more than once if a notification error occurs and notifications must be re-sent. - */ - on(event: "completed", listener: () => void): this; - /** - * Emitted when Apple returns a notification as invalid but the notification has already been expunged from the cache - usually due to high throughput and indicates that notifications will be getting lost. The parameter is an estimate of how many notifications have been lost. You should experiment with increasing the cache size or enabling ```autoAdjustCache``` if you see this frequently. - * - * **Note**: With ```autoAdjustCache``` enabled this event will still be emitted when an adjustment is triggered. - */ - on(event: "cacheTooSmall", listener: (sizeDifference: number) => void): this; - /** - * Emitted when a connection to Apple is successfully established. The parameter indicates the number of open connections. No action is required as the connection is managed internally. - */ - on(event: "connected", listener: (openSockets: net.Socket[]) => void): this; - /** - * Emitted when the connection to Apple has been closed, this could be for numerous reasons, for example an error has occurred or the connection has timed out. The parameter is the same as for `connected` and again, no action is required. - */ - on(event: "disconnected", listener: (openSockets: net.Socket[]) => void): this; - /** - * Emitted when the connectionTimeout option has been specified and no activity has occurred on a socket for a specified duration. The socket will be closed immediately after this event and a `disconnected` event will also be emitted. - */ - on(event: "timeout", listener: () => void): this; - /** - * Emitted when a message has been received from Apple stating that a notification was invalid or if an internal error occurred before that notification could be pushed to Apple. If the notification is still in the cache it will be passed as the second argument, otherwise null. Where possible the associated `Device` object will be passed as a third parameter, however in cases where the token supplied to the module cannot be parsed into a `Buffer` the supplied value will be returned. - - * Error codes smaller than 512 correspond to those returned by Apple as per their [docs][errors]. Other errors are applicable to `node-apn` itself. Definitions can be found in `lib/errors.js`. - */ - on(event: "transmissionError", listener: (errorCode: number, notification: Notification, device: Device | Buffer) => void): this; - on(event: string, listener: Function): this; -} -export interface NotificationAlertOptions { - title?: string; - subtitle?: string; - body: string; - "title-loc-key"?: string; - "title-loc-args"?: string[]; - "action-loc-key"?: string; - "loc-key"?: string; - "loc-args"?: string[]; - "launch-image"?: string; -} -export declare class Notification { - /** - * The maximum number of retries which should be performed when sending a notification if an error occurs. A value of 0 will only allow one attempt at sending (0 retries). Set to -1 to disable (default). - */ - public retryLimit: number; - /** - * The UNIX timestamp representing when the notification should expire. This does not contribute to the 2048 byte payload size limit. An expiry of 0 indicates that the notification expires immediately. - */ - public expiry: number; - /** - * From Apple's Documentation, Provide one of the following values: - * - * - 10 - The push message is sent immediately. (Default) - * > The push notification must trigger an alert, sound, or badge on the device. It is an error use this priority for a push that contains only the content-available key. - * - 5 - The push message is sent at a time that conserves power on the device receiving it. - */ - public priority: number; - /** - * The encoding to use when transmitting the notification to APNS, defaults to `utf8`. `utf16le` is also possible but as each character is represented by a minimum of 2 bytes, will at least halve the possible payload size. If in doubt leave as default. - */ - public encoding: string; - /** - * This object represents the root JSON object that you can add custom information for your application to. The properties below will only be added to the payload (under `aps`) when the notification is prepared for sending. - */ - public payload: any; - /** - * The value to specify for `payload.aps.badge` - */ - public badge: number; - /** - * The value to specify for `payload.aps.sound` - */ - public sound: string; - /** - * The value to specify for `payload.aps.alert` can be either a `String` or an `Object` as outlined by the payload documentation. - */ - public alert: string | NotificationAlertOptions; - /** - * Setting this to true will specify "content-available" in the payload when it is compiled. - */ - public newsstandAvailable: boolean; - /** - * Setting this to true will specify "content-available" in the payload when it is compiled. - */ - public contentAvailable: boolean; - /** - * The value to specify for the `mdm` field where applicable. - */ - public mdm: string | Object; - /** - * The value to specify for `payload.aps['url-args']`. This used for Safari Push NOtifications and should be an array of values in accordance with the Web Payload Documentation. - */ - public urlArgs: string[]; - /** - * When this parameter is set and `notification#trim()` is called it will attempt to truncate the string at the nearest space. - */ - public truncateAtWordEnd: boolean; - /** - * You can optionally pass in an object representing the payload, or configure properties on the returned object. - */ - constructor(payload?: any); - /** - * Set the `aps.alert` text body. This will use the most space-efficient means. - */ - setAlertText(alertText: string): Notification; - /** - * Set the `title` property of the `aps.alert` object - used with Safari Push Notifications - */ - setAlertTitle(alertTitle: string): Notification; - /** - * Set the `action` property of the `aps.alert` object - used with Safari Push Notifications - */ - setAlertAction(alertAction: string): Notification; - /** - * Set the `action-loc-key` property of the `aps.alert` object. - */ - setActionLocKey(key: string): Notification; - /** - * Set the `loc-key` property of the `aps.alert` object. - */ - setLocKey(key: string): Notification; - /** - * Set the `loc-args` property of the `aps.alert` object. - */ - setLocArgs(args: string[]): Notification; - /** - * Set the `launch-image` property of the `aps.alert` object. - */ - setLaunchImage(image: string): Notification; - /** - * Set the `mdm` property on the payload. - */ - setMDM(mdm: string | Object): Notification; - /** - * Set the `content-available` property of the `aps` object. - */ - setNewsstandAvailable(available: boolean): Notification; - /** - * Set the `content-available` property of the `aps` object. - */ - setContentAvailable(available: boolean): Notification; - /** - * Set the `url-args` property of the `aps` object. - */ - setUrlArgs(urlArgs: string[]): Notification; - /** - * Attempt to automatically trim the notification alert text body to meet the payload size limit of 2048 bytes. - */ - trim(): number; -} -export declare class Device { - public token: Buffer; - /** - * `deviceToken` can be a `Buffer` or a `String` containing a "hex" representation of the token. Throws an error if the deviceToken supplied is invalid. - */ - constructor(deviceToken: string | Buffer); -} - -export interface FeedbackOptions { - /** - * The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`) - */ - cert?: string | Buffer; - /** - * The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`) - */ - key?: string | Buffer; - /** - * An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). - */ - ca?: (string | Buffer)[]; - /** - * File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will be used instead of certificate and key above. - */ - pfx?: string | Buffer; - /** - * The passphrase for the connection key, if required - */ - passphrase?: string; - /** - * Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly) - */ - production?: boolean; - /** - * Feedback server port (Defaults to: `2196`) - */ - port?: number; - /** - * Sets the behaviour for triggering the `feedback` event. When `true` the event will be triggered once per connection with an array of timestamp and device token tuples. Otherwise a `feedback` event will be emitted once per token received. (Defaults to: true) - */ - batchFeedback?: boolean; - /** - * The maximum number of tokens to pass when emitting the event - a value of 0 will cause all tokens to be passed after connection is reset. After this number of tokens are received the `feedback` event will be emitted. (Only applies when `batchFeedback` is enabled) - */ - batchSize?: number; - /** - * How often to automatically poll the feedback service. Set to `0` to disable. (Defaults to: `3600`) - */ - interval?: number; -} -export interface FeedbackData { - time: number; - device: Device; -} -/** - * Connection to the Apple Push Notification Feedback Service and if `interval` isn't disabled automatically begins polling the service. Many of the options are the same as `apn.Connection()` - */ -export declare class Feedback { - constructor(options: FeedbackOptions); - /** - * Trigger a query of the feedback service. If `interval` is non-zero then this method will be called automatically. - */ - start(): void; - /** - * You can cancel the interval by calling `feedback.cancel()`. If you do not wish to have the service automatically queried then set `interval` to 0 and use `feedback.start()` to manually invoke it one time. - */ - cancel(): void; - /** - * Emitted when an error occurs initialising the module. Usually caused by failing to load the certificates. - */ - on(event: "error", listener: (error: Error) => void): Feedback; - /** - * Emitted when an error occurs receiving or processing the feedback and in the case of a socket error occurring. These errors are usually informational and node-apn will automatically recover. - */ - on(event: "feedbackError", listener: (error: Error) => void): Feedback; - /** - * Emitted when data has been received from the feedback service, typically once per connection. `feedbackData` is an array of objects, each containing the `time` returned by the server (epoch time) and the `device` a `Buffer` containing the device token. - */ - on(event: "feedback", listener: (feedbackData: FeedbackData[]) => void): Feedback; - on(event: string, listener: Function): Feedback; -} - -export declare enum Errors { - "noErrorsEncountered" = 0, - "processingError" = 1, - "missingDeviceToken" = 2, - "missingTopic" = 3, - "missingPayload" = 4, - "invalidTokenSize" = 5, - "invalidTopicSize" = 6, - "invalidPayloadSize" = 7, - "invalidToken" = 8, - "apnsShutdown" = 10, - "none" = 255, - "retryLimitExceeded" = 512, - "moduleInitialisationFailed" = 513, - "connectionRetryLimitExceeded" = 514, // When a connection is unable to be established. Usually because of a network / SSL error this will be emitted - "connectionTerminated" = 515 -} - -//Lowercase aliases -export { Connection as connection }; -export { Device as device }; -export { Errors as error }; -export { Feedback as feedback }; -export { Notification as notification }; diff --git a/types/argparse/argparse-tests.ts b/types/argparse/argparse-tests.ts index cec1ece95b..f5b9e76f81 100644 --- a/types/argparse/argparse-tests.ts +++ b/types/argparse/argparse-tests.ts @@ -1,7 +1,7 @@ // near copy of each of the tests from https://github.com/nodeca/argparse/tree/master/examples -import {ArgumentParser, RawDescriptionHelpFormatter} from 'argparse'; +import { ArgumentParser, RawDescriptionHelpFormatter } from 'argparse'; var args: any; var simpleExample = new ArgumentParser({ diff --git a/types/askmethat-rating/askmethat-rating-tests.ts b/types/askmethat-rating/askmethat-rating-tests.ts index 2f17ad0b62..af0ab3cb88 100644 --- a/types/askmethat-rating/askmethat-rating-tests.ts +++ b/types/askmethat-rating/askmethat-rating-tests.ts @@ -13,3 +13,6 @@ let options = { let div = document.createElement("div"); let amcRating = new AskmethatRating(div, 2 , options); + +options.readonly = true; +amcRating.defaultOptions = options; diff --git a/types/askmethat-rating/index.d.ts b/types/askmethat-rating/index.d.ts index ff31f81747..43a59957bd 100644 --- a/types/askmethat-rating/index.d.ts +++ b/types/askmethat-rating/index.d.ts @@ -75,7 +75,12 @@ export class AskmethatRating { * * @return options based on @type AskmethatRatingOptions */ - readonly defaultOptions: any; + /** + * @function set the default option for the rating + * + * @return options based on @type AskmethatRatingOptions + */ + defaultOptions: AskmethatRatingOptions; /** * constructor with div element, default rating value & default options * @@ -122,6 +127,12 @@ export class AskmethatRating { * Update readonly status if needed for the rating */ private mutationEvent(); + /** + * This is fired by mutation observer when an attribute changed in the hidden input + * Is protected to have some unit tests + * @param {MutationRecord[]} mutations list of mutations record + */ + protected mutationDisableEvent(mutations: MutationRecord[]): void; /** * @function static method to retrieve with identifier the value * @param {string} identifier: string container identifier diff --git a/types/assert-plus/index.d.ts b/types/assert-plus/index.d.ts index d79172bc49..6c1f369729 100644 --- a/types/assert-plus/index.d.ts +++ b/types/assert-plus/index.d.ts @@ -5,7 +5,7 @@ /// -import {Stream} from 'stream'; +import { Stream } from 'stream'; export function array(arr: any[], message ?: string): void; diff --git a/types/async.nexttick/async.nexttick-tests.ts b/types/async.nexttick/async.nexttick-tests.ts index 90f6ae7f15..876a8e0f88 100644 --- a/types/async.nexttick/async.nexttick-tests.ts +++ b/types/async.nexttick/async.nexttick-tests.ts @@ -1,4 +1,4 @@ -import {nextTick} from 'async.nexttick'; +import { nextTick } from 'async.nexttick'; function calledOnNextTick(a: string): number { return parseInt(a, 10); diff --git a/types/auto-sni/index.d.ts b/types/auto-sni/index.d.ts index bc252831ca..19272446a6 100644 --- a/types/auto-sni/index.d.ts +++ b/types/auto-sni/index.d.ts @@ -5,7 +5,7 @@ /// -import {Server} from "https"; +import { Server } from "https"; declare namespace createServer { interface Options { diff --git a/types/babel-core/index.d.ts b/types/babel-core/index.d.ts index a3cd7019ab..653ab1228d 100644 --- a/types/babel-core/index.d.ts +++ b/types/babel-core/index.d.ts @@ -1,7 +1,9 @@ // Type definitions for babel-core v6.7 // Project: https://github.com/babel/babel/tree/master/packages/babel-core // Definitions by: Troy Gerwien +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// /// @@ -12,7 +14,7 @@ export {t as types}; type Node = t.Node; export import template = require('babel-template'); export var version: string; -import traverse, {Visitor} from "babel-traverse"; +import traverse, {Visitor } from "babel-traverse"; export {traverse, Visitor}; diff --git a/types/babel-generator/babel-generator-tests.ts b/types/babel-generator/babel-generator-tests.ts index 92c65b7f54..1aeec38831 100644 --- a/types/babel-generator/babel-generator-tests.ts +++ b/types/babel-generator/babel-generator-tests.ts @@ -1,5 +1,5 @@ // Example from https://github.com/babel/babel/tree/master/packages/babel-generator -import {parse} from 'babylon'; +import { parse } from 'babylon'; import generate from 'babel-generator'; const code = 'class Example {}'; diff --git a/types/babel-plugin-syntax-jsx/babel-plugin-syntax-jsx-tests.ts b/types/babel-plugin-syntax-jsx/babel-plugin-syntax-jsx-tests.ts new file mode 100644 index 0000000000..4dcb7b4882 --- /dev/null +++ b/types/babel-plugin-syntax-jsx/babel-plugin-syntax-jsx-tests.ts @@ -0,0 +1,10 @@ +import jsx from "babel-plugin-syntax-jsx"; + +// Example taken from the babel plugin handbook: +// https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#-enabling-syntax-in-plugins +export default function myBabelPlugin() { + return { + visitor: {}, + inherits: jsx, + }; +} diff --git a/types/babel-plugin-syntax-jsx/index.d.ts b/types/babel-plugin-syntax-jsx/index.d.ts new file mode 100644 index 0000000000..c7b0ede972 --- /dev/null +++ b/types/babel-plugin-syntax-jsx/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for babel-plugin-syntax-jsx 6.18 +// Project: https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-jsx +// Definitions by: Marvin Hagemeister +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// NB: This export doesn't match the handbook example, where `jsx` is the default export. +// But it does match the runtime behaviour (at least at the time of this writing). For some reason, +// babel-plugin-syntax-jsx/lib/index.js has this line at the bottom: module.exports = exports["default"]; +declare function jsx(): { + manipulateOptions(opts: any, parserOpts: { plugins: string[] }): void; +}; + +export default jsx; diff --git a/types/apn/tsconfig.json b/types/babel-plugin-syntax-jsx/tsconfig.json similarity index 90% rename from types/apn/tsconfig.json rename to types/babel-plugin-syntax-jsx/tsconfig.json index a6d716d8fe..bb19fbf329 100644 --- a/types/apn/tsconfig.json +++ b/types/babel-plugin-syntax-jsx/tsconfig.json @@ -17,6 +17,6 @@ }, "files": [ "index.d.ts", - "apn-tests.ts" + "babel-plugin-syntax-jsx-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/babel-plugin-syntax-jsx/tslint.json b/types/babel-plugin-syntax-jsx/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babel-plugin-syntax-jsx/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/babel-template/index.d.ts b/types/babel-template/index.d.ts index 7d73adc466..71fd5318f7 100644 --- a/types/babel-template/index.d.ts +++ b/types/babel-template/index.d.ts @@ -1,13 +1,15 @@ // Type definitions for babel-template v6.7 // Project: https://github.com/babel/babel/tree/master/packages/babel-template // Definitions by: Troy Gerwien +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// /// -import {BabylonOptions} from 'babylon'; +import { BabylonOptions } from 'babylon'; import * as t from 'babel-types'; type Node = t.Node; diff --git a/types/babel-traverse/babel-traverse-tests.ts b/types/babel-traverse/babel-traverse-tests.ts index 5952faefd1..92f99f28ae 100644 --- a/types/babel-traverse/babel-traverse-tests.ts +++ b/types/babel-traverse/babel-traverse-tests.ts @@ -2,7 +2,7 @@ import * as babylon from "babylon"; -import traverse, {Visitor} from 'babel-traverse'; +import traverse, {Visitor } from 'babel-traverse'; import * as t from 'babel-types'; diff --git a/types/babel-traverse/index.d.ts b/types/babel-traverse/index.d.ts index 8d34144d0a..cb2dd53a84 100644 --- a/types/babel-traverse/index.d.ts +++ b/types/babel-traverse/index.d.ts @@ -1,7 +1,9 @@ // Type definitions for babel-traverse v6.7 // Project: https://github.com/babel/babel/tree/master/packages/babel-traverse // Definitions by: Troy Gerwien +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/babel-types/babel-types-tests.ts b/types/babel-types/babel-types-tests.ts index 394603ab31..0ef79f39f4 100644 --- a/types/babel-types/babel-types-tests.ts +++ b/types/babel-types/babel-types-tests.ts @@ -1,7 +1,3 @@ - -/// - - // Examples from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-types import traverse from "babel-traverse"; import * as t from "babel-types"; @@ -25,13 +21,13 @@ if (t.isBinaryExpression(ast)) { ast.right; ast.operator; } + t.assertBinaryExpression(ast); t.assertBinaryExpression(ast, { operator: "*" }); -var exp: t.Expression = t.nullLiteral(); +const exp: t.Expression = t.nullLiteral(); // React examples: - // https://github.com/babel/babel/blob/4e50b2d9d9c376cee7a2cbf56553fe5b982ea53c/packages/babel-plugin-transform-react-inline-elements/src/index.js#L61 traverse(ast, { JSXElement(path, file) { diff --git a/types/babel-types/index.d.ts b/types/babel-types/index.d.ts index c3f77b559f..1879c81e85 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for babel-types v6.25 +// Type definitions for babel-types 6.25 // Project: https://github.com/babel/babel/tree/master/packages/babel-types // Definitions by: Troy Gerwien // Sam Baxter // Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export interface Comment { value: string; @@ -34,9 +35,9 @@ export interface SourceLocation { export interface Node { type: string; - leadingComments?: Array; - innerComments?: Array; - trailingComments?: Array; + leadingComments?: Comment[]; + innerComments?: Comment[]; + trailingComments?: Comment[]; start: number; end: number; loc: SourceLocation; @@ -150,7 +151,7 @@ export interface ForStatement extends Node { export interface FunctionDeclaration extends Node { type: "FunctionDeclaration"; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement; generator: boolean; async: boolean; @@ -161,7 +162,7 @@ export interface FunctionDeclaration extends Node { export interface FunctionExpression extends Node { type: "FunctionExpression"; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement; generator: boolean; async: boolean; @@ -254,7 +255,7 @@ export interface ObjectMethod extends Node { value: Expression; decorators?: Decorator[]; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement; generator: boolean; async: boolean; @@ -361,14 +362,14 @@ export interface AssignmentPattern extends Node { export interface ArrayPattern extends Node { type: "ArrayPattern"; - elements: Array; + elements: Expression[]; typeAnnotation?: TypeAnnotation; } export interface ArrowFunctionExpression extends Node { type: "ArrowFunctionExpression"; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement | Expression; generator: boolean; async: boolean; @@ -474,7 +475,7 @@ export interface ClassMethod extends Node { static: boolean; decorators?: Decorator[]; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement; generator: boolean; async: boolean; @@ -872,12 +873,33 @@ export interface SpreadProperty extends Node { argument: Expression; } -export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | ObjectExpression | SequenceExpression | ThisExpression | UnaryExpression | UpdateExpression | ArrowFunctionExpression | ClassExpression | MetaProperty | Super | TaggedTemplateExpression | TemplateLiteral | YieldExpression | TypeCastExpression | JSXElement | JSXEmptyExpression | JSXIdentifier | JSXMemberExpression | ParenthesizedExpression | AwaitExpression | BindExpression | DoExpression; +export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression + | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral + | NullLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | ObjectExpression + | SequenceExpression | ThisExpression | UnaryExpression | UpdateExpression | ArrowFunctionExpression + | ClassExpression | MetaProperty | Super | TaggedTemplateExpression | TemplateLiteral | YieldExpression + | TypeCastExpression | JSXElement | JSXEmptyExpression | JSXIdentifier | JSXMemberExpression + | ParenthesizedExpression | AwaitExpression | BindExpression | DoExpression; + export type Binary = BinaryExpression | LogicalExpression; -export type Scopable = BlockStatement | CatchClause | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ClassDeclaration | ClassExpression | ForOfStatement | ClassMethod; -export type BlockParent = BlockStatement | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ForOfStatement | ClassMethod; + +export type Scopable = BlockStatement | CatchClause | DoWhileStatement | ForInStatement | ForStatement + | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement + | ArrowFunctionExpression | ClassDeclaration | ClassExpression | ForOfStatement | ClassMethod; + +export type BlockParent = BlockStatement | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration + | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression + | ForOfStatement | ClassMethod; + export type Block = BlockStatement | Program; -export type Statement = BlockStatement | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement | EmptyStatement | ExpressionStatement | ForInStatement | ForStatement | FunctionDeclaration | IfStatement | LabeledStatement | ReturnStatement | SwitchStatement | ThrowStatement | TryStatement | VariableDeclaration | WhileStatement | WithStatement | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ForOfStatement | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; + +export type Statement = BlockStatement | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement + | EmptyStatement | ExpressionStatement | ForInStatement | ForStatement | FunctionDeclaration | IfStatement + | LabeledStatement | ReturnStatement | SwitchStatement | ThrowStatement | TryStatement | VariableDeclaration + | WhileStatement | WithStatement | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration + | ExportNamedDeclaration | ForOfStatement | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface + | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; + export type Terminatorless = BreakStatement | ContinueStatement | ReturnStatement | ThrowStatement | YieldExpression | AwaitExpression; export type CompletionStatement = BreakStatement | ContinueStatement | ReturnStatement | ThrowStatement; export type Conditional = ConditionalExpression | IfStatement; @@ -889,7 +911,11 @@ export type ForXStatement = ForInStatement | ForOfStatement; export type Function = FunctionDeclaration | FunctionExpression | ObjectMethod | ArrowFunctionExpression | ClassMethod; export type FunctionParent = FunctionDeclaration | FunctionExpression | Program | ObjectMethod | ArrowFunctionExpression | ClassMethod; export type Pureish = FunctionDeclaration | FunctionExpression | StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | ArrowFunctionExpression | ClassDeclaration | ClassExpression; -export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; + +export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration | ExportAllDeclaration + | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration | DeclareClass | DeclareFunction + | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; + export type LVal = Identifier | MemberExpression | RestElement | AssignmentPattern | ArrayPattern | ObjectPattern; export type Literal = StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | RegExpLiteral | TemplateLiteral; export type Immutable = StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | JSXAttribute | JSXClosingElement | JSXElement | JSXExpressionContainer | JSXOpeningElement; @@ -903,15 +929,36 @@ export type Class = ClassDeclaration | ClassExpression; export type ModuleDeclaration = ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration; export type ExportDeclaration = ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration; export type ModuleSpecifier = ExportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ImportSpecifier | ExportDefaultSpecifier | ExportNamespaceSpecifier; -export type Flow = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation | ClassImplements | ClassProperty | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | ExistentialTypeParam | FunctionTypeAnnotation | FunctionTypeParam | GenericTypeAnnotation | InterfaceExtends | InterfaceDeclaration | IntersectionTypeAnnotation | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation | TypeofTypeAnnotation | TypeAlias | TypeAnnotation | TypeCastExpression | TypeParameterDeclaration | TypeParameterInstantiation | ObjectTypeAnnotation | ObjectTypeCallProperty | ObjectTypeIndexer | ObjectTypeProperty | QualifiedTypeIdentifier | UnionTypeAnnotation | VoidTypeAnnotation; -export type FlowTypeAnnotation = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation | FunctionTypeAnnotation | GenericTypeAnnotation | IntersectionTypeAnnotation | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation | TypeofTypeAnnotation | TypeAnnotation | ObjectTypeAnnotation | UnionTypeAnnotation | VoidTypeAnnotation; + +export type Flow = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation + | ClassImplements | ClassProperty | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule + | DeclareTypeAlias | DeclareVariable | ExistentialTypeParam | FunctionTypeAnnotation | FunctionTypeParam + | GenericTypeAnnotation | InterfaceExtends | InterfaceDeclaration | IntersectionTypeAnnotation + | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation + | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation + | TypeofTypeAnnotation | TypeAlias | TypeAnnotation | TypeCastExpression | TypeParameterDeclaration + | TypeParameterInstantiation | ObjectTypeAnnotation | ObjectTypeCallProperty | ObjectTypeIndexer + | ObjectTypeProperty | QualifiedTypeIdentifier | UnionTypeAnnotation | VoidTypeAnnotation; + +export type FlowTypeAnnotation = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation + | BooleanLiteralTypeAnnotation | FunctionTypeAnnotation | GenericTypeAnnotation | IntersectionTypeAnnotation + | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation + | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation + | TypeofTypeAnnotation | TypeAnnotation | ObjectTypeAnnotation | UnionTypeAnnotation | VoidTypeAnnotation; + export type FlowBaseAnnotation = AnyTypeAnnotation | BooleanTypeAnnotation | MixedTypeAnnotation | NumberTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | VoidTypeAnnotation; export type FlowDeclaration = DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; -export type JSX = JSXAttribute | JSXClosingElement | JSXElement | JSXEmptyExpression | JSXExpressionContainer | JSXIdentifier | JSXMemberExpression | JSXNamespacedName | JSXOpeningElement | JSXSpreadAttribute | JSXText; + +export type JSX = JSXAttribute | JSXClosingElement | JSXElement | JSXEmptyExpression | JSXExpressionContainer + | JSXIdentifier | JSXMemberExpression | JSXNamespacedName | JSXOpeningElement | JSXSpreadAttribute | JSXText; export function arrayExpression(elements?: Array): ArrayExpression; export function assignmentExpression(operator?: string, left?: LVal, right?: Expression): AssignmentExpression; -export function binaryExpression(operator?: "+" | "-" | "/" | "%" | "*" | "**" | "&" | "|" | ">>" | ">>>" | "<<" | "^" | "==" | "===" | "!=" | "!==" | "in" | "instanceof" | ">" | "<" | ">=" | "<=", left?: Expression, right?: Expression): BinaryExpression; +export function binaryExpression( + operator?: "+" | "-" | "/" | "%" | "*" | "**" | "&" | "|" | ">>" | ">>>" | "<<" | "^" | "==" | "===" | "!=" | "!==" | "in" | "instanceof" | ">" | "<" | ">=" | "<=", + left?: Expression, + right?: Expression +): BinaryExpression; export function directive(value?: DirectiveLiteral): Directive; export function directiveLiteral(value?: string): DirectiveLiteral; export function blockStatement(body?: Statement[], directives?: Directive[]): BlockStatement; @@ -927,8 +974,8 @@ export function expressionStatement(expression?: Expression): ExpressionStatemen export function file(program?: Program, comments?: Comment[], tokens?: any[]): File; export function forInStatement(left?: VariableDeclaration | LVal, right?: Expression, body?: Statement): ForInStatement; export function forStatement(init?: VariableDeclaration | Expression, test?: Expression, update?: Expression, body?: Statement): ForStatement; -export function functionDeclaration(id?: Identifier, params?: Array, body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration; -export function functionExpression(id?: Identifier, params?: Array, body?: BlockStatement, generator?: boolean, async?: boolean): FunctionExpression; +export function functionDeclaration(id?: Identifier, params?: LVal[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration; +export function functionExpression(id?: Identifier, params?: LVal[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionExpression; export function identifier(name?: string): Identifier; export function ifStatement(test?: Expression, consequent?: Statement, alternate?: Statement): IfStatement; export function labeledStatement(label?: Identifier, body?: Statement): LabeledStatement; @@ -942,7 +989,7 @@ export function memberExpression(object?: Expression | Super, property?: Express export function newExpression(callee?: Expression | Super, _arguments?: Array): NewExpression; export function program(body?: Array, directives?: Directive[]): Program; export function objectExpression(properties?: Array): ObjectExpression; -export function objectMethod(kind?: "get" | "set" | "method", key?: Expression, params?: Array, body?: BlockStatement, computed?: boolean): ObjectMethod; +export function objectMethod(kind?: "get" | "set" | "method", key?: Expression, params?: LVal[], body?: BlockStatement, computed?: boolean): ObjectMethod; export function objectProperty(key?: Expression, value?: Expression, computed?: boolean, shorthand?: boolean, decorators?: Decorator[]): ObjectProperty; export function restElement(argument?: LVal, typeAnnotation?: TypeAnnotation): RestElement; export function returnStatement(argument?: Expression): ReturnStatement; @@ -959,8 +1006,8 @@ export function variableDeclarator(id?: LVal, init?: Expression): VariableDeclar export function whileStatement(test?: Expression, body?: BlockStatement | Statement): WhileStatement; export function withStatement(object?: Expression, body?: BlockStatement | Statement): WithStatement; export function assignmentPattern(left?: Identifier, right?: Expression): AssignmentPattern; -export function arrayPattern(elements?: Array, typeAnnotation?: TypeAnnotation): ArrayPattern; -export function arrowFunctionExpression(params?: Array, body?: BlockStatement | Expression, async?: boolean): ArrowFunctionExpression; +export function arrayPattern(elements?: Expression[], typeAnnotation?: TypeAnnotation): ArrayPattern; +export function arrowFunctionExpression(params?: LVal[], body?: BlockStatement | Expression, async?: boolean): ArrowFunctionExpression; export function classBody(body?: Array): ClassBody; export function classDeclaration(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassDeclaration; export function classExpression(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassExpression; @@ -974,11 +1021,11 @@ export function importDefaultSpecifier(local?: Identifier): ImportDefaultSpecifi export function importNamespaceSpecifier(local?: Identifier): ImportNamespaceSpecifier; export function importSpecifier(local?: Identifier, imported?: Identifier): ImportSpecifier; export function metaProperty(meta?: string, property?: string): MetaProperty; -export function classMethod(kind?: "constructor" | "method" | "get" | "set", key?: Expression, params?: Array, body?: BlockStatement, computed?: boolean, _static?: boolean): ClassMethod; +export function classMethod(kind?: "constructor" | "method" | "get" | "set", key?: Expression, params?: LVal[], body?: BlockStatement, computed?: boolean, _static?: boolean): ClassMethod; export function objectPattern(properties?: Array, typeAnnotation?: TypeAnnotation): ObjectPattern; export function spreadElement(argument?: Expression): SpreadElement; export function taggedTemplateExpression(tag?: Expression, quasi?: TemplateLiteral): TaggedTemplateExpression; -export function templateElement(value?: {cooked?: string; raw?: string;}, tail?: boolean): TemplateElement; +export function templateElement(value?: { cooked?: string; raw?: string; }, tail?: boolean): TemplateElement; export function templateLiteral(quasis?: TemplateElement[], expressions?: Expression[]): TemplateLiteral; export function yieldExpression(argument?: Expression, delegate?: boolean): YieldExpression; export function anyTypeAnnotation(): AnyTypeAnnotation; @@ -1044,367 +1091,367 @@ export function exportNamespaceSpecifier(exported?: Identifier): ExportNamespace export function restProperty(argument?: LVal): RestProperty; export function spreadProperty(argument?: Expression): SpreadProperty; -export function isArrayExpression(node: Object, opts?: Object): node is ArrayExpression; -export function isAssignmentExpression(node: Object, opts?: Object): node is AssignmentExpression; -export function isBinaryExpression(node: Object, opts?: Object): node is BinaryExpression; -export function isDirective(node: Object, opts?: Object): node is Directive; -export function isDirectiveLiteral(node: Object, opts?: Object): node is DirectiveLiteral; -export function isBlockStatement(node: Object, opts?: Object): node is BlockStatement; -export function isBreakStatement(node: Object, opts?: Object): node is BreakStatement; -export function isCallExpression(node: Object, opts?: Object): node is CallExpression; -export function isCatchClause(node: Object, opts?: Object): node is CatchClause; -export function isConditionalExpression(node: Object, opts?: Object): node is ConditionalExpression; -export function isContinueStatement(node: Object, opts?: Object): node is ContinueStatement; -export function isDebuggerStatement(node: Object, opts?: Object): node is DebuggerStatement; -export function isDoWhileStatement(node: Object, opts?: Object): node is DoWhileStatement; -export function isEmptyStatement(node: Object, opts?: Object): node is EmptyStatement; -export function isExpressionStatement(node: Object, opts?: Object): node is ExpressionStatement; -export function isFile(node: Object, opts?: Object): node is File; -export function isForInStatement(node: Object, opts?: Object): node is ForInStatement; -export function isForStatement(node: Object, opts?: Object): node is ForStatement; -export function isFunctionDeclaration(node: Object, opts?: Object): node is FunctionDeclaration; -export function isFunctionExpression(node: Object, opts?: Object): node is FunctionExpression; -export function isIdentifier(node: Object, opts?: Object): node is Identifier; -export function isIfStatement(node: Object, opts?: Object): node is IfStatement; -export function isLabeledStatement(node: Object, opts?: Object): node is LabeledStatement; -export function isStringLiteral(node: Object, opts?: Object): node is StringLiteral; -export function isNumericLiteral(node: Object, opts?: Object): node is NumericLiteral; -export function isNullLiteral(node: Object, opts?: Object): node is NullLiteral; -export function isBooleanLiteral(node: Object, opts?: Object): node is BooleanLiteral; -export function isRegExpLiteral(node: Object, opts?: Object): node is RegExpLiteral; -export function isLogicalExpression(node: Object, opts?: Object): node is LogicalExpression; -export function isMemberExpression(node: Object, opts?: Object): node is MemberExpression; -export function isNewExpression(node: Object, opts?: Object): node is NewExpression; -export function isProgram(node: Object, opts?: Object): node is Program; -export function isObjectExpression(node: Object, opts?: Object): node is ObjectExpression; -export function isObjectMethod(node: Object, opts?: Object): node is ObjectMethod; -export function isObjectProperty(node: Object, opts?: Object): node is ObjectProperty; -export function isRestElement(node: Object, opts?: Object): node is RestElement; -export function isReturnStatement(node: Object, opts?: Object): node is ReturnStatement; -export function isSequenceExpression(node: Object, opts?: Object): node is SequenceExpression; -export function isSwitchCase(node: Object, opts?: Object): node is SwitchCase; -export function isSwitchStatement(node: Object, opts?: Object): node is SwitchStatement; -export function isThisExpression(node: Object, opts?: Object): node is ThisExpression; -export function isThrowStatement(node: Object, opts?: Object): node is ThrowStatement; -export function isTryStatement(node: Object, opts?: Object): node is TryStatement; -export function isUnaryExpression(node: Object, opts?: Object): node is UnaryExpression; -export function isUpdateExpression(node: Object, opts?: Object): node is UpdateExpression; -export function isVariableDeclaration(node: Object, opts?: Object): node is VariableDeclaration; -export function isVariableDeclarator(node: Object, opts?: Object): node is VariableDeclarator; -export function isWhileStatement(node: Object, opts?: Object): node is WhileStatement; -export function isWithStatement(node: Object, opts?: Object): node is WithStatement; -export function isAssignmentPattern(node: Object, opts?: Object): node is AssignmentPattern; -export function isArrayPattern(node: Object, opts?: Object): node is ArrayPattern; -export function isArrowFunctionExpression(node: Object, opts?: Object): node is ArrowFunctionExpression; -export function isClassBody(node: Object, opts?: Object): node is ClassBody; -export function isClassDeclaration(node: Object, opts?: Object): node is ClassDeclaration; -export function isClassExpression(node: Object, opts?: Object): node is ClassExpression; -export function isExportAllDeclaration(node: Object, opts?: Object): node is ExportAllDeclaration; -export function isExportDefaultDeclaration(node: Object, opts?: Object): node is ExportDefaultDeclaration; -export function isExportNamedDeclaration(node: Object, opts?: Object): node is ExportNamedDeclaration; -export function isExportSpecifier(node: Object, opts?: Object): node is ExportSpecifier; -export function isForOfStatement(node: Object, opts?: Object): node is ForOfStatement; -export function isImportDeclaration(node: Object, opts?: Object): node is ImportDeclaration; -export function isImportDefaultSpecifier(node: Object, opts?: Object): node is ImportDefaultSpecifier; -export function isImportNamespaceSpecifier(node: Object, opts?: Object): node is ImportNamespaceSpecifier; -export function isImportSpecifier(node: Object, opts?: Object): node is ImportSpecifier; -export function isMetaProperty(node: Object, opts?: Object): node is MetaProperty; -export function isClassMethod(node: Object, opts?: Object): node is ClassMethod; -export function isObjectPattern(node: Object, opts?: Object): node is ObjectPattern; -export function isSpreadElement(node: Object, opts?: Object): node is SpreadElement; -export function isSuper(node: Object, opts?: Object): node is Super; -export function isTaggedTemplateExpression(node: Object, opts?: Object): node is TaggedTemplateExpression; -export function isTemplateElement(node: Object, opts?: Object): node is TemplateElement; -export function isTemplateLiteral(node: Object, opts?: Object): node is TemplateLiteral; -export function isYieldExpression(node: Object, opts?: Object): node is YieldExpression; -export function isAnyTypeAnnotation(node: Object, opts?: Object): node is AnyTypeAnnotation; -export function isArrayTypeAnnotation(node: Object, opts?: Object): node is ArrayTypeAnnotation; -export function isBooleanTypeAnnotation(node: Object, opts?: Object): node is BooleanTypeAnnotation; -export function isBooleanLiteralTypeAnnotation(node: Object, opts?: Object): node is BooleanLiteralTypeAnnotation; -export function isNullLiteralTypeAnnotation(node: Object, opts?: Object): node is NullLiteralTypeAnnotation; -export function isClassImplements(node: Object, opts?: Object): node is ClassImplements; -export function isClassProperty(node: Object, opts?: Object): node is ClassProperty; -export function isDeclareClass(node: Object, opts?: Object): node is DeclareClass; -export function isDeclareFunction(node: Object, opts?: Object): node is DeclareFunction; -export function isDeclareInterface(node: Object, opts?: Object): node is DeclareInterface; -export function isDeclareModule(node: Object, opts?: Object): node is DeclareModule; -export function isDeclareTypeAlias(node: Object, opts?: Object): node is DeclareTypeAlias; -export function isDeclareVariable(node: Object, opts?: Object): node is DeclareVariable; -export function isExistentialTypeParam(node: Object, opts?: Object): node is ExistentialTypeParam; -export function isFunctionTypeAnnotation(node: Object, opts?: Object): node is FunctionTypeAnnotation; -export function isFunctionTypeParam(node: Object, opts?: Object): node is FunctionTypeParam; -export function isGenericTypeAnnotation(node: Object, opts?: Object): node is GenericTypeAnnotation; -export function isInterfaceExtends(node: Object, opts?: Object): node is InterfaceExtends; -export function isInterfaceDeclaration(node: Object, opts?: Object): node is InterfaceDeclaration; -export function isIntersectionTypeAnnotation(node: Object, opts?: Object): node is IntersectionTypeAnnotation; -export function isMixedTypeAnnotation(node: Object, opts?: Object): node is MixedTypeAnnotation; -export function isNullableTypeAnnotation(node: Object, opts?: Object): node is NullableTypeAnnotation; -export function isNumericLiteralTypeAnnotation(node: Object, opts?: Object): node is NumericLiteralTypeAnnotation; -export function isNumberTypeAnnotation(node: Object, opts?: Object): node is NumberTypeAnnotation; -export function isStringLiteralTypeAnnotation(node: Object, opts?: Object): node is StringLiteralTypeAnnotation; -export function isStringTypeAnnotation(node: Object, opts?: Object): node is StringTypeAnnotation; -export function isThisTypeAnnotation(node: Object, opts?: Object): node is ThisTypeAnnotation; -export function isTupleTypeAnnotation(node: Object, opts?: Object): node is TupleTypeAnnotation; -export function isTypeofTypeAnnotation(node: Object, opts?: Object): node is TypeofTypeAnnotation; -export function isTypeAlias(node: Object, opts?: Object): node is TypeAlias; -export function isTypeAnnotation(node: Object, opts?: Object): node is TypeAnnotation; -export function isTypeCastExpression(node: Object, opts?: Object): node is TypeCastExpression; -export function isTypeParameterDeclaration(node: Object, opts?: Object): node is TypeParameterDeclaration; -export function isTypeParameterInstantiation(node: Object, opts?: Object): node is TypeParameterInstantiation; -export function isObjectTypeAnnotation(node: Object, opts?: Object): node is ObjectTypeAnnotation; -export function isObjectTypeCallProperty(node: Object, opts?: Object): node is ObjectTypeCallProperty; -export function isObjectTypeIndexer(node: Object, opts?: Object): node is ObjectTypeIndexer; -export function isObjectTypeProperty(node: Object, opts?: Object): node is ObjectTypeProperty; -export function isQualifiedTypeIdentifier(node: Object, opts?: Object): node is QualifiedTypeIdentifier; -export function isUnionTypeAnnotation(node: Object, opts?: Object): node is UnionTypeAnnotation; -export function isVoidTypeAnnotation(node: Object, opts?: Object): node is VoidTypeAnnotation; -export function isJSXAttribute(node: Object, opts?: Object): node is JSXAttribute; -export function isJSXClosingElement(node: Object, opts?: Object): node is JSXClosingElement; -export function isJSXElement(node: Object, opts?: Object): node is JSXElement; -export function isJSXEmptyExpression(node: Object, opts?: Object): node is JSXEmptyExpression; -export function isJSXExpressionContainer(node: Object, opts?: Object): node is JSXExpressionContainer; -export function isJSXIdentifier(node: Object, opts?: Object): node is JSXIdentifier; -export function isJSXMemberExpression(node: Object, opts?: Object): node is JSXMemberExpression; -export function isJSXNamespacedName(node: Object, opts?: Object): node is JSXNamespacedName; -export function isJSXOpeningElement(node: Object, opts?: Object): node is JSXOpeningElement; -export function isJSXSpreadAttribute(node: Object, opts?: Object): node is JSXSpreadAttribute; -export function isJSXText(node: Object, opts?: Object): node is JSXText; -export function isNoop(node: Object, opts?: Object): node is Noop; -export function isParenthesizedExpression(node: Object, opts?: Object): node is ParenthesizedExpression; -export function isAwaitExpression(node: Object, opts?: Object): node is AwaitExpression; -export function isBindExpression(node: Object, opts?: Object): node is BindExpression; -export function isDecorator(node: Object, opts?: Object): node is Decorator; -export function isDoExpression(node: Object, opts?: Object): node is DoExpression; -export function isExportDefaultSpecifier(node: Object, opts?: Object): node is ExportDefaultSpecifier; -export function isExportNamespaceSpecifier(node: Object, opts?: Object): node is ExportNamespaceSpecifier; -export function isRestProperty(node: Object, opts?: Object): node is RestProperty; -export function isSpreadProperty(node: Object, opts?: Object): node is SpreadProperty; -export function isExpression(node: Object, opts?: Object): node is Expression; -export function isBinary(node: Object, opts?: Object): node is Binary; -export function isScopable(node: Object, opts?: Object): node is Scopable; -export function isBlockParent(node: Object, opts?: Object): node is BlockParent; -export function isBlock(node: Object, opts?: Object): node is Block; -export function isStatement(node: Object, opts?: Object): node is Statement; -export function isTerminatorless(node: Object, opts?: Object): node is Terminatorless; -export function isCompletionStatement(node: Object, opts?: Object): node is CompletionStatement; -export function isConditional(node: Object, opts?: Object): node is Conditional; -export function isLoop(node: Object, opts?: Object): node is Loop; -export function isWhile(node: Object, opts?: Object): node is While; -export function isExpressionWrapper(node: Object, opts?: Object): node is ExpressionWrapper; -export function isFor(node: Object, opts?: Object): node is For; -export function isForXStatement(node: Object, opts?: Object): node is ForXStatement; -export function isFunction(node: Object, opts?: Object): node is Function; -export function isFunctionParent(node: Object, opts?: Object): node is FunctionParent; -export function isPureish(node: Object, opts?: Object): node is Pureish; -export function isDeclaration(node: Object, opts?: Object): node is Declaration; -export function isLVal(node: Object, opts?: Object): node is LVal; -export function isLiteral(node: Object, opts?: Object): node is Literal; -export function isImmutable(node: Object, opts?: Object): node is Immutable; -export function isUserWhitespacable(node: Object, opts?: Object): node is UserWhitespacable; -export function isMethod(node: Object, opts?: Object): node is Method; -export function isObjectMember(node: Object, opts?: Object): node is ObjectMember; -export function isProperty(node: Object, opts?: Object): node is Property; -export function isUnaryLike(node: Object, opts?: Object): node is UnaryLike; -export function isPattern(node: Object, opts?: Object): node is Pattern; -export function isClass(node: Object, opts?: Object): node is Class; -export function isModuleDeclaration(node: Object, opts?: Object): node is ModuleDeclaration; -export function isExportDeclaration(node: Object, opts?: Object): node is ExportDeclaration; -export function isModuleSpecifier(node: Object, opts?: Object): node is ModuleSpecifier; -export function isFlow(node: Object, opts?: Object): node is Flow; -export function isFlowBaseAnnotation(node: Object, opts?: Object): node is FlowBaseAnnotation; -export function isFlowDeclaration(node: Object, opts?: Object): node is FlowDeclaration; -export function isJSX(node: Object, opts?: Object): node is JSX; -export function isNumberLiteral(node: Object, opts?: Object): node is NumericLiteral; -export function isRegexLiteral(node: Object, opts?: Object): node is RegExpLiteral; +export function isArrayExpression(node: object, opts?: object): node is ArrayExpression; +export function isAssignmentExpression(node: object, opts?: object): node is AssignmentExpression; +export function isBinaryExpression(node: object, opts?: object): node is BinaryExpression; +export function isDirective(node: object, opts?: object): node is Directive; +export function isDirectiveLiteral(node: object, opts?: object): node is DirectiveLiteral; +export function isBlockStatement(node: object, opts?: object): node is BlockStatement; +export function isBreakStatement(node: object, opts?: object): node is BreakStatement; +export function isCallExpression(node: object, opts?: object): node is CallExpression; +export function isCatchClause(node: object, opts?: object): node is CatchClause; +export function isConditionalExpression(node: object, opts?: object): node is ConditionalExpression; +export function isContinueStatement(node: object, opts?: object): node is ContinueStatement; +export function isDebuggerStatement(node: object, opts?: object): node is DebuggerStatement; +export function isDoWhileStatement(node: object, opts?: object): node is DoWhileStatement; +export function isEmptyStatement(node: object, opts?: object): node is EmptyStatement; +export function isExpressionStatement(node: object, opts?: object): node is ExpressionStatement; +export function isFile(node: object, opts?: object): node is File; +export function isForInStatement(node: object, opts?: object): node is ForInStatement; +export function isForStatement(node: object, opts?: object): node is ForStatement; +export function isFunctionDeclaration(node: object, opts?: object): node is FunctionDeclaration; +export function isFunctionExpression(node: object, opts?: object): node is FunctionExpression; +export function isIdentifier(node: object, opts?: object): node is Identifier; +export function isIfStatement(node: object, opts?: object): node is IfStatement; +export function isLabeledStatement(node: object, opts?: object): node is LabeledStatement; +export function isStringLiteral(node: object, opts?: object): node is StringLiteral; +export function isNumericLiteral(node: object, opts?: object): node is NumericLiteral; +export function isNullLiteral(node: object, opts?: object): node is NullLiteral; +export function isBooleanLiteral(node: object, opts?: object): node is BooleanLiteral; +export function isRegExpLiteral(node: object, opts?: object): node is RegExpLiteral; +export function isLogicalExpression(node: object, opts?: object): node is LogicalExpression; +export function isMemberExpression(node: object, opts?: object): node is MemberExpression; +export function isNewExpression(node: object, opts?: object): node is NewExpression; +export function isProgram(node: object, opts?: object): node is Program; +export function isObjectExpression(node: object, opts?: object): node is ObjectExpression; +export function isObjectMethod(node: object, opts?: object): node is ObjectMethod; +export function isObjectProperty(node: object, opts?: object): node is ObjectProperty; +export function isRestElement(node: object, opts?: object): node is RestElement; +export function isReturnStatement(node: object, opts?: object): node is ReturnStatement; +export function isSequenceExpression(node: object, opts?: object): node is SequenceExpression; +export function isSwitchCase(node: object, opts?: object): node is SwitchCase; +export function isSwitchStatement(node: object, opts?: object): node is SwitchStatement; +export function isThisExpression(node: object, opts?: object): node is ThisExpression; +export function isThrowStatement(node: object, opts?: object): node is ThrowStatement; +export function isTryStatement(node: object, opts?: object): node is TryStatement; +export function isUnaryExpression(node: object, opts?: object): node is UnaryExpression; +export function isUpdateExpression(node: object, opts?: object): node is UpdateExpression; +export function isVariableDeclaration(node: object, opts?: object): node is VariableDeclaration; +export function isVariableDeclarator(node: object, opts?: object): node is VariableDeclarator; +export function isWhileStatement(node: object, opts?: object): node is WhileStatement; +export function isWithStatement(node: object, opts?: object): node is WithStatement; +export function isAssignmentPattern(node: object, opts?: object): node is AssignmentPattern; +export function isArrayPattern(node: object, opts?: object): node is ArrayPattern; +export function isArrowFunctionExpression(node: object, opts?: object): node is ArrowFunctionExpression; +export function isClassBody(node: object, opts?: object): node is ClassBody; +export function isClassDeclaration(node: object, opts?: object): node is ClassDeclaration; +export function isClassExpression(node: object, opts?: object): node is ClassExpression; +export function isExportAllDeclaration(node: object, opts?: object): node is ExportAllDeclaration; +export function isExportDefaultDeclaration(node: object, opts?: object): node is ExportDefaultDeclaration; +export function isExportNamedDeclaration(node: object, opts?: object): node is ExportNamedDeclaration; +export function isExportSpecifier(node: object, opts?: object): node is ExportSpecifier; +export function isForOfStatement(node: object, opts?: object): node is ForOfStatement; +export function isImportDeclaration(node: object, opts?: object): node is ImportDeclaration; +export function isImportDefaultSpecifier(node: object, opts?: object): node is ImportDefaultSpecifier; +export function isImportNamespaceSpecifier(node: object, opts?: object): node is ImportNamespaceSpecifier; +export function isImportSpecifier(node: object, opts?: object): node is ImportSpecifier; +export function isMetaProperty(node: object, opts?: object): node is MetaProperty; +export function isClassMethod(node: object, opts?: object): node is ClassMethod; +export function isObjectPattern(node: object, opts?: object): node is ObjectPattern; +export function isSpreadElement(node: object, opts?: object): node is SpreadElement; +export function isSuper(node: object, opts?: object): node is Super; +export function isTaggedTemplateExpression(node: object, opts?: object): node is TaggedTemplateExpression; +export function isTemplateElement(node: object, opts?: object): node is TemplateElement; +export function isTemplateLiteral(node: object, opts?: object): node is TemplateLiteral; +export function isYieldExpression(node: object, opts?: object): node is YieldExpression; +export function isAnyTypeAnnotation(node: object, opts?: object): node is AnyTypeAnnotation; +export function isArrayTypeAnnotation(node: object, opts?: object): node is ArrayTypeAnnotation; +export function isBooleanTypeAnnotation(node: object, opts?: object): node is BooleanTypeAnnotation; +export function isBooleanLiteralTypeAnnotation(node: object, opts?: object): node is BooleanLiteralTypeAnnotation; +export function isNullLiteralTypeAnnotation(node: object, opts?: object): node is NullLiteralTypeAnnotation; +export function isClassImplements(node: object, opts?: object): node is ClassImplements; +export function isClassProperty(node: object, opts?: object): node is ClassProperty; +export function isDeclareClass(node: object, opts?: object): node is DeclareClass; +export function isDeclareFunction(node: object, opts?: object): node is DeclareFunction; +export function isDeclareInterface(node: object, opts?: object): node is DeclareInterface; +export function isDeclareModule(node: object, opts?: object): node is DeclareModule; +export function isDeclareTypeAlias(node: object, opts?: object): node is DeclareTypeAlias; +export function isDeclareVariable(node: object, opts?: object): node is DeclareVariable; +export function isExistentialTypeParam(node: object, opts?: object): node is ExistentialTypeParam; +export function isFunctionTypeAnnotation(node: object, opts?: object): node is FunctionTypeAnnotation; +export function isFunctionTypeParam(node: object, opts?: object): node is FunctionTypeParam; +export function isGenericTypeAnnotation(node: object, opts?: object): node is GenericTypeAnnotation; +export function isInterfaceExtends(node: object, opts?: object): node is InterfaceExtends; +export function isInterfaceDeclaration(node: object, opts?: object): node is InterfaceDeclaration; +export function isIntersectionTypeAnnotation(node: object, opts?: object): node is IntersectionTypeAnnotation; +export function isMixedTypeAnnotation(node: object, opts?: object): node is MixedTypeAnnotation; +export function isNullableTypeAnnotation(node: object, opts?: object): node is NullableTypeAnnotation; +export function isNumericLiteralTypeAnnotation(node: object, opts?: object): node is NumericLiteralTypeAnnotation; +export function isNumberTypeAnnotation(node: object, opts?: object): node is NumberTypeAnnotation; +export function isStringLiteralTypeAnnotation(node: object, opts?: object): node is StringLiteralTypeAnnotation; +export function isStringTypeAnnotation(node: object, opts?: object): node is StringTypeAnnotation; +export function isThisTypeAnnotation(node: object, opts?: object): node is ThisTypeAnnotation; +export function isTupleTypeAnnotation(node: object, opts?: object): node is TupleTypeAnnotation; +export function isTypeofTypeAnnotation(node: object, opts?: object): node is TypeofTypeAnnotation; +export function isTypeAlias(node: object, opts?: object): node is TypeAlias; +export function isTypeAnnotation(node: object, opts?: object): node is TypeAnnotation; +export function isTypeCastExpression(node: object, opts?: object): node is TypeCastExpression; +export function isTypeParameterDeclaration(node: object, opts?: object): node is TypeParameterDeclaration; +export function isTypeParameterInstantiation(node: object, opts?: object): node is TypeParameterInstantiation; +export function isObjectTypeAnnotation(node: object, opts?: object): node is ObjectTypeAnnotation; +export function isObjectTypeCallProperty(node: object, opts?: object): node is ObjectTypeCallProperty; +export function isObjectTypeIndexer(node: object, opts?: object): node is ObjectTypeIndexer; +export function isObjectTypeProperty(node: object, opts?: object): node is ObjectTypeProperty; +export function isQualifiedTypeIdentifier(node: object, opts?: object): node is QualifiedTypeIdentifier; +export function isUnionTypeAnnotation(node: object, opts?: object): node is UnionTypeAnnotation; +export function isVoidTypeAnnotation(node: object, opts?: object): node is VoidTypeAnnotation; +export function isJSXAttribute(node: object, opts?: object): node is JSXAttribute; +export function isJSXClosingElement(node: object, opts?: object): node is JSXClosingElement; +export function isJSXElement(node: object, opts?: object): node is JSXElement; +export function isJSXEmptyExpression(node: object, opts?: object): node is JSXEmptyExpression; +export function isJSXExpressionContainer(node: object, opts?: object): node is JSXExpressionContainer; +export function isJSXIdentifier(node: object, opts?: object): node is JSXIdentifier; +export function isJSXMemberExpression(node: object, opts?: object): node is JSXMemberExpression; +export function isJSXNamespacedName(node: object, opts?: object): node is JSXNamespacedName; +export function isJSXOpeningElement(node: object, opts?: object): node is JSXOpeningElement; +export function isJSXSpreadAttribute(node: object, opts?: object): node is JSXSpreadAttribute; +export function isJSXText(node: object, opts?: object): node is JSXText; +export function isNoop(node: object, opts?: object): node is Noop; +export function isParenthesizedExpression(node: object, opts?: object): node is ParenthesizedExpression; +export function isAwaitExpression(node: object, opts?: object): node is AwaitExpression; +export function isBindExpression(node: object, opts?: object): node is BindExpression; +export function isDecorator(node: object, opts?: object): node is Decorator; +export function isDoExpression(node: object, opts?: object): node is DoExpression; +export function isExportDefaultSpecifier(node: object, opts?: object): node is ExportDefaultSpecifier; +export function isExportNamespaceSpecifier(node: object, opts?: object): node is ExportNamespaceSpecifier; +export function isRestProperty(node: object, opts?: object): node is RestProperty; +export function isSpreadProperty(node: object, opts?: object): node is SpreadProperty; +export function isExpression(node: object, opts?: object): node is Expression; +export function isBinary(node: object, opts?: object): node is Binary; +export function isScopable(node: object, opts?: object): node is Scopable; +export function isBlockParent(node: object, opts?: object): node is BlockParent; +export function isBlock(node: object, opts?: object): node is Block; +export function isStatement(node: object, opts?: object): node is Statement; +export function isTerminatorless(node: object, opts?: object): node is Terminatorless; +export function isCompletionStatement(node: object, opts?: object): node is CompletionStatement; +export function isConditional(node: object, opts?: object): node is Conditional; +export function isLoop(node: object, opts?: object): node is Loop; +export function isWhile(node: object, opts?: object): node is While; +export function isExpressionWrapper(node: object, opts?: object): node is ExpressionWrapper; +export function isFor(node: object, opts?: object): node is For; +export function isForXStatement(node: object, opts?: object): node is ForXStatement; +// tslint:disable-next-line ban-types +export function isFunction(node: object, opts?: object): node is Function; +export function isFunctionParent(node: object, opts?: object): node is FunctionParent; +export function isPureish(node: object, opts?: object): node is Pureish; +export function isDeclaration(node: object, opts?: object): node is Declaration; +export function isLVal(node: object, opts?: object): node is LVal; +export function isLiteral(node: object, opts?: object): node is Literal; +export function isImmutable(node: object, opts?: object): node is Immutable; +export function isUserWhitespacable(node: object, opts?: object): node is UserWhitespacable; +export function isMethod(node: object, opts?: object): node is Method; +export function isObjectMember(node: object, opts?: object): node is ObjectMember; +export function isProperty(node: object, opts?: object): node is Property; +export function isUnaryLike(node: object, opts?: object): node is UnaryLike; +export function isPattern(node: object, opts?: object): node is Pattern; +export function isClass(node: object, opts?: object): node is Class; +export function isModuleDeclaration(node: object, opts?: object): node is ModuleDeclaration; +export function isExportDeclaration(node: object, opts?: object): node is ExportDeclaration; +export function isModuleSpecifier(node: object, opts?: object): node is ModuleSpecifier; +export function isFlow(node: object, opts?: object): node is Flow; +export function isFlowBaseAnnotation(node: object, opts?: object): node is FlowBaseAnnotation; +export function isFlowDeclaration(node: object, opts?: object): node is FlowDeclaration; +export function isJSX(node: object, opts?: object): node is JSX; +export function isNumberLiteral(node: object, opts?: object): node is NumericLiteral; +export function isRegexLiteral(node: object, opts?: object): node is RegExpLiteral; -export function isReferencedIdentifier(node: Object, opts?: Object): boolean; -export function isReferencedMemberExpression(node: Object, opts?: Object): boolean; -export function isBindingIdentifier(node: Object, opts?: Object): boolean; -export function isScope(node: Object, opts?: Object): boolean; -export function isReferenced(node: Object, opts?: Object): boolean; -export function isBlockScoped(node: Object, opts?: Object): boolean; -export function isVar(node: Object, opts?: Object): boolean; -export function isUser(node: Object, opts?: Object): boolean; -export function isGenerated(node: Object, opts?: Object): boolean; -export function isPure(node: Object, opts?: Object): boolean; +export function isReferencedIdentifier(node: object, opts?: object): boolean; +export function isReferencedMemberExpression(node: object, opts?: object): boolean; +export function isBindingIdentifier(node: object, opts?: object): boolean; +export function isScope(node: object, opts?: object): boolean; +export function isReferenced(node: object, opts?: object): boolean; +export function isBlockScoped(node: object, opts?: object): boolean; +export function isVar(node: object, opts?: object): boolean; +export function isUser(node: object, opts?: object): boolean; +export function isGenerated(node: object, opts?: object): boolean; +export function isPure(node: object, opts?: object): boolean; // React specific -interface ReactHelpers { +export interface ReactHelpers { isCompatTag(tagName?: string): boolean; - buildChildren(node: Object): Object[]; + buildChildren(node: object): Node[]; } export const react: ReactHelpers; -export function assertArrayExpression(node: Object, opts?: Object): void; -export function assertAssignmentExpression(node: Object, opts?: Object): void; -export function assertBinaryExpression(node: Object, opts?: Object): void; -export function assertDirective(node: Object, opts?: Object): void; -export function assertDirectiveLiteral(node: Object, opts?: Object): void; -export function assertBlockStatement(node: Object, opts?: Object): void; -export function assertBreakStatement(node: Object, opts?: Object): void; -export function assertCallExpression(node: Object, opts?: Object): void; -export function assertCatchClause(node: Object, opts?: Object): void; -export function assertConditionalExpression(node: Object, opts?: Object): void; -export function assertContinueStatement(node: Object, opts?: Object): void; -export function assertDebuggerStatement(node: Object, opts?: Object): void; -export function assertDoWhileStatement(node: Object, opts?: Object): void; -export function assertEmptyStatement(node: Object, opts?: Object): void; -export function assertExpressionStatement(node: Object, opts?: Object): void; -export function assertFile(node: Object, opts?: Object): void; -export function assertForInStatement(node: Object, opts?: Object): void; -export function assertForStatement(node: Object, opts?: Object): void; -export function assertFunctionDeclaration(node: Object, opts?: Object): void; -export function assertFunctionExpression(node: Object, opts?: Object): void; -export function assertIdentifier(node: Object, opts?: Object): void; -export function assertIfStatement(node: Object, opts?: Object): void; -export function assertLabeledStatement(node: Object, opts?: Object): void; -export function assertStringLiteral(node: Object, opts?: Object): void; -export function assertNumericLiteral(node: Object, opts?: Object): void; -export function assertNullLiteral(node: Object, opts?: Object): void; -export function assertBooleanLiteral(node: Object, opts?: Object): void; -export function assertRegExpLiteral(node: Object, opts?: Object): void; -export function assertLogicalExpression(node: Object, opts?: Object): void; -export function assertMemberExpression(node: Object, opts?: Object): void; -export function assertNewExpression(node: Object, opts?: Object): void; -export function assertProgram(node: Object, opts?: Object): void; -export function assertObjectExpression(node: Object, opts?: Object): void; -export function assertObjectMethod(node: Object, opts?: Object): void; -export function assertObjectProperty(node: Object, opts?: Object): void; -export function assertRestElement(node: Object, opts?: Object): void; -export function assertReturnStatement(node: Object, opts?: Object): void; -export function assertSequenceExpression(node: Object, opts?: Object): void; -export function assertSwitchCase(node: Object, opts?: Object): void; -export function assertSwitchStatement(node: Object, opts?: Object): void; -export function assertThisExpression(node: Object, opts?: Object): void; -export function assertThrowStatement(node: Object, opts?: Object): void; -export function assertTryStatement(node: Object, opts?: Object): void; -export function assertUnaryExpression(node: Object, opts?: Object): void; -export function assertUpdateExpression(node: Object, opts?: Object): void; -export function assertVariableDeclaration(node: Object, opts?: Object): void; -export function assertVariableDeclarator(node: Object, opts?: Object): void; -export function assertWhileStatement(node: Object, opts?: Object): void; -export function assertWithStatement(node: Object, opts?: Object): void; -export function assertAssignmentPattern(node: Object, opts?: Object): void; -export function assertArrayPattern(node: Object, opts?: Object): void; -export function assertArrowFunctionExpression(node: Object, opts?: Object): void; -export function assertClassBody(node: Object, opts?: Object): void; -export function assertClassDeclaration(node: Object, opts?: Object): void; -export function assertClassExpression(node: Object, opts?: Object): void; -export function assertExportAllDeclaration(node: Object, opts?: Object): void; -export function assertExportDefaultDeclaration(node: Object, opts?: Object): void; -export function assertExportNamedDeclaration(node: Object, opts?: Object): void; -export function assertExportSpecifier(node: Object, opts?: Object): void; -export function assertForOfStatement(node: Object, opts?: Object): void; -export function assertImportDeclaration(node: Object, opts?: Object): void; -export function assertImportDefaultSpecifier(node: Object, opts?: Object): void; -export function assertImportNamespaceSpecifier(node: Object, opts?: Object): void; -export function assertImportSpecifier(node: Object, opts?: Object): void; -export function assertMetaProperty(node: Object, opts?: Object): void; -export function assertClassMethod(node: Object, opts?: Object): void; -export function assertObjectPattern(node: Object, opts?: Object): void; -export function assertSpreadElement(node: Object, opts?: Object): void; -export function assertSuper(node: Object, opts?: Object): void; -export function assertTaggedTemplateExpression(node: Object, opts?: Object): void; -export function assertTemplateElement(node: Object, opts?: Object): void; -export function assertTemplateLiteral(node: Object, opts?: Object): void; -export function assertYieldExpression(node: Object, opts?: Object): void; -export function assertAnyTypeAnnotation(node: Object, opts?: Object): void; -export function assertArrayTypeAnnotation(node: Object, opts?: Object): void; -export function assertBooleanTypeAnnotation(node: Object, opts?: Object): void; -export function assertBooleanLiteralTypeAnnotation(node: Object, opts?: Object): void; -export function assertNullLiteralTypeAnnotation(node: Object, opts?: Object): void; -export function assertClassImplements(node: Object, opts?: Object): void; -export function assertClassProperty(node: Object, opts?: Object): void; -export function assertDeclareClass(node: Object, opts?: Object): void; -export function assertDeclareFunction(node: Object, opts?: Object): void; -export function assertDeclareInterface(node: Object, opts?: Object): void; -export function assertDeclareModule(node: Object, opts?: Object): void; -export function assertDeclareTypeAlias(node: Object, opts?: Object): void; -export function assertDeclareVariable(node: Object, opts?: Object): void; -export function assertExistentialTypeParam(node: Object, opts?: Object): void; -export function assertFunctionTypeAnnotation(node: Object, opts?: Object): void; -export function assertFunctionTypeParam(node: Object, opts?: Object): void; -export function assertGenericTypeAnnotation(node: Object, opts?: Object): void; -export function assertInterfaceExtends(node: Object, opts?: Object): void; -export function assertInterfaceDeclaration(node: Object, opts?: Object): void; -export function assertIntersectionTypeAnnotation(node: Object, opts?: Object): void; -export function assertMixedTypeAnnotation(node: Object, opts?: Object): void; -export function assertNullableTypeAnnotation(node: Object, opts?: Object): void; -export function assertNumericLiteralTypeAnnotation(node: Object, opts?: Object): void; -export function assertNumberTypeAnnotation(node: Object, opts?: Object): void; -export function assertStringLiteralTypeAnnotation(node: Object, opts?: Object): void; -export function assertStringTypeAnnotation(node: Object, opts?: Object): void; -export function assertThisTypeAnnotation(node: Object, opts?: Object): void; -export function assertTupleTypeAnnotation(node: Object, opts?: Object): void; -export function assertTypeofTypeAnnotation(node: Object, opts?: Object): void; -export function assertTypeAlias(node: Object, opts?: Object): void; -export function assertTypeAnnotation(node: Object, opts?: Object): void; -export function assertTypeCastExpression(node: Object, opts?: Object): void; -export function assertTypeParameterDeclaration(node: Object, opts?: Object): void; -export function assertTypeParameterInstantiation(node: Object, opts?: Object): void; -export function assertObjectTypeAnnotation(node: Object, opts?: Object): void; -export function assertObjectTypeCallProperty(node: Object, opts?: Object): void; -export function assertObjectTypeIndexer(node: Object, opts?: Object): void; -export function assertObjectTypeProperty(node: Object, opts?: Object): void; -export function assertQualifiedTypeIdentifier(node: Object, opts?: Object): void; -export function assertUnionTypeAnnotation(node: Object, opts?: Object): void; -export function assertVoidTypeAnnotation(node: Object, opts?: Object): void; -export function assertJSXAttribute(node: Object, opts?: Object): void; -export function assertJSXClosingElement(node: Object, opts?: Object): void; -export function assertJSXElement(node: Object, opts?: Object): void; -export function assertJSXEmptyExpression(node: Object, opts?: Object): void; -export function assertJSXExpressionContainer(node: Object, opts?: Object): void; -export function assertJSXIdentifier(node: Object, opts?: Object): void; -export function assertJSXMemberExpression(node: Object, opts?: Object): void; -export function assertJSXNamespacedName(node: Object, opts?: Object): void; -export function assertJSXOpeningElement(node: Object, opts?: Object): void; -export function assertJSXSpreadAttribute(node: Object, opts?: Object): void; -export function assertJSXText(node: Object, opts?: Object): void; -export function assertNoop(node: Object, opts?: Object): void; -export function assertParenthesizedExpression(node: Object, opts?: Object): void; -export function assertAwaitExpression(node: Object, opts?: Object): void; -export function assertBindExpression(node: Object, opts?: Object): void; -export function assertDecorator(node: Object, opts?: Object): void; -export function assertDoExpression(node: Object, opts?: Object): void; -export function assertExportDefaultSpecifier(node: Object, opts?: Object): void; -export function assertExportNamespaceSpecifier(node: Object, opts?: Object): void; -export function assertRestProperty(node: Object, opts?: Object): void; -export function assertSpreadProperty(node: Object, opts?: Object): void; -export function assertExpression(node: Object, opts?: Object): void; -export function assertBinary(node: Object, opts?: Object): void; -export function assertScopable(node: Object, opts?: Object): void; -export function assertBlockParent(node: Object, opts?: Object): void; -export function assertBlock(node: Object, opts?: Object): void; -export function assertStatement(node: Object, opts?: Object): void; -export function assertTerminatorless(node: Object, opts?: Object): void; -export function assertCompletionStatement(node: Object, opts?: Object): void; -export function assertConditional(node: Object, opts?: Object): void; -export function assertLoop(node: Object, opts?: Object): void; -export function assertWhile(node: Object, opts?: Object): void; -export function assertExpressionWrapper(node: Object, opts?: Object): void; -export function assertFor(node: Object, opts?: Object): void; -export function assertForXStatement(node: Object, opts?: Object): void; -export function assertFunction(node: Object, opts?: Object): void; -export function assertFunctionParent(node: Object, opts?: Object): void; -export function assertPureish(node: Object, opts?: Object): void; -export function assertDeclaration(node: Object, opts?: Object): void; -export function assertLVal(node: Object, opts?: Object): void; -export function assertLiteral(node: Object, opts?: Object): void; -export function assertImmutable(node: Object, opts?: Object): void; -export function assertUserWhitespacable(node: Object, opts?: Object): void; -export function assertMethod(node: Object, opts?: Object): void; -export function assertObjectMember(node: Object, opts?: Object): void; -export function assertProperty(node: Object, opts?: Object): void; -export function assertUnaryLike(node: Object, opts?: Object): void; -export function assertPattern(node: Object, opts?: Object): void; -export function assertClass(node: Object, opts?: Object): void; -export function assertModuleDeclaration(node: Object, opts?: Object): void; -export function assertExportDeclaration(node: Object, opts?: Object): void; -export function assertModuleSpecifier(node: Object, opts?: Object): void; -export function assertFlow(node: Object, opts?: Object): void; -export function assertFlowBaseAnnotation(node: Object, opts?: Object): void; -export function assertFlowDeclaration(node: Object, opts?: Object): void; -export function assertJSX(node: Object, opts?: Object): void; -export function assertNumberLiteral(node: Object, opts?: Object): void; -export function assertRegexLiteral(node: Object, opts?: Object): void; - +export function assertArrayExpression(node: object, opts?: object): void; +export function assertAssignmentExpression(node: object, opts?: object): void; +export function assertBinaryExpression(node: object, opts?: object): void; +export function assertDirective(node: object, opts?: object): void; +export function assertDirectiveLiteral(node: object, opts?: object): void; +export function assertBlockStatement(node: object, opts?: object): void; +export function assertBreakStatement(node: object, opts?: object): void; +export function assertCallExpression(node: object, opts?: object): void; +export function assertCatchClause(node: object, opts?: object): void; +export function assertConditionalExpression(node: object, opts?: object): void; +export function assertContinueStatement(node: object, opts?: object): void; +export function assertDebuggerStatement(node: object, opts?: object): void; +export function assertDoWhileStatement(node: object, opts?: object): void; +export function assertEmptyStatement(node: object, opts?: object): void; +export function assertExpressionStatement(node: object, opts?: object): void; +export function assertFile(node: object, opts?: object): void; +export function assertForInStatement(node: object, opts?: object): void; +export function assertForStatement(node: object, opts?: object): void; +export function assertFunctionDeclaration(node: object, opts?: object): void; +export function assertFunctionExpression(node: object, opts?: object): void; +export function assertIdentifier(node: object, opts?: object): void; +export function assertIfStatement(node: object, opts?: object): void; +export function assertLabeledStatement(node: object, opts?: object): void; +export function assertStringLiteral(node: object, opts?: object): void; +export function assertNumericLiteral(node: object, opts?: object): void; +export function assertNullLiteral(node: object, opts?: object): void; +export function assertBooleanLiteral(node: object, opts?: object): void; +export function assertRegExpLiteral(node: object, opts?: object): void; +export function assertLogicalExpression(node: object, opts?: object): void; +export function assertMemberExpression(node: object, opts?: object): void; +export function assertNewExpression(node: object, opts?: object): void; +export function assertProgram(node: object, opts?: object): void; +export function assertObjectExpression(node: object, opts?: object): void; +export function assertObjectMethod(node: object, opts?: object): void; +export function assertObjectProperty(node: object, opts?: object): void; +export function assertRestElement(node: object, opts?: object): void; +export function assertReturnStatement(node: object, opts?: object): void; +export function assertSequenceExpression(node: object, opts?: object): void; +export function assertSwitchCase(node: object, opts?: object): void; +export function assertSwitchStatement(node: object, opts?: object): void; +export function assertThisExpression(node: object, opts?: object): void; +export function assertThrowStatement(node: object, opts?: object): void; +export function assertTryStatement(node: object, opts?: object): void; +export function assertUnaryExpression(node: object, opts?: object): void; +export function assertUpdateExpression(node: object, opts?: object): void; +export function assertVariableDeclaration(node: object, opts?: object): void; +export function assertVariableDeclarator(node: object, opts?: object): void; +export function assertWhileStatement(node: object, opts?: object): void; +export function assertWithStatement(node: object, opts?: object): void; +export function assertAssignmentPattern(node: object, opts?: object): void; +export function assertArrayPattern(node: object, opts?: object): void; +export function assertArrowFunctionExpression(node: object, opts?: object): void; +export function assertClassBody(node: object, opts?: object): void; +export function assertClassDeclaration(node: object, opts?: object): void; +export function assertClassExpression(node: object, opts?: object): void; +export function assertExportAllDeclaration(node: object, opts?: object): void; +export function assertExportDefaultDeclaration(node: object, opts?: object): void; +export function assertExportNamedDeclaration(node: object, opts?: object): void; +export function assertExportSpecifier(node: object, opts?: object): void; +export function assertForOfStatement(node: object, opts?: object): void; +export function assertImportDeclaration(node: object, opts?: object): void; +export function assertImportDefaultSpecifier(node: object, opts?: object): void; +export function assertImportNamespaceSpecifier(node: object, opts?: object): void; +export function assertImportSpecifier(node: object, opts?: object): void; +export function assertMetaProperty(node: object, opts?: object): void; +export function assertClassMethod(node: object, opts?: object): void; +export function assertObjectPattern(node: object, opts?: object): void; +export function assertSpreadElement(node: object, opts?: object): void; +export function assertSuper(node: object, opts?: object): void; +export function assertTaggedTemplateExpression(node: object, opts?: object): void; +export function assertTemplateElement(node: object, opts?: object): void; +export function assertTemplateLiteral(node: object, opts?: object): void; +export function assertYieldExpression(node: object, opts?: object): void; +export function assertAnyTypeAnnotation(node: object, opts?: object): void; +export function assertArrayTypeAnnotation(node: object, opts?: object): void; +export function assertBooleanTypeAnnotation(node: object, opts?: object): void; +export function assertBooleanLiteralTypeAnnotation(node: object, opts?: object): void; +export function assertNullLiteralTypeAnnotation(node: object, opts?: object): void; +export function assertClassImplements(node: object, opts?: object): void; +export function assertClassProperty(node: object, opts?: object): void; +export function assertDeclareClass(node: object, opts?: object): void; +export function assertDeclareFunction(node: object, opts?: object): void; +export function assertDeclareInterface(node: object, opts?: object): void; +export function assertDeclareModule(node: object, opts?: object): void; +export function assertDeclareTypeAlias(node: object, opts?: object): void; +export function assertDeclareVariable(node: object, opts?: object): void; +export function assertExistentialTypeParam(node: object, opts?: object): void; +export function assertFunctionTypeAnnotation(node: object, opts?: object): void; +export function assertFunctionTypeParam(node: object, opts?: object): void; +export function assertGenericTypeAnnotation(node: object, opts?: object): void; +export function assertInterfaceExtends(node: object, opts?: object): void; +export function assertInterfaceDeclaration(node: object, opts?: object): void; +export function assertIntersectionTypeAnnotation(node: object, opts?: object): void; +export function assertMixedTypeAnnotation(node: object, opts?: object): void; +export function assertNullableTypeAnnotation(node: object, opts?: object): void; +export function assertNumericLiteralTypeAnnotation(node: object, opts?: object): void; +export function assertNumberTypeAnnotation(node: object, opts?: object): void; +export function assertStringLiteralTypeAnnotation(node: object, opts?: object): void; +export function assertStringTypeAnnotation(node: object, opts?: object): void; +export function assertThisTypeAnnotation(node: object, opts?: object): void; +export function assertTupleTypeAnnotation(node: object, opts?: object): void; +export function assertTypeofTypeAnnotation(node: object, opts?: object): void; +export function assertTypeAlias(node: object, opts?: object): void; +export function assertTypeAnnotation(node: object, opts?: object): void; +export function assertTypeCastExpression(node: object, opts?: object): void; +export function assertTypeParameterDeclaration(node: object, opts?: object): void; +export function assertTypeParameterInstantiation(node: object, opts?: object): void; +export function assertObjectTypeAnnotation(node: object, opts?: object): void; +export function assertObjectTypeCallProperty(node: object, opts?: object): void; +export function assertObjectTypeIndexer(node: object, opts?: object): void; +export function assertObjectTypeProperty(node: object, opts?: object): void; +export function assertQualifiedTypeIdentifier(node: object, opts?: object): void; +export function assertUnionTypeAnnotation(node: object, opts?: object): void; +export function assertVoidTypeAnnotation(node: object, opts?: object): void; +export function assertJSXAttribute(node: object, opts?: object): void; +export function assertJSXClosingElement(node: object, opts?: object): void; +export function assertJSXElement(node: object, opts?: object): void; +export function assertJSXEmptyExpression(node: object, opts?: object): void; +export function assertJSXExpressionContainer(node: object, opts?: object): void; +export function assertJSXIdentifier(node: object, opts?: object): void; +export function assertJSXMemberExpression(node: object, opts?: object): void; +export function assertJSXNamespacedName(node: object, opts?: object): void; +export function assertJSXOpeningElement(node: object, opts?: object): void; +export function assertJSXSpreadAttribute(node: object, opts?: object): void; +export function assertJSXText(node: object, opts?: object): void; +export function assertNoop(node: object, opts?: object): void; +export function assertParenthesizedExpression(node: object, opts?: object): void; +export function assertAwaitExpression(node: object, opts?: object): void; +export function assertBindExpression(node: object, opts?: object): void; +export function assertDecorator(node: object, opts?: object): void; +export function assertDoExpression(node: object, opts?: object): void; +export function assertExportDefaultSpecifier(node: object, opts?: object): void; +export function assertExportNamespaceSpecifier(node: object, opts?: object): void; +export function assertRestProperty(node: object, opts?: object): void; +export function assertSpreadProperty(node: object, opts?: object): void; +export function assertExpression(node: object, opts?: object): void; +export function assertBinary(node: object, opts?: object): void; +export function assertScopable(node: object, opts?: object): void; +export function assertBlockParent(node: object, opts?: object): void; +export function assertBlock(node: object, opts?: object): void; +export function assertStatement(node: object, opts?: object): void; +export function assertTerminatorless(node: object, opts?: object): void; +export function assertCompletionStatement(node: object, opts?: object): void; +export function assertConditional(node: object, opts?: object): void; +export function assertLoop(node: object, opts?: object): void; +export function assertWhile(node: object, opts?: object): void; +export function assertExpressionWrapper(node: object, opts?: object): void; +export function assertFor(node: object, opts?: object): void; +export function assertForXStatement(node: object, opts?: object): void; +export function assertFunction(node: object, opts?: object): void; +export function assertFunctionParent(node: object, opts?: object): void; +export function assertPureish(node: object, opts?: object): void; +export function assertDeclaration(node: object, opts?: object): void; +export function assertLVal(node: object, opts?: object): void; +export function assertLiteral(node: object, opts?: object): void; +export function assertImmutable(node: object, opts?: object): void; +export function assertUserWhitespacable(node: object, opts?: object): void; +export function assertMethod(node: object, opts?: object): void; +export function assertObjectMember(node: object, opts?: object): void; +export function assertProperty(node: object, opts?: object): void; +export function assertUnaryLike(node: object, opts?: object): void; +export function assertPattern(node: object, opts?: object): void; +export function assertClass(node: object, opts?: object): void; +export function assertModuleDeclaration(node: object, opts?: object): void; +export function assertExportDeclaration(node: object, opts?: object): void; +export function assertModuleSpecifier(node: object, opts?: object): void; +export function assertFlow(node: object, opts?: object): void; +export function assertFlowBaseAnnotation(node: object, opts?: object): void; +export function assertFlowDeclaration(node: object, opts?: object): void; +export function assertJSX(node: object, opts?: object): void; +export function assertNumberLiteral(node: object, opts?: object): void; +export function assertRegexLiteral(node: object, opts?: object): void; diff --git a/types/babel-types/tslint.json b/types/babel-types/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babel-types/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/babelify/index.d.ts b/types/babelify/index.d.ts index c69eef42b2..f394d2ba44 100644 --- a/types/babelify/index.d.ts +++ b/types/babelify/index.d.ts @@ -1,7 +1,9 @@ // Type definitions for babelify v7.3.0 // Project: https://github.com/babel/babelify // Definitions by: TeamworkGuy2 +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/babylon/babylon-tests.ts b/types/babylon/babylon-tests.ts index 769d635e89..d844b9a8f7 100644 --- a/types/babylon/babylon-tests.ts +++ b/types/babylon/babylon-tests.ts @@ -12,7 +12,6 @@ assert(node.start === 0); assert(node.end === 38); assert(node.loc.start > node.loc.end); - babylon.parse(code, { sourceType: "module", // default: "script" plugins: ["jsx"] // default: [] diff --git a/types/babylon/index.d.ts b/types/babylon/index.d.ts index eb35a5d799..eb22f30c13 100644 --- a/types/babylon/index.d.ts +++ b/types/babylon/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for babylon v6.16.1 +// Type definitions for babylon 6.16 // Project: https://github.com/babel/babylon // Definitions by: Troy Gerwien +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// +// TypeScript Version: 2.3 import { File, Expression } from 'babel-types'; diff --git a/types/babylon/tslint.json b/types/babylon/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babylon/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/basic-auth/basic-auth-tests.ts b/types/basic-auth/basic-auth-tests.ts index e416afe352..9c03137b37 100644 --- a/types/basic-auth/basic-auth-tests.ts +++ b/types/basic-auth/basic-auth-tests.ts @@ -1,4 +1,4 @@ -import {IncomingMessage} from 'http'; +import { IncomingMessage } from 'http'; import auth = require('basic-auth'); const loginData = auth(undefined! as IncomingMessage); diff --git a/types/bintrees/bintrees-tests.ts b/types/bintrees/bintrees-tests.ts index 707d8e0adf..fb4a22a3d8 100644 --- a/types/bintrees/bintrees-tests.ts +++ b/types/bintrees/bintrees-tests.ts @@ -1,14 +1,50 @@ +/// +/// +import assert = require('assert'); import { BinTree, RBTree } from 'bintrees'; -let treeA = new RBTree((a:number, b:number) => a - b); +describe('bintrees', () => { + it('builds a simple tree', () => { + let treeA = new RBTree((a: number, b: number) => a - b); -treeA.insert(5); -treeA.insert(3); -treeA.remove(3); + treeA.insert(5); + treeA.insert(3); + treeA.remove(3); -let treeB = new BinTree((a:string, b:string) => a.length - b.length); + assert.equal(treeA.size, 1); + }); + + it('builds a tree of strings', () => { + let treeB = new BinTree((a:string, b:string) => a.length - b.length); + + treeB.insert('hi'); + treeB.insert('there'); + treeB.insert('how'); + treeB.insert('are'); // ignored + treeB.remove('how'); + + assert.equal(treeB.size, 2); + assert.equal(treeB.min(), 'hi'); + }); + + it('maintains a tree of objects', () => { + + interface C { + id: number + } + + let treeC = new BinTree((a: C, b: C) => a.id - b.id); + + treeC.insert({ id: 100 }); + treeC.insert({ id: 110 }); + treeC.insert({ id: 105 }); + + let ids: number[] = []; + treeC.each((val: C) => { + ids.push(val.id); + }); + + assert.deepEqual(ids, [100, 105, 110]); + }); +}); -treeB.insert('hi'); -treeB.insert('there'); -treeB.insert('how'); -treeB.insert('are'); diff --git a/types/bintrees/index.d.ts b/types/bintrees/index.d.ts index 7a7b2c233e..743997dc03 100644 --- a/types/bintrees/index.d.ts +++ b/types/bintrees/index.d.ts @@ -5,8 +5,8 @@ declare module 'bintrees' { - type Callback = (item: T) => void; - type Comparator = (a: T, b: T) => number; + type Callback = (item: T) => void; + type Comparator = (a: T, b: T) => number; class Iterator { constructor(tree: TreeBase); @@ -37,14 +37,14 @@ declare module 'bintrees' { iterator(): Iterator; - each(cb: Callback): void; + each(cb: Callback): void; - reach(cb: Callback): void; + reach(cb: Callback): void; } export class RBTree extends TreeBase { - constructor(comparator: Comparator); + constructor(comparator: Comparator); insert(item: T): boolean; @@ -52,7 +52,7 @@ declare module 'bintrees' { } export class BinTree extends TreeBase { - constructor(comparator: Comparator); + constructor(comparator: Comparator); insert(item: T): boolean; diff --git a/types/bleno/tslint.json b/types/bleno/tslint.json index 377cc837d4..3db14f85ea 100644 --- a/types/bleno/tslint.json +++ b/types/bleno/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } +{ "extends": "dtslint/dt.json" } diff --git a/types/blessed/index.d.ts b/types/blessed/index.d.ts index b08f77b3b1..abbc31d295 100644 --- a/types/blessed/index.d.ts +++ b/types/blessed/index.d.ts @@ -5,7 +5,7 @@ /// -import {EventEmitter} from 'events'; +import { EventEmitter } from 'events'; import * as stream from "stream"; import * as child_process from "child_process"; diff --git a/types/bootstrap-table/index.d.ts b/types/bootstrap-table/index.d.ts index e70ada9e38..166289f14f 100644 --- a/types/bootstrap-table/index.d.ts +++ b/types/bootstrap-table/index.d.ts @@ -7,7 +7,8 @@ /// interface JQuery { - bootstrapTable(options?: any): JQuery; + bootstrapTable(options?: any): JQuery; + bootstrapTable(method: string, parameter?: any): JQuery; } declare var bootstrapTable: JQueryStatic; diff --git a/types/bwip-js/index.d.ts b/types/bwip-js/index.d.ts index 9c37fa6e44..04732ef703 100644 --- a/types/bwip-js/index.d.ts +++ b/types/bwip-js/index.d.ts @@ -5,7 +5,7 @@ /// -import {IncomingMessage as Request, ServerResponse as Response} from 'http'; +import { IncomingMessage as Request, ServerResponse as Response } from 'http'; declare namespace BwipJs { export function loadFont(fontName:string, sizeMulti: number, fontFile: string): void; diff --git a/types/catbox/catbox-tests.ts b/types/catbox/catbox-tests.ts new file mode 100644 index 0000000000..565573adad --- /dev/null +++ b/types/catbox/catbox-tests.ts @@ -0,0 +1,27 @@ +import Catbox = require("catbox"); + +const Memory: Catbox.EnginePrototypeOrObject = { + start(callback: Catbox.CallBackNoResult) {}, + stop() {}, + get() {}, + set() {}, + drop() {}, + isReady(): boolean { return true; }, + validateSegmentName(segment: string): null { return null; }, +}; + +const client = new Catbox.Client(Memory, { partition: 'cache' }); + +const cache = new Catbox.Policy({ + expiresIn: 5000, +}, client, 'cache'); + +cache.set('foo', 'bar', 5000, () => {}); + +cache.get('foo', () => {}); + +cache.drop('foo', () => {}); + +cache.isReady(); + +cache.stats(); diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts index 5dad5af29a..e34059d618 100644 --- a/types/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -6,12 +6,8 @@ import * as Boom from 'boom'; -export interface CallBackNoResult { - (err?: Boom.BoomError): void; -} -export interface CallBackWithResult { - (err: Boom.BoomError | null | undefined, result: T): void; -} +export type CallBackNoResult = (err?: Boom.BoomError) => void; +export type CallBackWithResult = (err: Boom.BoomError | null | undefined, result: T) => void; /** * Client @@ -20,14 +16,44 @@ export interface CallBackWithResult { * * function - a prototype function with the signature function(options). catbox will call new func(options). * * object - a pre instantiated client implementation object. Does not support passing options. * options - the strategy configuration object. Each strategy defines its own configuration options with the following common options: - * * partition - the partition name used to isolate the cached results across multiple clients. The partition name is used as the MongoDB database name, the Riak bucket, or as a key prefix in Redis and Memcached. To share the cache across multiple clients, use the same partition name. + * * partition - the partition name used to isolate the cached results across multiple clients. The partition name is used as the MongoDB database name, + * the Riak bucket, or as a key prefix in Redis and Memcached. To share the cache across multiple clients, use the same partition name. * @see {@link https://github.com/hapijs/catbox#client} */ -export interface Client extends ClientApi { - new(engine: EnginePrototypeOrObject, options: ClientOptions): Client; +export class Client implements ClientApi { + constructor(engine: EnginePrototypeOrObject, options: ClientOptions); + + /** start(callback) - creates a connection to the cache server. Must be called before any other method is available. The callback signature is function(err). */ + start(callback: CallBackNoResult): void; + /** stop() - terminates the connection to the cache server. */ + stop(): void; + /** + * get(key, callback) - retrieve an item from the cache engine if found where: + * * key - a cache key object (see [ICacheKey]). + * * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned + */ + get(key: CacheKey, callback: CallBackWithResult): CacheItem; + /** + * set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where: + * * key - a cache key object (see [ICacheKey]). + * * value - the string or object value to be stored. + * * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * * callback - a function with the signature function(err). + */ + set(key: CacheKey, value: CacheItem, ttl: number, callback: CallBackNoResult): void; + /** + * drop(key, callback) - remove an item from cache where: + * * key - a cache key object (see [ICacheKey]). + * * callback - a function with the signature function(err). + */ + drop(key: CacheKey, callback: CallBackNoResult): void; + /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */ + isReady(): boolean; + /** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */ + validateSegmentName(segment: string): null | Boom.BoomError; } -type EnginePrototypeOrObject = EnginePrototype | ClientApi; +export type EnginePrototypeOrObject = EnginePrototype | ClientApi; /** * A prototype CatBox engine function @@ -50,7 +76,7 @@ export interface ClientApi { * get(key, callback) - retrieve an item from the cache engine if found where: * * key - a cache key object (see [ICacheKey]). * * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned - */ + */ get(key: CacheKey, callback: CallBackWithResult): CacheItem; /** * set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where: @@ -92,21 +118,52 @@ export interface CachedObject { ttl: number; } -type CacheItem = any; +export type CacheItem = any; export interface ClientOptions { partition: string; } /** - * The Policy object provides a convenient cache interface by setting a global policy which is automatically applied to every storage action. The object is constructed using new Policy(options, [cache, segment]) where: + * The Policy object provides a convenient cache interface by setting a global policy which is automatically applied to every storage action. + * The object is constructed using new Policy(options, [cache, segment]) where: * * options - an object with the IPolicyOptions structure * * cache - a Client instance (which has already been started). * * segment - required when cache is provided. The segment name used to isolate cached items within the cache partition. * @see {@link https://github.com/hapijs/catbox#policy} */ -export interface Policy extends PolicyAPI { - new(options: PolicyOptions, cache: Client, segment: string): Policy; +export class Policy implements PolicyAPI { + constructor(options: PolicyOptions, cache: Client, segment: string); + /** + * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, + * a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: + * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. + * * callback - the return function. + */ + get(id: string | {id: string}, callback: PolicyGetCallback): CacheItem; + /** + * set(id, value, ttl, callback) - store an item in the cache where: + * * id - the unique item identifier (within the policy segment). + * * value - the string or object value to be stored. + * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * This should be set to 0 in order to use the caching rules configured when creating the Policy object. + * * callback - a function with the signature function(err). + */ + set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void; + /** + * drop(id, callback) - remove the item from cache where: + * * id - the unique item identifier (within the policy segment). + * * callback - a function with the signature function(err). + */ + drop(id: string | {id: string}, callback: CallBackNoResult): void; + /** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */ + ttl(created: number): number; + /** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */ + rules(options: PolicyOptions): void; + /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready or if there is no cache engine set. */ + isReady(): boolean; + /** stats - an object with cache statistics */ + stats(): CacheStatisticsObject; } /** @@ -116,7 +173,8 @@ export interface Policy extends PolicyAPI { */ export interface PolicyAPI { /** - * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: + * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, + * a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. * * callback - the return function. */ @@ -125,7 +183,8 @@ export interface PolicyAPI { * set(id, value, ttl, callback) - store an item in the cache where: * * id - the unique item identifier (within the policy segment). * * value - the string or object value to be stored. - * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). This should be set to 0 in order to use the caching rules configured when creating the Policy object. + * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * This should be set to 0 in order to use the caching rules configured when creating the Policy object. * * callback - a function with the signature function(err). */ set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void; @@ -152,9 +211,7 @@ export interface PolicyAPI { * @param cached - null if a valid item was not found in the cache, or IPolicyGetCallbackCachedOptions * @param report - an object with logging information about the generation operation */ -export interface PolicyGetCallback{ - (err: null | Boom.BoomError, value: CacheItem, cached: PolicyGetCallbackCachedOptions, report: PolicyGetCallbackReportLog): void; -} +export type PolicyGetCallback = (err: null | Boom.BoomError, value: CacheItem, cached: PolicyGetCallbackCachedOptions, report: PolicyGetCallbackReportLog) => void; export interface PolicyGetCallbackCachedOptions { /** item - the cached value. */ @@ -178,14 +235,19 @@ export interface PolicyOptions { /** generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: */ generateFunc?: GenerateFunc; /** - * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. Alternatively function that returns staleIn value in milliseconds. The function signature is function(stored, ttl) where: + * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. + * Must be less than expiresIn. Alternatively function that returns staleIn value in milliseconds. The function signature is function(stored, ttl) where: * * stored - the timestamp when the item was stored in the cache (in milliseconds). * * ttl - the remaining time-to-live (not the original value used when storing the object). - */ + */ staleIn?: number | ((stored: number, ttl: number) => number); /** staleTimeout - number of milliseconds to wait before returning a stale value while generateFunc is generating a fresh value. */ staleTimeout?: number; - /** generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. */ + /** + * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. + * When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. + * Set to false to disable timeouts which may cause all get() requests to get stuck forever. + */ generateTimeout?: number | false; /** dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. */ dropOnError?: boolean; @@ -193,7 +255,10 @@ export interface PolicyOptions { generateOnReadError?: boolean; /** generateIgnoreWriteError - if false, an upstream cache write error will be passed back with the generated value when calling the get() method. Defaults to true. */ generateIgnoreWriteError?: boolean; - /** pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0, no blocking of concurrent generateFunc calls beyond staleTimeout. */ + /** + * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. + * Defaults to 0, no blocking of concurrent generateFunc calls beyond staleTimeout. + */ pendingGenerateTimeout?: number; } @@ -208,9 +273,7 @@ export interface PolicyOptions { * * ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. * @see {@link https://github.com/hapijs/catbox#policy} */ -export interface GenerateFunc { - (id: string, next: ((err: null | Boom.BoomError, value: CacheItem, ttl?: number) => void)): void; -} +export type GenerateFunc = (id: string, next: ((err: null | Boom.BoomError, value: CacheItem, ttl?: number) => void)) => void; /** * An object with logging information about the generation operation containing the following keys (as relevant): @@ -242,6 +305,6 @@ export interface CacheStatisticsObject { stales: number; /** generates - number of calls to the generate function. */ generates: number; - /** errors - cache operations errors. TODO check this*/ + /** errors - cache operations errors. TODO check this */ errors: number; } diff --git a/types/catbox/tsconfig.json b/types/catbox/tsconfig.json index 3bc13b0278..b04177a675 100644 --- a/types/catbox/tsconfig.json +++ b/types/catbox/tsconfig.json @@ -16,6 +16,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts" + "index.d.ts", + "catbox-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/catbox/tslint.json b/types/catbox/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/catbox/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index f1a39c84c4..a465806797 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -159,6 +159,8 @@ declare namespace Chart { elements?: ChartElementsOptions; scales?: ChartScales; cutoutPercentage?: number; + circumference?: number; + rotation?: number; } interface ChartFontOptions { diff --git a/types/chokidar/index.d.ts b/types/chokidar/index.d.ts index 09e957aa05..b60a4a5655 100644 --- a/types/chokidar/index.d.ts +++ b/types/chokidar/index.d.ts @@ -6,7 +6,7 @@ /// import * as fs from 'fs'; -import {EventEmitter} from 'events'; +import { EventEmitter } from 'events'; /** * The object's keys are all the directories (using absolute paths unless the `cwd` option was diff --git a/types/clear-require/clear-require-tests.ts b/types/clear-require/clear-require-tests.ts new file mode 100644 index 0000000000..53aea4d832 --- /dev/null +++ b/types/clear-require/clear-require-tests.ts @@ -0,0 +1,8 @@ +import * as clear from 'clear-require'; + +clear('my-module'); // clear specific module from require cache + +clear.all(); // clear all of the require cache + +clear.match(new RegExp('^.*$')); // clear all modules which match the RegExp +clear.match(/^.*$/); // similar to above but using /regex/ notation diff --git a/types/clear-require/index.d.ts b/types/clear-require/index.d.ts new file mode 100644 index 0000000000..4b9118a008 --- /dev/null +++ b/types/clear-require/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for clear-require 2.0 +// Project: https://github.com/sindresorhus/clear-module +// Definitions by: dan-j +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface ClearRequire { + (moduleId: string): boolean; + all(): void; + match(regex: RegExp): void; +} + +declare const clear: ClearRequire; + +export = clear; diff --git a/types/clear-require/tsconfig.json b/types/clear-require/tsconfig.json new file mode 100644 index 0000000000..9c28741f0b --- /dev/null +++ b/types/clear-require/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", + "clear-require-tests.ts" + ] +} diff --git a/types/clear-require/tslint.json b/types/clear-require/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/clear-require/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/closure-compiler/closure-compiler-tests.ts b/types/closure-compiler/closure-compiler-tests.ts index 3dd827a0f8..44693fca43 100644 --- a/types/closure-compiler/closure-compiler-tests.ts +++ b/types/closure-compiler/closure-compiler-tests.ts @@ -1,4 +1,4 @@ -import {compile} from 'closure-compiler'; +import { compile } from 'closure-compiler'; compile('some.source()', {'check-only': null}, (err: Error, stdout: string, stderr: string): void => { diff --git a/types/color-convert/color-convert-tests.ts b/types/color-convert/color-convert-tests.ts new file mode 100644 index 0000000000..735c169a2f --- /dev/null +++ b/types/color-convert/color-convert-tests.ts @@ -0,0 +1,6 @@ +import * as color from 'color-convert'; +import * as conv from 'color-convert/conversions'; + +let hsv: [number, number, number] = color.rgb.hsv([1, 2, 3]); +let hsv_raw: [number, number, number] = color.rgb.hsv.raw([1, 2, 3]); +let aaa: [number, number, number] = color.rgb.hsv([1, 2, 3]); diff --git a/types/color-convert/conversions.d.ts b/types/color-convert/conversions.d.ts new file mode 100644 index 0000000000..aa461d40b0 --- /dev/null +++ b/types/color-convert/conversions.d.ts @@ -0,0 +1,136 @@ +import * as cssKeywords from 'color-name'; + +export type RGB = [number, number, number]; +export type HSL = [number, number, number]; +export type HSV = [number, number, number]; +export type HWB = [number, number, number]; +export type CMYK = [number, number, number, number]; +export type XYZ = [number, number, number]; +export type LAB = [number, number, number]; +export type LCH = [number, number, number]; +export type HEX = string; +export type KEYWORD = keyof typeof cssKeywords; +export type ANSI16 = number; +export type ANSI256 = number; +export type HCG = [number, number, number]; +export type APPLE = [number, number, number]; +export type GRAY = [number]; + +export namespace rgb { + const channels: 3; + const labels: 'rgb'; + function hsl(rgb: RGB): HSL; + function hsv(rgb: RGB): HSV; + function hwb(rgb: RGB): HWB; + function cmyk(rgb: RGB): CMYK; + function keyword(rgb: RGB): KEYWORD; + function xyz(rgb: RGB): XYZ; + function lab(rgb: RGB): LAB; + function ansi16(rgb: RGB): ANSI16; + function ansi256(rgb: RGB): ANSI256; + function hex(rgb: RGB): HEX; + function hcg(rgb: RGB): HCG; + function apple(rgb: RGB): APPLE; + function gray(rgb: RGB): GRAY; +} + +export namespace hsl { + const channels: 3; + const labels: 'hsl'; + function rgb(hsl: HSL): RGB; + function hsv(hsl: HSL): HSV; + function hcg(hsl: HSL): HCG; +} + +export namespace hsv { + const channels: 3; + const labels: 'hsv'; + function rgb(hsv: HSV): RGB; + function hsl(hsv: HSV): HSL; + function ansi16(hsv: HSV): ANSI16; + function hcg(hsv: HSV): HCG; +} + +export namespace hwb { + const channels: 3; + const labels: 'hwb'; + function rgb(hwb: HWB): RGB; + function hcg(hwb: HWB): HCG; +} + +export namespace cmyk { + const channels: 4; + const labels: 'cmyk'; + function rgb(cmyk: CMYK): RGB; +} + +export namespace xyz { + const channels: 3; + const labels: 'xyz'; + function rgb(xyz: XYZ): RGB; + function lab(xyz: XYZ): LAB; +} + +export namespace lab { + const channels: 3; + const labels: 'lab'; + function xyz(lab: LAB): XYZ; + function lch(lab: LAB): LCH; +} + +export namespace lch { + const channels: 3; + const labels: 'lch'; + function lab(lch: LCH): LAB; +} + +export namespace hex { + const channels: 1; + const labels: ['hex']; + function rgb(hex: HEX): RGB; +} + +export namespace keyword { + const channels: 1; + const labels: ['keyword']; + function rgb(keyword: KEYWORD): RGB; +} + +export namespace ansi16 { + const channels: 1; + const labels: ['ansi16']; + function rgb(ansi16: ANSI16): RGB; +} + +export namespace ansi256 { + const channels: 1; + const labels: ['ansi256']; + function rgb(ansi256: ANSI256): RGB; +} + +export namespace hcg { + const channels: 3; + const labels: ['h', 'c', 'g']; + function rgb(hcg: HCG): RGB; + function hsv(hcg: HCG): HSV; + function hsl(hcg: HCG): HSL; + function hwb(hcg: HCG): HWB; +} + +export namespace apple { + const channels: 3; + const labels: ['r16', 'g16', 'b16']; + function rgb(apple: APPLE): RGB; +} + +export namespace gray { + const channels: 1; + const labels: ['gray']; + function rgb(gray: GRAY): RGB; + function hsl(gray: GRAY): HSL; + function hsv(gray: GRAY): HSV; + function hwb(gray: GRAY): HWB; + function cmyk(gray: GRAY): CMYK; + function lab(gray: GRAY): LAB; + function hex(gray: GRAY): HEX; +} diff --git a/types/color-convert/index.d.ts b/types/color-convert/index.d.ts new file mode 100644 index 0000000000..be2a0dafa6 --- /dev/null +++ b/types/color-convert/index.d.ts @@ -0,0 +1,98 @@ +// Type definitions for color-convert 1.9 +// Project: https://github.com/qix-/color-convert#readme +// Definitions by: Junyoung Clare Jang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import conversions = require('./conversions'); +import route = require('./route'); + +export const rgb: typeof conversions.rgb & route.rgb & { + [F in keyof route.rgb]: { + raw: route.rgb[F] + } +}; + +export const hsl: typeof conversions.hsl & route.hsl & { + [F in keyof route.hsl]: { + raw: route.hsl[F] + } +}; + +export const hsv: typeof conversions.hsv & route.hsv & { + [F in keyof route.hsv]: { + raw: route.hsv[F] + } +}; + +export const hwb: typeof conversions.hwb & route.hwb & { + [F in keyof route.hwb]: { + raw: route.hwb[F] + } +}; + +export const cmyk: typeof conversions.cmyk & route.cmyk & { + [F in keyof route.cmyk]: { + raw: route.cmyk[F] + } +}; + +export const xyz: typeof conversions.xyz & route.xyz & { + [F in keyof route.xyz]: { + raw: route.xyz[F] + } +}; + +export const lab: typeof conversions.lab & route.lab & { + [F in keyof route.lab]: { + raw: route.lab[F] + } +}; + +export const lch: typeof conversions.lch & route.lch & { + [F in keyof route.lch]: { + raw: route.lch[F] + } +}; + +export const hex: typeof conversions.hex & route.hex & { + [F in keyof route.hex]: { + raw: route.hex[F] + } +}; + +export const keyword: typeof conversions.keyword & route.keyword & { + [F in keyof route.keyword]: { + raw: route.keyword[F] + } +}; + +export const ansi16: typeof conversions.ansi16 & route.ansi16 & { + [F in keyof route.ansi16]: { + raw: route.ansi16[F] + } +}; + +export const ansi256: typeof conversions.ansi256 & route.ansi256 & { + [F in keyof route.ansi256]: { + raw: route.ansi256[F] + } +}; + +export const hcg: typeof conversions.hcg & route.hcg & { + [F in keyof route.hcg]: { + raw: route.hcg[F] + } +}; + +export const apple: typeof conversions.apple & route.apple & { + [F in keyof route.apple]: { + raw: route.apple[F] + } +}; + +export const gray: typeof conversions.gray & route.gray & { + [F in keyof route.gray]: { + raw: route.gray[F] + } +}; diff --git a/types/color-convert/route.d.ts b/types/color-convert/route.d.ts new file mode 100644 index 0000000000..f9ea4f7cf8 --- /dev/null +++ b/types/color-convert/route.d.ts @@ -0,0 +1,262 @@ +import conversions = require('./conversions'); + +declare namespace route { + interface rgb { + hsl(from: conversions.RGB): conversions.HSL; + hsv(from: conversions.RGB): conversions.HSV; + hwb(from: conversions.RGB): conversions.HWB; + cmyk(from: conversions.RGB): conversions.CMYK; + xyz(from: conversions.RGB): conversions.XYZ; + lab(from: conversions.RGB): conversions.LAB; + lch(from: conversions.RGB): conversions.LCH; + hex(from: conversions.RGB): conversions.HEX; + keyword(from: conversions.RGB): conversions.KEYWORD; + ansi16(from: conversions.RGB): conversions.ANSI16; + ansi256(from: conversions.RGB): conversions.ANSI256; + hcg(from: conversions.RGB): conversions.HCG; + apple(from: conversions.RGB): conversions.APPLE; + gray(from: conversions.RGB): conversions.GRAY; + } + interface hsl { + rgb(from: conversions.HSL): conversions.RGB; + hsv(from: conversions.HSL): conversions.HSV; + hwb(from: conversions.HSL): conversions.HWB; + cmyk(from: conversions.HSL): conversions.CMYK; + xyz(from: conversions.HSL): conversions.XYZ; + lab(from: conversions.HSL): conversions.LAB; + lch(from: conversions.HSL): conversions.LCH; + hex(from: conversions.HSL): conversions.HEX; + keyword(from: conversions.HSL): conversions.KEYWORD; + ansi16(from: conversions.HSL): conversions.ANSI16; + ansi256(from: conversions.HSL): conversions.ANSI256; + hcg(from: conversions.HSL): conversions.HCG; + apple(from: conversions.HSL): conversions.APPLE; + gray(from: conversions.HSL): conversions.GRAY; + } + interface hsv { + rgb(from: conversions.HSV): conversions.RGB; + hsl(from: conversions.HSV): conversions.HSL; + hwb(from: conversions.HSV): conversions.HWB; + cmyk(from: conversions.HSV): conversions.CMYK; + xyz(from: conversions.HSV): conversions.XYZ; + lab(from: conversions.HSV): conversions.LAB; + lch(from: conversions.HSV): conversions.LCH; + hex(from: conversions.HSV): conversions.HEX; + keyword(from: conversions.HSV): conversions.KEYWORD; + ansi16(from: conversions.HSV): conversions.ANSI16; + ansi256(from: conversions.HSV): conversions.ANSI256; + hcg(from: conversions.HSV): conversions.HCG; + apple(from: conversions.HSV): conversions.APPLE; + gray(from: conversions.HSV): conversions.GRAY; + } + interface hwb { + rgb(from: conversions.HWB): conversions.RGB; + hsl(from: conversions.HWB): conversions.HSL; + hsv(from: conversions.HWB): conversions.HSV; + cmyk(from: conversions.HWB): conversions.CMYK; + xyz(from: conversions.HWB): conversions.XYZ; + lab(from: conversions.HWB): conversions.LAB; + lch(from: conversions.HWB): conversions.LCH; + hex(from: conversions.HWB): conversions.HEX; + keyword(from: conversions.HWB): conversions.KEYWORD; + ansi16(from: conversions.HWB): conversions.ANSI16; + ansi256(from: conversions.HWB): conversions.ANSI256; + hcg(from: conversions.HWB): conversions.HCG; + apple(from: conversions.HWB): conversions.APPLE; + gray(from: conversions.HWB): conversions.GRAY; + } + interface cmyk { + rgb(from: conversions.CMYK): conversions.RGB; + hsl(from: conversions.CMYK): conversions.HSL; + hsv(from: conversions.CMYK): conversions.HSV; + hwb(from: conversions.CMYK): conversions.HWB; + xyz(from: conversions.CMYK): conversions.XYZ; + lab(from: conversions.CMYK): conversions.LAB; + lch(from: conversions.CMYK): conversions.LCH; + hex(from: conversions.CMYK): conversions.HEX; + keyword(from: conversions.CMYK): conversions.KEYWORD; + ansi16(from: conversions.CMYK): conversions.ANSI16; + ansi256(from: conversions.CMYK): conversions.ANSI256; + hcg(from: conversions.CMYK): conversions.HCG; + apple(from: conversions.CMYK): conversions.APPLE; + gray(from: conversions.CMYK): conversions.GRAY; + } + interface xyz { + rgb(from: conversions.XYZ): conversions.RGB; + hsl(from: conversions.XYZ): conversions.HSL; + hsv(from: conversions.XYZ): conversions.HSV; + hwb(from: conversions.XYZ): conversions.HWB; + cmyk(from: conversions.XYZ): conversions.CMYK; + lab(from: conversions.XYZ): conversions.LAB; + lch(from: conversions.XYZ): conversions.LCH; + hex(from: conversions.XYZ): conversions.HEX; + keyword(from: conversions.XYZ): conversions.KEYWORD; + ansi16(from: conversions.XYZ): conversions.ANSI16; + ansi256(from: conversions.XYZ): conversions.ANSI256; + hcg(from: conversions.XYZ): conversions.HCG; + apple(from: conversions.XYZ): conversions.APPLE; + gray(from: conversions.XYZ): conversions.GRAY; + } + interface lab { + rgb(from: conversions.LAB): conversions.RGB; + hsl(from: conversions.LAB): conversions.HSL; + hsv(from: conversions.LAB): conversions.HSV; + hwb(from: conversions.LAB): conversions.HWB; + cmyk(from: conversions.LAB): conversions.CMYK; + xyz(from: conversions.LAB): conversions.XYZ; + lch(from: conversions.LAB): conversions.LCH; + hex(from: conversions.LAB): conversions.HEX; + keyword(from: conversions.LAB): conversions.KEYWORD; + ansi16(from: conversions.LAB): conversions.ANSI16; + ansi256(from: conversions.LAB): conversions.ANSI256; + hcg(from: conversions.LAB): conversions.HCG; + apple(from: conversions.LAB): conversions.APPLE; + gray(from: conversions.LAB): conversions.GRAY; + } + interface lch { + rgb(from: conversions.LCH): conversions.RGB; + hsl(from: conversions.LCH): conversions.HSL; + hsv(from: conversions.LCH): conversions.HSV; + hwb(from: conversions.LCH): conversions.HWB; + cmyk(from: conversions.LCH): conversions.CMYK; + xyz(from: conversions.LCH): conversions.XYZ; + lab(from: conversions.LCH): conversions.LAB; + hex(from: conversions.LCH): conversions.HEX; + keyword(from: conversions.LCH): conversions.KEYWORD; + ansi16(from: conversions.LCH): conversions.ANSI16; + ansi256(from: conversions.LCH): conversions.ANSI256; + hcg(from: conversions.LCH): conversions.HCG; + apple(from: conversions.LCH): conversions.APPLE; + gray(from: conversions.LCH): conversions.GRAY; + } + interface hex { + rgb(from: conversions.HEX): conversions.RGB; + hsl(from: conversions.HEX): conversions.HSL; + hsv(from: conversions.HEX): conversions.HSV; + hwb(from: conversions.HEX): conversions.HWB; + cmyk(from: conversions.HEX): conversions.CMYK; + xyz(from: conversions.HEX): conversions.XYZ; + lab(from: conversions.HEX): conversions.LAB; + lch(from: conversions.HEX): conversions.LCH; + keyword(from: conversions.HEX): conversions.KEYWORD; + ansi16(from: conversions.HEX): conversions.ANSI16; + ansi256(from: conversions.HEX): conversions.ANSI256; + hcg(from: conversions.HEX): conversions.HCG; + apple(from: conversions.HEX): conversions.APPLE; + gray(from: conversions.HEX): conversions.GRAY; + } + interface keyword { + rgb(from: conversions.KEYWORD): conversions.RGB; + hsl(from: conversions.KEYWORD): conversions.HSL; + hsv(from: conversions.KEYWORD): conversions.HSV; + hwb(from: conversions.KEYWORD): conversions.HWB; + cmyk(from: conversions.KEYWORD): conversions.CMYK; + xyz(from: conversions.KEYWORD): conversions.XYZ; + lab(from: conversions.KEYWORD): conversions.LAB; + lch(from: conversions.KEYWORD): conversions.LCH; + hex(from: conversions.KEYWORD): conversions.HEX; + ansi16(from: conversions.KEYWORD): conversions.ANSI16; + ansi256(from: conversions.KEYWORD): conversions.ANSI256; + hcg(from: conversions.KEYWORD): conversions.HCG; + apple(from: conversions.KEYWORD): conversions.APPLE; + gray(from: conversions.KEYWORD): conversions.GRAY; + } + interface ansi16 { + rgb(from: conversions.ANSI16): conversions.RGB; + hsl(from: conversions.ANSI16): conversions.HSL; + hsv(from: conversions.ANSI16): conversions.HSV; + hwb(from: conversions.ANSI16): conversions.HWB; + cmyk(from: conversions.ANSI16): conversions.CMYK; + xyz(from: conversions.ANSI16): conversions.XYZ; + lab(from: conversions.ANSI16): conversions.LAB; + lch(from: conversions.ANSI16): conversions.LCH; + hex(from: conversions.ANSI16): conversions.HEX; + keyword(from: conversions.ANSI16): conversions.KEYWORD; + ansi256(from: conversions.ANSI16): conversions.ANSI256; + hcg(from: conversions.ANSI16): conversions.HCG; + apple(from: conversions.ANSI16): conversions.APPLE; + gray(from: conversions.ANSI16): conversions.GRAY; + } + interface ansi256 { + rgb(from: conversions.ANSI256): conversions.RGB; + hsl(from: conversions.ANSI256): conversions.HSL; + hsv(from: conversions.ANSI256): conversions.HSV; + hwb(from: conversions.ANSI256): conversions.HWB; + cmyk(from: conversions.ANSI256): conversions.CMYK; + xyz(from: conversions.ANSI256): conversions.XYZ; + lab(from: conversions.ANSI256): conversions.LAB; + lch(from: conversions.ANSI256): conversions.LCH; + hex(from: conversions.ANSI256): conversions.HEX; + keyword(from: conversions.ANSI256): conversions.KEYWORD; + ansi16(from: conversions.ANSI256): conversions.ANSI16; + hcg(from: conversions.ANSI256): conversions.HCG; + apple(from: conversions.ANSI256): conversions.APPLE; + gray(from: conversions.ANSI256): conversions.GRAY; + } + interface hcg { + rgb(from: conversions.HCG): conversions.RGB; + hsl(from: conversions.HCG): conversions.HSL; + hsv(from: conversions.HCG): conversions.HSV; + hwb(from: conversions.HCG): conversions.HWB; + cmyk(from: conversions.HCG): conversions.CMYK; + xyz(from: conversions.HCG): conversions.XYZ; + lab(from: conversions.HCG): conversions.LAB; + lch(from: conversions.HCG): conversions.LCH; + hex(from: conversions.HCG): conversions.HEX; + keyword(from: conversions.HCG): conversions.KEYWORD; + ansi16(from: conversions.HCG): conversions.ANSI16; + ansi256(from: conversions.HCG): conversions.ANSI256; + apple(from: conversions.HCG): conversions.APPLE; + gray(from: conversions.HCG): conversions.GRAY; + } + interface apple { + rgb(from: conversions.APPLE): conversions.RGB; + hsl(from: conversions.APPLE): conversions.HSL; + hsv(from: conversions.APPLE): conversions.HSV; + hwb(from: conversions.APPLE): conversions.HWB; + cmyk(from: conversions.APPLE): conversions.CMYK; + xyz(from: conversions.APPLE): conversions.XYZ; + lab(from: conversions.APPLE): conversions.LAB; + lch(from: conversions.APPLE): conversions.LCH; + hex(from: conversions.APPLE): conversions.HEX; + keyword(from: conversions.APPLE): conversions.KEYWORD; + ansi16(from: conversions.APPLE): conversions.ANSI16; + ansi256(from: conversions.APPLE): conversions.ANSI256; + hcg(from: conversions.APPLE): conversions.HCG; + gray(from: conversions.APPLE): conversions.GRAY; + } + interface gray { + rgb(from: conversions.GRAY): conversions.RGB; + hsl(from: conversions.GRAY): conversions.HSL; + hsv(from: conversions.GRAY): conversions.HSV; + hwb(from: conversions.GRAY): conversions.HWB; + cmyk(from: conversions.GRAY): conversions.CMYK; + xyz(from: conversions.GRAY): conversions.XYZ; + lab(from: conversions.GRAY): conversions.LAB; + lch(from: conversions.GRAY): conversions.LCH; + hex(from: conversions.GRAY): conversions.HEX; + keyword(from: conversions.GRAY): conversions.KEYWORD; + ansi16(from: conversions.GRAY): conversions.ANSI16; + ansi256(from: conversions.GRAY): conversions.ANSI256; + hcg(from: conversions.GRAY): conversions.HCG; + apple(from: conversions.GRAY): conversions.APPLE; + } +} + +declare function route(fromModel: 'rgb'): route.rgb; +declare function route(fromModel: 'hsl'): route.hsl; +declare function route(fromModel: 'hsv'): route.hsv; +declare function route(fromModel: 'hwb'): route.hwb; +declare function route(fromModel: 'cmyk'): route.cmyk; +declare function route(fromModel: 'xyz'): route.xyz; +declare function route(fromModel: 'lab'): route.lab; +declare function route(fromModel: 'lch'): route.lch; +declare function route(fromModel: 'hex'): route.hex; +declare function route(fromModel: 'keyword'): route.keyword; +declare function route(fromModel: 'ansi16'): route.ansi16; +declare function route(fromModel: 'ansi256'): route.ansi256; +declare function route(fromModel: 'hcg'): route.hcg; +declare function route(fromModel: 'apple'): route.apple; +declare function route(fromModel: 'gray'): route.gray; + +export = route; diff --git a/types/color-convert/tsconfig.json b/types/color-convert/tsconfig.json new file mode 100644 index 0000000000..70b4bd0fd9 --- /dev/null +++ b/types/color-convert/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "conversions.d.ts", + "route.d.ts", + "color-convert-tests.ts" + ] +} diff --git a/types/color-convert/tslint.json b/types/color-convert/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color-convert/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/color-name/color-name-tests.ts b/types/color-name/color-name-tests.ts new file mode 100644 index 0000000000..5d8998c97a --- /dev/null +++ b/types/color-name/color-name-tests.ts @@ -0,0 +1,5 @@ +import * as colorname from 'color-name'; + +let color: [number, number, number] = colorname.aliceblue; +color = colorname.darkkhaki; +color = colorname.gainsboro; diff --git a/types/color-name/index.d.ts b/types/color-name/index.d.ts new file mode 100644 index 0000000000..65b4ecc8fb --- /dev/null +++ b/types/color-name/index.d.ts @@ -0,0 +1,161 @@ +// Type definitions for color-name 1.1 +// Project: https://www.npmjs.com/package/color-name +// Definitions by: Junyoung Clare Jang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Tuple of Red, Green, and Blue + * @example + * // Red = 55, Green = 70, Blue = 0 + * const rgb: RGB = [55, 70, 0]; + */ +export type RGB = [number, number, number]; + +export const aliceblue: RGB; +export const antiquewhite: RGB; +export const aqua: RGB; +export const aquamarine: RGB; +export const azure: RGB; +export const beige: RGB; +export const bisque: RGB; +export const black: RGB; +export const blanchedalmond: RGB; +export const blue: RGB; +export const blueviolet: RGB; +export const brown: RGB; +export const burlywood: RGB; +export const cadetblue: RGB; +export const chartreuse: RGB; +export const chocolate: RGB; +export const coral: RGB; +export const cornflowerblue: RGB; +export const cornsilk: RGB; +export const crimson: RGB; +export const cyan: RGB; +export const darkblue: RGB; +export const darkcyan: RGB; +export const darkgoldenrod: RGB; +export const darkgray: RGB; +export const darkgreen: RGB; +export const darkgrey: RGB; +export const darkkhaki: RGB; +export const darkmagenta: RGB; +export const darkolivegreen: RGB; +export const darkorange: RGB; +export const darkorchid: RGB; +export const darkred: RGB; +export const darksalmon: RGB; +export const darkseagreen: RGB; +export const darkslateblue: RGB; +export const darkslategray: RGB; +export const darkslategrey: RGB; +export const darkturquoise: RGB; +export const darkviolet: RGB; +export const deeppink: RGB; +export const deepskyblue: RGB; +export const dimgray: RGB; +export const dimgrey: RGB; +export const dodgerblue: RGB; +export const firebrick: RGB; +export const floralwhite: RGB; +export const forestgreen: RGB; +export const fuchsia: RGB; +export const gainsboro: RGB; +export const ghostwhite: RGB; +export const gold: RGB; +export const goldenrod: RGB; +export const gray: RGB; +export const green: RGB; +export const greenyellow: RGB; +export const grey: RGB; +export const honeydew: RGB; +export const hotpink: RGB; +export const indianred: RGB; +export const indigo: RGB; +export const ivory: RGB; +export const khaki: RGB; +export const lavender: RGB; +export const lavenderblush: RGB; +export const lawngreen: RGB; +export const lemonchiffon: RGB; +export const lightblue: RGB; +export const lightcoral: RGB; +export const lightcyan: RGB; +export const lightgoldenrodyellow: RGB; +export const lightgray: RGB; +export const lightgreen: RGB; +export const lightgrey: RGB; +export const lightpink: RGB; +export const lightsalmon: RGB; +export const lightseagreen: RGB; +export const lightskyblue: RGB; +export const lightslategray: RGB; +export const lightslategrey: RGB; +export const lightsteelblue: RGB; +export const lightyellow: RGB; +export const lime: RGB; +export const limegreen: RGB; +export const linen: RGB; +export const magenta: RGB; +export const maroon: RGB; +export const mediumaquamarine: RGB; +export const mediumblue: RGB; +export const mediumorchid: RGB; +export const mediumpurple: RGB; +export const mediumseagreen: RGB; +export const mediumslateblue: RGB; +export const mediumspringgreen: RGB; +export const mediumturquoise: RGB; +export const mediumvioletred: RGB; +export const midnightblue: RGB; +export const mintcream: RGB; +export const mistyrose: RGB; +export const moccasin: RGB; +export const navajowhite: RGB; +export const navy: RGB; +export const oldlace: RGB; +export const olive: RGB; +export const olivedrab: RGB; +export const orange: RGB; +export const orangered: RGB; +export const orchid: RGB; +export const palegoldenrod: RGB; +export const palegreen: RGB; +export const paleturquoise: RGB; +export const palevioletred: RGB; +export const papayawhip: RGB; +export const peachpuff: RGB; +export const peru: RGB; +export const pink: RGB; +export const plum: RGB; +export const powderblue: RGB; +export const purple: RGB; +export const rebeccapurple: RGB; +export const red: RGB; +export const rosybrown: RGB; +export const royalblue: RGB; +export const saddlebrown: RGB; +export const salmon: RGB; +export const sandybrown: RGB; +export const seagreen: RGB; +export const seashell: RGB; +export const sienna: RGB; +export const silver: RGB; +export const skyblue: RGB; +export const slateblue: RGB; +export const slategray: RGB; +export const slategrey: RGB; +export const snow: RGB; +export const springgreen: RGB; +export const steelblue: RGB; +export const tan: RGB; +export const teal: RGB; +export const thistle: RGB; +export const tomato: RGB; +export const turquoise: RGB; +export const violet: RGB; +export const wheat: RGB; +export const white: RGB; +export const whitesmoke: RGB; +export const yellow: RGB; +export const yellowgreen: RGB; diff --git a/types/color-name/tsconfig.json b/types/color-name/tsconfig.json new file mode 100644 index 0000000000..30cfb50814 --- /dev/null +++ b/types/color-name/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "baseUrl": "../", + "forceConsistentCasingInFileNames": true, + "lib": [ + "es6" + ], + "module": "commonjs", + "noEmit": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "types": [], + "typeRoots": ["../"] + }, + "files": [ + "index.d.ts", + "color-name-tests.ts" + ] +} diff --git a/types/color-name/tslint.json b/types/color-name/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color-name/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/color-string/color-string-tests.ts b/types/color-string/color-string-tests.ts new file mode 100644 index 0000000000..3f084fbc25 --- /dev/null +++ b/types/color-string/color-string-tests.ts @@ -0,0 +1,38 @@ +import * as colorString from 'color-string'; + +let colorDescriptor: colorString.ColorDescriptor | null; +colorDescriptor = colorString.get('#FFF'); +colorDescriptor = colorString.get('#FFFA'); +colorDescriptor = colorString.get('#FFFFFFAA'); +colorDescriptor = colorString.get('hsl(360, 100%, 50%)'); +colorDescriptor = colorString.get('hwb(60, 3%, 60%)'); + +let color: colorString.Color | null; +color = colorString.get.rgb('#FFF'); +color = colorString.get.rgb('blue'); +color = colorString.get.rgb('rgba(200, 60, 60, 0.3)'); +color = colorString.get.rgb('rgb(200, 200, 200)'); + +color = colorString.get.hsl('hsl(360, 100%, 50%)'); +color = colorString.get.hsl('hsla(360, 60%, 50%, 0.4)'); +color = colorString.get.hwb('hwb(60, 3%, 60%)'); + +color = colorString.get.hwb('hwb(60, 3%, 60%, 0.6)'); + +color = colorString.get.rgb('invalid color string'); + +let stringifiedColor: string; +stringifiedColor = colorString.to.hex([255, 255, 255]); +stringifiedColor = colorString.to.hex([0, 0, 255, 0.4]); +stringifiedColor = colorString.to.hex([0, 0, 255], 0.4); +stringifiedColor = colorString.to.rgb([255, 255, 255]); +stringifiedColor = colorString.to.rgb([0, 0, 255, 0.4]); +stringifiedColor = colorString.to.rgb([0, 0, 255], 0.4); +stringifiedColor = colorString.to.rgb.percent([0, 0, 255]); +stringifiedColor = colorString.to.keyword([255, 255, 0]); +stringifiedColor = colorString.to.hsl([360, 100, 100]); +stringifiedColor = colorString.to.hwb([50, 3, 15]); + +stringifiedColor = colorString.to.rgb(0, [0, 255], 0.4); +stringifiedColor = colorString.to.rgb([0, 0], [255], 0.4); +stringifiedColor = colorString.to.rgb([0], 0, [255, 0.4]); diff --git a/types/color-string/index.d.ts b/types/color-string/index.d.ts new file mode 100644 index 0000000000..4eda883297 --- /dev/null +++ b/types/color-string/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for color-string 1.5 +// Project: https://github.com/qix-/color-string#readme +// Definitions by: BendingBender +// Dan Marshall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Color = [number, number, number, number]; + +export interface ColorDescriptor { + model: 'rgb' | 'hsl' | 'hwb'; + value: Color; +} + +export function get(colorString: string): ColorDescriptor | null; + +export namespace get { + function hsl(colorString: string): Color | null; + function hwb(colorString: string): Color | null; + function rgb(colorString: string): Color | null; +} + +export namespace to { + function hex(...args: Array): string; + function rgb(...args: Array): string; + namespace rgb { + function percent(...args: Array): string; + } + function keyword(...args: Array): string; + function hsl(...args: Array): string; + function hwb(...args: Array): string; +} diff --git a/types/color-string/tsconfig.json b/types/color-string/tsconfig.json new file mode 100644 index 0000000000..bf5a829c6e --- /dev/null +++ b/types/color-string/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", + "color-string-tests.ts" + ] +} diff --git a/types/color-string/tslint.json b/types/color-string/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color-string/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/connect-timeout/index.d.ts b/types/connect-timeout/index.d.ts index bfaa7c473d..0ec4963306 100644 --- a/types/connect-timeout/index.d.ts +++ b/types/connect-timeout/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/expressjs/timeout // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/consul/index.d.ts b/types/consul/index.d.ts index 4d577cd2a1..3d344ae983 100644 --- a/types/consul/index.d.ts +++ b/types/consul/index.d.ts @@ -7,7 +7,7 @@ -import {IncomingMessage as HttpIncomingMessage} from "http"; +import { IncomingMessage as HttpIncomingMessage } from "http"; declare namespace Consul { diff --git a/types/cookie-parser/cookie-parser-tests.ts b/types/cookie-parser/cookie-parser-tests.ts index 1f9aaa1a8b..3a9f885efd 100644 --- a/types/cookie-parser/cookie-parser-tests.ts +++ b/types/cookie-parser/cookie-parser-tests.ts @@ -1,6 +1,31 @@ - import express = require('express'); import cookieParser = require('cookie-parser'); -var app = express(); +const app = express(); app.use(cookieParser('optional secret string')); + +let obj: object; +let str: string; +let notTrue: false; +let undef: undefined; + +const res = cookieParser.JSONCookie('foo'); +if (typeof res === 'undefined') { + undef = res; +} else { + obj = res; +} + +const res2 = cookieParser.JSONCookies({foo: 'bar'}); +const jsonRes: { foo?: object } = res2; + +const res3 = cookieParser.signedCookie('', 'keyboard cat'); +cookieParser.signedCookie('', ['keyboard', 'cat']); +if (typeof res3 === 'string') { + str = res3; +} else { + notTrue = res3; +} + +const res4 = cookieParser.signedCookies({foo: 'bar'}, 'keyboard cat'); +const signedCookieRes: { foo?: string | false } = res4; diff --git a/types/cookie-parser/index.d.ts b/types/cookie-parser/index.d.ts index 96412d6ee9..b2520080b0 100644 --- a/types/cookie-parser/index.d.ts +++ b/types/cookie-parser/index.d.ts @@ -1,12 +1,26 @@ -// Type definitions for cookie-parser v1.3.4 +// Type definitions for cookie-parser 1.4 // Project: https://github.com/expressjs/cookie-parser // Definitions by: Santi Albo +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +import * as express from 'express'; +declare function cookieParser(secret?: string | string[], options?: cookieParser.CookieParseOptions): express.RequestHandler; +declare namespace cookieParser { + interface CookieParseOptions { + decode?(val: string): string; + } -import express = require('express'); -declare function e(secret?: string, options?: any): express.RequestHandler; -declare namespace e { } -export = e; + function JSONCookie(jsonCookie: string): object | undefined; + + function JSONCookies(jsonCookies: T): { [P in keyof T]: object | undefined }; + + function signedCookie(cookie: string, secret: string | string[]): string | false; + + function signedCookies(cookies: T, secret: string | string[]): { [P in keyof T]?: string | false}; +} + +export = cookieParser; diff --git a/types/cookie-parser/tslint.json b/types/cookie-parser/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cookie-parser/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cookie/cookie-tests.ts b/types/cookie/cookie-tests.ts index dd5be0f850..08e4d43519 100644 --- a/types/cookie/cookie-tests.ts +++ b/types/cookie/cookie-tests.ts @@ -1,23 +1,21 @@ - - import cookie = require('cookie'); function test_serialize(): void { - var retVal: string; + let retVal: string; retVal = cookie.serialize('foo', 'bar'); retVal = cookie.serialize('foo', 'bar', { httpOnly: true }); } function test_parse(): void { - var retVal: { [key: string]: string }; + let retVal: { [key: string]: string }; retVal = cookie.parse('foo=bar; bar=baz;'); retVal = cookie.parse('foo=bar; bar=baz', { decode: x => x }); } function test_options(): void { - var serializeOptions: cookie.CookieSerializeOptions = { + const serializeOptions: cookie.CookieSerializeOptions = { encode: (x: string) => x, path: '/', expires: new Date(), @@ -27,7 +25,7 @@ function test_options(): void { httpOnly: false }; - var parseOptios: cookie.CookieParseOptions = { + const parseOptios: cookie.CookieParseOptions = { decode: (x: string) => x }; } diff --git a/types/cookie/index.d.ts b/types/cookie/index.d.ts index 507eaee01d..bb7fc2cb54 100644 --- a/types/cookie/index.d.ts +++ b/types/cookie/index.d.ts @@ -1,15 +1,16 @@ -// Type definitions for cookie v0.3.0 +// Type definitions for cookie 0.3 // Project: https://github.com/jshttp/cookie // Definitions by: Pine Mizune // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface CookieSerializeOptions { +export interface CookieSerializeOptions { /** * Specifies the value for the Domain Set-Cookie attribute. By default, no * domain is set, and most clients will consider the cookie to apply to only * the current domain. */ domain?: string; + /** * Specifies a function that will be used to encode a cookie's value. Since * value of a cookie has a limited character set (and must be a simple @@ -20,7 +21,8 @@ interface CookieSerializeOptions { * encode a JavaScript string into UTF-8 byte sequences and then URL-encode * any that fall outside of the cookie range. */ - encode?: (val: string) => string; + encode?(val: string): string; + /** * Specifies the `Date` object to be the value for the `Expires` * `Set-Cookie` attribute. By default, no expiration is set, and most @@ -83,7 +85,7 @@ interface CookieSerializeOptions { secure?: boolean; } -interface CookieParseOptions { +export interface CookieParseOptions { /** * Specifies a function that will be used to decode a cookie's value. Since * the value of a cookie has a limited character set (and must be a simple @@ -96,7 +98,7 @@ interface CookieParseOptions { * *Note* if an error is thrown from this function, the original, non-decoded * cookie value will be returned as the cookie's value. */ - decode?: (val: string) => string; + decode?(val: string): string; } /** diff --git a/types/cookie/tslint.json b/types/cookie/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cookie/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cucumber/cucumber-tests.ts b/types/cucumber/cucumber-tests.ts index 53ca726230..e0ecc2bed9 100644 --- a/types/cucumber/cucumber-tests.ts +++ b/types/cucumber/cucumber-tests.ts @@ -62,7 +62,7 @@ function StepSample() { }); Then(/^I should see "(.*)" as the page title$/, {timeout: 60 * 1000}, function (title: string, callback: Callback) { - var pageTitle = this.browser.text('title'); + const pageTitle = this.browser.text('title'); if (title === pageTitle) { callback(); @@ -75,38 +75,41 @@ function StepSample() { // https://github.com/cucumber/cucumber-js/blob/a5fd8251918c278ab2e389226d165cedb44df14a/lib/cucumber/ast/data_table.js Given(/^a table step with Table raw$/, function (table: Table) { - var expected = [ + const expected = [ ['Cucumber', 'Cucumis sativus'], ['Burr Gherkin', 'Cucumis anguria'] ]; - - assert.deepEqual(table.raw(), expected); + const actual: string[][] = table.raw(); + assert.deepEqual(actual, expected); }); Given(/^a table step with Table rows$/, function (table: Table) { - var expected = [ + const expected = [ ['Apricot', '5'], ['Brocolli', '2'], ['Cucumber', '10'] ]; - assert.deepEqual(table.rows(), expected) + const actual: string[][] = table.rows(); + assert.deepEqual(actual, expected); }); Given(/^a table step with Table rowHash$/, function (table: Table) { - var expected = { + const expected = { 'Cucumber': 'Cucumis sativus', 'Burr Gherkin': 'Cucumis anguria' }; - assert.deepEqual(table.rowsHash(), expected) + const actual: { [firstCol:string]: string } = table.rowsHash(); + assert.deepEqual(actual, expected); }); Given(/^a table step$/, function (table: Table) { - var expected = [ + const expected = [ {'Vegetable': 'Apricot', 'Rating': '5'}, {'Vegetable': 'Brocolli', 'Rating': '2'}, {'Vegetable': 'Cucumber', 'Rating': '10'} ]; - assert.deepEqual(table.hashes(), expected) + const actual: { [colName:string]: string }[] = table.hashes(); + assert.deepEqual(actual, expected); }); defineParameterType({ diff --git a/types/cucumber/index.d.ts b/types/cucumber/index.d.ts index 60e3d27d5d..635a594ae5 100644 --- a/types/cucumber/index.d.ts +++ b/types/cucumber/index.d.ts @@ -13,10 +13,10 @@ declare namespace cucumber { } export interface TableDefinition { - raw: () => Array; - rows: () => Array; - rowsHash: () => {}; - hashes: () => {}; + raw: () => Array>; + rows: () => Array>; + rowsHash: () => { [firstCol:string]: string }; + hashes: () => Array<{ [colName:string]: string }>; } type StepDefinitionParam = string | number | CallbackStepDefinition | TableDefinition; diff --git a/types/cucumber/v1/cucumber-tests.ts b/types/cucumber/v1/cucumber-tests.ts index 596772274f..347bec135b 100644 --- a/types/cucumber/v1/cucumber-tests.ts +++ b/types/cucumber/v1/cucumber-tests.ts @@ -5,17 +5,17 @@ function StepSample() { type Callback = cucumber.CallbackStepDefinition; type Table = cucumber.TableDefinition; type HookScenario = cucumber.HookScenario; - var step = this; - var hook = this; + const step = this; + const hook = this; hook.Before(function (scenario: HookScenario, callback: Callback) { scenario.isFailed() && callback.pending(); }); - + hook.Before({ timeout: 1000 }, function(scenario: HookScenario, callback: Callback) { callback(); }); - + hook.After({ timeout: 1000 }, function(scenario: HookScenario, callback: Callback) { callback(); }); @@ -39,7 +39,7 @@ function StepSample() { }); step.Then(/^I should see "(.*)" as the page title$/, {timeout: 60 * 1000}, function (title: string, callback: Callback) { - var pageTitle = this.browser.text('title'); + const pageTitle = this.browser.text('title'); if (title === pageTitle) { callback(); @@ -52,38 +52,41 @@ function StepSample() { // https://github.com/cucumber/cucumber-js/blob/a5fd8251918c278ab2e389226d165cedb44df14a/lib/cucumber/ast/data_table.js step.Given(/^a table step with Table raw$/, function (table: Table) { - var expected = [ + const expected = [ ['Cucumber', 'Cucumis sativus'], ['Burr Gherkin', 'Cucumis anguria'] ]; - - assert.deepEqual(table.raw(), expected); + const actual: string[][] = table.raw(); + assert.deepEqual(actual, expected); }); step.Given(/^a table step with Table rows$/, function (table: Table) { - var expected = [ + const expected = [ ['Apricot', '5'], ['Brocolli', '2'], ['Cucumber', '10'] ]; - assert.deepEqual(table.rows(), expected) + const actual: string[][] = table.rows(); + assert.deepEqual(actual, expected); }); step.Given(/^a table step with Table rowHash$/, function (table: Table) { - var expected = { + const expected = { 'Cucumber': 'Cucumis sativus', 'Burr Gherkin': 'Cucumis anguria' }; - assert.deepEqual(table.rowsHash(), expected) + const actual: { [firstCol:string]: string } = table.rowsHash(); + assert.deepEqual(actual, expected); }); step.Given(/^a table step$/, function (table: Table) { - var expected = [ + const expected = [ {'Vegetable': 'Apricot', 'Rating': '5'}, {'Vegetable': 'Brocolli', 'Rating': '2'}, {'Vegetable': 'Cucumber', 'Rating': '10'} ]; - assert.deepEqual(table.hashes(), expected) + const actual: { [colName:string]: string }[] = table.hashes(); + assert.deepEqual(actual, expected); }); } diff --git a/types/cucumber/v1/index.d.ts b/types/cucumber/v1/index.d.ts index bdf30d740d..39a915f935 100644 --- a/types/cucumber/v1/index.d.ts +++ b/types/cucumber/v1/index.d.ts @@ -13,10 +13,10 @@ declare namespace cucumber { } export interface TableDefinition { - raw: () => Array; - rows: () => Array; - rowsHash: () => {}; - hashes: () => {}; + raw: () => Array>; + rows: () => Array>; + rowsHash: () => { [firstCol:string]: string }; + hashes: () => Array<{ [colName:string]: string }>; } type StepDefinitionParam = string | CallbackStepDefinition | TableDefinition; diff --git a/types/d3-axis/index.d.ts b/types/d3-axis/index.d.ts index 9cee537067..1c7820c809 100644 --- a/types/d3-axis/index.d.ts +++ b/types/d3-axis/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.0.4 +// Last module patch version validated against: 1.0.8 import { Selection, TransitionLike } from 'd3-selection'; @@ -82,6 +82,10 @@ export interface Axis { /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * + * This method is also a convenience function for axis.tickArguments. + * * @param count Number of ticks that should be rendered * @param specifier An optional format specifier to customize how the tick values are formatted. */ @@ -91,6 +95,8 @@ export interface Axis { * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * Use with a TIME SCALE ONLY. * + * This method is also a convenience function for axis.tickArguments. + * * @param interval A time interval used to generate date-based ticks. This is typically a TimeInterval/CountableTimeInterval as defined * in d3-time. E.g. as obtained by passing in d3.timeMinute.every(15). * @param specifier An optional format specifier to customize how the tick values are formatted. @@ -99,17 +105,31 @@ export interface Axis { /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. + * + * The meaning of the arguments depends on the axis’ scale type: most commonly, the arguments are a suggested count for the number of ticks + * (or a time interval for time scales), and an optional format specifier to customize how the tick values are formatted. + * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * This method is also a convenience function for axis.tickArguments. */ ticks(arg0: any, ...args: any[]): this; /** - * Get an array containing the currently set arguments to be passed into scale.ticks and scale.tickFormat. + * Get an array containing the currently set arguments to be passed into scale.ticks and scale.tickFormat, which defaults to the empty array. */ tickArguments(): any[]; /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * See also axis.ticks. + * * @param args An array containing a single element representing the count, i.e. number of ticks to be rendered. */ tickArguments(args: [number]): this; @@ -117,6 +137,11 @@ export interface Axis { /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * See also axis.ticks. + * * @param args An array containing two elements. The first element represents the count, i.e. number of ticks to be rendered. The second * element is a string representing the format specifier to customize how the tick values are formatted. */ @@ -126,6 +151,8 @@ export interface Axis { * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * Use with a TIME SCALE ONLY. * + * See also axis.ticks. + * * @param args An array containing a single element representing a time interval used to generate date-based ticks. * This is typically a TimeInterval/CountableTimeInterval as defined in d3-time. E.g. as obtained by passing in d3.timeMinute.every(15). */ @@ -135,6 +162,8 @@ export interface Axis { * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * Use with a TIME SCALE ONLY. * + * See also axis.ticks. + * * @param args An array containing two elements. The first element represents a time interval used to generate date-based ticks. * This is typically a TimeInterval/CountableTimeInterval as defined in d3-time. E.g. as obtained by passing in d3.timeMinute.every(15). * The second element is a string representing the format specifier to customize how the tick values are formatted. @@ -144,6 +173,11 @@ export interface Axis { /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * See also axis.ticks. + * * @param args An array with arguments suitable for the scale to be used for tick generation */ tickArguments(args: any[]): this; diff --git a/types/d3-hsv/d3-hsv-tests.ts b/types/d3-hsv/d3-hsv-tests.ts index 72e18145e6..0d3e564360 100644 --- a/types/d3-hsv/d3-hsv-tests.ts +++ b/types/d3-hsv/d3-hsv-tests.ts @@ -6,8 +6,8 @@ * are not intended as functional tests. */ -import {hsv, HSVColor} from 'd3-hsv'; -import {rgb, RGBColor} from 'd3-color'; +import { hsv, HSVColor } from 'd3-hsv'; +import { rgb, RGBColor } from 'd3-color'; let c: RGBColor; let cHSV: HSVColor; diff --git a/types/d3-hsv/index.d.ts b/types/d3-hsv/index.d.ts index c10fa6ee44..6a7a2c8560 100644 --- a/types/d3-hsv/index.d.ts +++ b/types/d3-hsv/index.d.ts @@ -5,7 +5,7 @@ // Last module patch version validated against: 0.0.3 -import {Color, RGBColor, ColorSpaceObject, ColorCommonInstance} from 'd3-color'; +import { Color, RGBColor, ColorSpaceObject, ColorCommonInstance } from 'd3-color'; export type ColorSpaceObjectWithHSV = ColorSpaceObject | HSVColor; diff --git a/types/d3-selection-multi/index.d.ts b/types/d3-selection-multi/index.d.ts index da3c64e5e3..4dd2a47c46 100644 --- a/types/d3-selection-multi/index.d.ts +++ b/types/d3-selection-multi/index.d.ts @@ -5,8 +5,8 @@ // Last module patch version validated against: 1.0.0 -import {Selection, BaseType, ArrayLike, ValueFn} from 'd3-selection'; -import {Transition} from 'd3-transition'; +import { Selection, BaseType, ArrayLike, ValueFn } from 'd3-selection'; +import { Transition } from 'd3-transition'; /** * An object mapping attribute (or style or property) names to value accessors diff --git a/types/d3-shape/d3-shape-tests.ts b/types/d3-shape/d3-shape-tests.ts index 6e0fa97d96..ee9a8fbb98 100644 --- a/types/d3-shape/d3-shape-tests.ts +++ b/types/d3-shape/d3-shape-tests.ts @@ -1319,10 +1319,10 @@ customSymbol = d3Shape.symbolTriangle; customSymbol = d3Shape.symbolWye; // ----------------------------------------------------------------------------------- -// Test pointRadius +// Test pointRadial // ----------------------------------------------------------------------------------- -let coordinatates: [number, number] = d3Shape.pointRadius(0, 12); +let coordinatates: [number, number] = d3Shape.pointRadial(0, 12); // ----------------------------------------------------------------------------------- // Test Stacks diff --git a/types/d3-shape/index.d.ts b/types/d3-shape/index.d.ts index 010c2108e9..27a92a79fe 100644 --- a/types/d3-shape/index.d.ts +++ b/types/d3-shape/index.d.ts @@ -2436,7 +2436,7 @@ export const symbolTriangle: SymbolType; export const symbolWye: SymbolType; // ----------------------------------------------------------------------------------- -// pointRadius +// pointRadial // ----------------------------------------------------------------------------------- /** @@ -2444,7 +2444,7 @@ export const symbolWye: SymbolType; * @param angle Angle in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise. * @param radius Radius. */ -export function pointRadius(angle: number, radius: number): [number, number]; +export function pointRadial(angle: number, radius: number): [number, number]; // ----------------------------------------------------------------------------------- // STACKS diff --git a/types/d3-time/index.d.ts b/types/d3-time/index.d.ts index 5e2b66718f..3d88edbf27 100644 --- a/types/d3-time/index.d.ts +++ b/types/d3-time/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.0.4 +// Last module patch version validated against: 1.0.7 // --------------------------------------------------------------- // Interfaces @@ -151,6 +151,8 @@ export interface CountableTimeInterval extends TimeInterval { * * This method can be used in conjunction with interval.range to ensure that two overlapping ranges are consistent. * + * The returned filtered interval does not support interval.count. See also interval.filter. + * * @param step Number of steps. */ every(step: number): TimeInterval | null; diff --git a/types/d3-tip/index.d.ts b/types/d3-tip/index.d.ts index e820e8120f..5a70a6cf4d 100644 --- a/types/d3-tip/index.d.ts +++ b/types/d3-tip/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Gert Braspenning // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {Primitive} from "d3"; +import { Primitive } from "d3"; declare module "d3" { type TooltipDirection = ("n" | "s" | "e" | "w" | "nw" | "ne" | "sw" | "se"); diff --git a/types/d3-zoom/d3-zoom-tests.ts b/types/d3-zoom/d3-zoom-tests.ts index 185b9fd45a..02f7120e79 100644 --- a/types/d3-zoom/d3-zoom-tests.ts +++ b/types/d3-zoom/d3-zoom-tests.ts @@ -385,6 +385,106 @@ svgZoom.translateBy( return 30; }); +// translateTo() ------------------------------------------------------------------------------------- + +// use on selection +svgZoom.translateTo(svgOverlay, 20, 50); +// svgZoom.translateTo(groupsSelection, 20, 50); // fails, as groupSelection mismachtes DOM Element type and datum type + +svgZoom.translateTo( + svgOverlay, + 20, + 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.translateTo( + 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 30; + }, + 50); +svgZoom.translateTo( + 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 30; + }, + 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; + }); + +// use on transition +svgZoom.translateTo(svgOverlayTransition, 20, 50); +// svgZoom.translateTo(groupsTransition, 20, 50); // fails, as groupTransition mismachtes DOM Element type and datum type + +svgZoom.translateTo( + svgOverlayTransition, + 20, + 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.translateTo( + 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; + }, + 50); +svgZoom.translateTo( + 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; + }, + 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; + }); + // scaleBy() ------------------------------------------------------------------------------------- // use on selection diff --git a/types/d3-zoom/index.d.ts b/types/d3-zoom/index.d.ts index a0980344bb..a633644ded 100644 --- a/types/d3-zoom/index.d.ts +++ b/types/d3-zoom/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for d3JS d3-zoom module 1.3 +// Type definitions for d3JS d3-zoom module 1.5 // Project: https://github.com/d3/d3-zoom/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.3.0 +// Last module patch version validated against: 1.5.0 import { ArrayLike, Selection, TransitionLike, ValueFn } from 'd3-selection'; import { ZoomView, ZoomInterpolator } from 'd3-interpolate'; @@ -127,7 +127,7 @@ export interface ZoomBehavior, x: number, y: number): void; /** * Translates the current zoom transform of the selected elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided by a value function evaluated for each element in the selection. * y is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param x A value function which is evaluated for each selected element, @@ -156,13 +156,13 @@ export interface ZoomBehavior, x: ValueFn, y: number): void; /** * Translates the current zoom transform of the selected elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided as a constant for all elements. * y is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param x Amount of translation in x-direction. @@ -173,13 +173,13 @@ export interface ZoomBehavior, x: number, y: ValueFn): void; /** * Translates the current zoom transform of the selected elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided by a value function evaluated for each element in the selection. * y is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param x A value function which is evaluated for each selected element, @@ -192,13 +192,13 @@ export interface ZoomBehavior, x: ValueFn, y: ValueFn): void; /** * Defines a “zoom” tween translating the current transform for the transitioning elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided as a constant for all elements. * y is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param x Amount of translation in x-direction. @@ -207,13 +207,13 @@ export interface ZoomBehavior, x: number, y: number): void; /** * Defines a “zoom” tween translating the current transform for the transitioning elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided by a value function evaluated for each element in the selection. * y is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param x A value function which is evaluated for each selected element, @@ -224,13 +224,13 @@ export interface ZoomBehavior, x: ValueFn, y: number): void; /** * Defines a “zoom” tween translating the current transform for the transitioning elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided as a constant for all elements. * y is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param x Amount of translation in x-direction. @@ -241,13 +241,13 @@ export interface ZoomBehavior, x: number, y: ValueFn): void; /** * Defines a “zoom” tween translating the current transform for the transitioning elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided by a value function evaluated for each element in the selection. * y is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param x A value function which is evaluated for each selected element, @@ -260,24 +260,158 @@ export interface ZoomBehavior, x: ValueFn, y: ValueFn): void; /** - * Scales the current zoom transform of the selected elements by k, such that the new k(1) = k(0) × k. + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided as a constant for all elements. + * + * @param selection A D3 selection of elements. + * @param x Target x-position of translation. + * @param y Target y-position of translation. + */ + translateTo(selection: Selection, x: number, y: number): void; + /** + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided by a value function evaluated for each element in the selection. + * y is provided as a constant for all elements. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param selection A D3 selection of elements. + * @param x A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target x-position of translation. + * @param y Target y-position of translation. + */ + translateTo(selection: Selection, x: ValueFn, y: number): void; + /** + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided by a value function evaluated for each element in the selection. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param selection A D3 selection of elements. + * @param x Target x-position of translation. + * @param y A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target y-position of translation. + */ + translateTo(selection: Selection, x: number, y: ValueFn): void; + /** + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided by a value function evaluated for each element in the selection. + * y is provided by a value function evaluated for each element in the selection. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param selection A D3 selection of elements. + * @param x A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target x-position of translation. + * @param y A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target y-position of translation. + */ + translateTo(selection: Selection, x: ValueFn, y: ValueFn): void; + /** + * Defines a “zoom” tween translating the current transform for the transitioning elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided as a constant for all elements. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param transition A D3 transition on elements. + * @param x Target x-position of translation. + * @param y Target y-position of translation. + */ + translateTo(transition: TransitionLike, x: number, y: number): void; + /** + * Defines a “zoom” tween translating the current transform for the transitioning elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided by a value function evaluated for each element in the selection. + * y is provided as a constant for all elements. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param transition A D3 transition on elements. + * @param x A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target x-position of translation. + * @param y Target y-position of translation. + */ + translateTo(transition: TransitionLike, x: ValueFn, y: number): void; + /** + * Defines a “zoom” tween translating the current transform for the transitioning elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided by a value function evaluated for each element in the selection. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param transition A D3 transition on elements. + * @param x Target x-position of translation. + * @param y A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target y-position of translation. + */ + translateTo(transition: TransitionLike, x: number, y: ValueFn): void; + /** + * Defines a “zoom” tween translating the current transform for the transitioning elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided by a value function evaluated for each element in the selection. + * y is provided by a value function evaluated for each element in the selection. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param transition A D3 transition on elements. + * @param x A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target x-position of translation. + * @param y A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target y-position of translation. + */ + translateTo(transition: TransitionLike, x: ValueFn, y: ValueFn): void; + + /** + * Scales the current zoom transform of the selected elements by k, such that the new k(1) = k(0)k. * * k is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param k Scale factor. */ scaleBy(selection: Selection, k: number): void; /** - * Scales the current zoom transform of the selected elements by k, such that the new k(1) = k(0) × k. + * Scales the current zoom transform of the selected elements by k, such that the new k(1) = k(0)k. * * k is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param k A value function which is evaluated for each selected element, @@ -286,24 +420,24 @@ export interface ZoomBehavior, k: ValueFn): void; /** - * Defines a “zoom” tween translating scaling the current transform of the selected elements by k, such that the new k(1) = k(0) × k. + * Defines a “zoom” tween translating scaling the current transform of the selected elements by k, such that the new k(1) = k(0)k. * * k is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param k Scale factor. */ scaleBy(transition: TransitionLike, k: number): void; /** - * Defines a “zoom” tween translating scaling the current transform of the selected elements by k, such that the new k(1) = k(0) × k. + * Defines a “zoom” tween translating scaling the current transform of the selected elements by k, such that the new k(1) = k(0)k. * * k is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param k A value function which is evaluated for each selected element, @@ -318,7 +452,7 @@ export interface ZoomBehavior, Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/dagre/index.d.ts b/types/dagre/index.d.ts index 7408d145cf..2c6c6e38ab 100644 --- a/types/dagre/index.d.ts +++ b/types/dagre/index.d.ts @@ -11,16 +11,33 @@ export namespace graphlib { edge(id: any): any; nodes(): string[]; node(id: any): any; - setDefaultEdgeLabel(callback: () => void): Graph; - setEdge(sourceId: string, targetId: string, options?: { [key: string]: any }): Graph; - setGraph(options: { [key: string]: any }): Graph; + setDefaultEdgeLabel(callback: string|(() => string|void)): Graph; + setDefaultNodeLabel(callback: string|(() => string|void)): Graph; + setEdge(sourceId: string, targetId: string, options?: { [key: string]: any }, value?: string): Graph; + setEdge(params: {v: string, w: string, name?: string}, value?: string): Graph; + setGraph(label: GraphLabel): Graph; setNode(id: string, node: { [key: string]: any }): Graph; + graph(): GraphLabel; + + constructor(opt?: {directed?: boolean, multigraph?: boolean, compound?: boolean}); + setParent(name: string, parentName: string): void; + hasNode(name: string): boolean; } } +export interface GraphLabel { + width?: number; + height?: number; + compound?: boolean; + rankdir?: string; + nodesep?: number; + edgesep?: number; +} + export function layout(graph: graphlib.Graph): void; export interface Edge { v: string; w: string; + name?: string; } diff --git a/types/deasync/deasync-tests.ts b/types/deasync/deasync-tests.ts new file mode 100644 index 0000000000..e4e77561e9 --- /dev/null +++ b/types/deasync/deasync-tests.ts @@ -0,0 +1,24 @@ +import * as deasync from "deasync"; + +function asyncFunction(input: number, cb: (res: number) => void) {} +function handle(res: number) {} + +// base case +asyncFunction(42, handle); + +// deasync +let wrapped = deasync(asyncFunction); +handle(wrapped(42)); + +// deasync.loopWhile +let done = false; +asyncFunction(42, () => { + done = true; +}); +deasync.loopWhile(() => !done); + +// deasync.runLoopOnce +deasync.runLoopOnce(); + +// deasync.sleep +deasync.sleep(100); diff --git a/types/deasync/index.d.ts b/types/deasync/index.d.ts new file mode 100644 index 0000000000..20440203e7 --- /dev/null +++ b/types/deasync/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for deasync 0.1 +// Project: https://github.com/abbr/deasync +// Definitions by: Matt Rollins +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = deasync; + +declare function deasync(fn: (...args: any[]) => void): (...args: any[]) => any; +declare namespace deasync { + function loopWhile(pred: () => boolean): void; + function runLoopOnce(): void; + function sleep(ms: number): void; +} diff --git a/types/deasync/tsconfig.json b/types/deasync/tsconfig.json new file mode 100644 index 0000000000..5b96318954 --- /dev/null +++ b/types/deasync/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", + "deasync-tests.ts" + ] +} diff --git a/types/deasync/tslint.json b/types/deasync/tslint.json new file mode 100644 index 0000000000..c6c6df5352 --- /dev/null +++ b/types/deasync/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/debessmann/debessmann-tests.ts b/types/debessmann/debessmann-tests.ts index 802257992e..4a247827fd 100644 --- a/types/debessmann/debessmann-tests.ts +++ b/types/debessmann/debessmann-tests.ts @@ -1,4 +1,4 @@ -import {DM, Event, EventId} from 'debessmann'; +import { DM, Event, EventId } from 'debessmann'; let eventId: EventId = {seq: 0, time: new Date()}; let e: Event = {_id: eventId, headers: {header1: 'header1Val'}}; diff --git a/types/decay/decay-tests.ts b/types/decay/decay-tests.ts index 20f33210ac..af45c63923 100644 --- a/types/decay/decay-tests.ts +++ b/types/decay/decay-tests.ts @@ -1,4 +1,4 @@ -import {redditHot, hackerHot, wilsonScore} from 'decay'; +import { redditHot, hackerHot, wilsonScore } from 'decay'; const upvotes = 42; const downvotes = 12; diff --git a/types/decorum/decorum-tests.ts b/types/decorum/decorum-tests.ts index 8cd03e046c..d6f2565fa5 100644 --- a/types/decorum/decorum-tests.ts +++ b/types/decorum/decorum-tests.ts @@ -1,4 +1,4 @@ -import {Required} from 'decorum'; +import { Required } from 'decorum'; import {Email} from 'decorum'; import {MinLength} from 'decorum'; import {MaxLength} from 'decorum'; diff --git a/types/dockerode/index.d.ts b/types/dockerode/index.d.ts index 1b456e8f45..d6cbadf938 100644 --- a/types/dockerode/index.d.ts +++ b/types/dockerode/index.d.ts @@ -427,6 +427,15 @@ declare namespace Dockerode { GlobalIPv6PrefixLen: number; MacAddress: string; } + }; + Node?: { + ID: string; + IP: string; + Addr: string; + Name: string; + Cpus: number; + Memory: number; + Labels: any; } }; } diff --git a/types/documentdb/documentdb-tests.ts b/types/documentdb/documentdb-tests.ts index 3395716305..3ad362e4a0 100644 --- a/types/documentdb/documentdb-tests.ts +++ b/types/documentdb/documentdb-tests.ts @@ -240,3 +240,15 @@ const rpr2 = new ddb.RangePartitionResolver((obj: any) => obj.foo, [ partitionKe const rangePartitionKey1: any = rpr1.getPartitionKey(document1); const rangeCollectionLink1: string = rpr1.resolveForCreate(hashPartitionKey1); const rangeCollectionLinks1: string[] = rpr1.resolveForRead(hashPartitionKey1); + +/** UriFactory methods */ +const dbUri = ddb.UriFactory.createDatabaseUri('dbfoo'); +const colUri = ddb.UriFactory.createDocumentCollectionUri('dbfoo', 'colbar'); +const docUri = ddb.UriFactory.createDocumentUri('dbfoo', 'colbar', 'doc1'); +const permUri = ddb.UriFactory.createPermissionUri('dbfoo', 'userId', 'permission1'); +const sprocUri = ddb.UriFactory.createStoredProcedureUri('dbfoo', 'colbar', 'sproc1'); +const triggerUri = ddb.UriFactory.createTriggerUri('dbfoo', 'colbar', 'trigger1'); +const udfUri = ddb.UriFactory.createUserDefinedFunctionUri('dbfoo', 'colbar', 'udf1'); +const conflictUri = ddb.UriFactory.createConflictUri('dbfoo', 'colbar', 'conflict1'); +const attachUri = ddb.UriFactory.createAttachmentUri('dbfoo', 'colbar', 'doc1', 'attachment1'); +const partitionKeyRangeUri = ddb.UriFactory.createPartitionKeyRangesUri('dbfoo', 'colbar'); diff --git a/types/documentdb/index.d.ts b/types/documentdb/index.d.ts index 7e73926c7f..140470fbda 100644 --- a/types/documentdb/index.d.ts +++ b/types/documentdb/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for DocumentDB 1.10 // Project: https://github.com/Azure/azure-documentdb-node -// Definitions by: Noel Abrahams , Brett Gutstein , Chris Stone +// Definitions by: Noel Abrahams , Brett Gutstein , Chris Stone , Yifan Wu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/documentdb /// @@ -1340,6 +1340,109 @@ export class DocumentClient { getWriteEndpoint(callback: RequestCallback): void; } +export class UriFactory { + /** + * Given a database id, this creates a database link. + * @param {string} databaseId -The database id + * @returns {string} -A database link in the format of dbs/{0} with {0} being a Uri escaped version of the databaseId + * @description Would be used when creating or deleting a DocumentCollection or a User in Azure DocumentDB database service + */ + static createDatabaseUri(databaseId: string): string; + /** + * Given a database and collection id, this creates a collection link. + * @param {string} databaseId -The database id + * @param {string} collectionId -The collection id + * @returns {string} A collection link in the format of dbs/{0}/colls/{1} with {0} being a Uri escaped version of the databaseId and {1} being collectionId + * @description Would be used when updating or deleting a DocumentCollection, creating a Document, a StoredProcedure, a + * Trigger, a UserDefinedFunction, or when executing a query with CreateDocumentQuery in Azure DocumentDB database service. + */ + static createDocumentCollectionUri(databaseId: string, collectionId: string): string; + /** + * Given a database and collection id, this creates a collection link. + * @param {string} databaseId -The database id + * @param {string} collectionId -The collection id + * @param {string} documentId -The document id + * @returns {string} -A document link in the format of dbs/{0}/colls/{1}/docs/{2} with {0} + * being a Uri escaped version of the databaseId, {1} being collectionId and {2} being the documentId + * @description Would be used when creating an Attachment, or when replacing or deleting a Document in Azure DocumentDB database service + */ + static createDocumentUri(databaseId: string, collectionId: string, documentId: string): string; + /** + * Given a database, collection and document id, this creates a document link. + * @param {string} databaseId -The database Id + * @param {string} userId -The user Id + * @param {string} permissionId - The permissionId + * @returns {string} A permission link in the format of dbs/{0}/users/{1}/permissions/{2} with {0} being a Uri escaped version of the databaseId, {1} being userId and {2} being permissionId + * @description Would be used when replacing or deleting a Permission in Azure DocumentDB database service. + */ + static createPermissionUri(databaseId: string, userId: string, permissionId: string): string; + + /** + * Given a database, collection and stored proc id, this creates a stored proc link. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} storedProcedureId -The stored procedure Id + * @returns {string} -A stored procedure link in the format of dbs/{0}/colls/{1}/sprocs/{2} + * with {0} being a Uri escaped version of the databaseId, + * {1} being collectionId and {2} being the storedProcedureId + * @description Would be used when replacing, executing, or deleting a StoredProcedure in Azure DocumentDB database service. + */ + static createStoredProcedureUri(databaseId: string, collectionId: string, storedProcedureId: string): string; + + /** + * @summary Given a database, collection and trigger id, this creates a trigger link. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} triggerId -The trigger Id + * @returns {string} -A trigger link in the format of dbs/{0}/colls/{1}/triggers/{2} + * with {0} being a Uri escaped version of the databaseId, + * {1} being collectionId and {2} being the triggerId + * @description Would be used when replacing, executing, or deleting a Trigger in Azure DocumentDB database service + */ + static createTriggerUri(databaseId: string, collectionId: string, triggerId: string): string; + + /** + * @summary Given a database, collection and udf id, this creates a udf link. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} udfId -The User Defined Function Id + * @returns {string} -A udf link in the format of dbs/{0}/colls/{1}/udfs/{2} with {0} being a Uri escaped version of the databaseId, {1} being collectionId and {2} being the udfId + * @description Would be used when replacing, executing, or deleting a UserDefinedFunction in Azure DocumentDB database service + */ + static createUserDefinedFunctionUri(databaseId: string, collectionId: string, udfId: string): string; + + /** + * @summary + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} conflictId -The conflict Id + * @returns {string} -A conflict link in the format of dbs/{0}/colls/{1}/conflicts/{2} + * with {0} being a Uri escaped version of the databaseId, {1} being collectionId and {2} being the conflictId + * @description Would be used when creating a Conflict in Azure DocumentDB database service. + */ + static createConflictUri(databaseId: string, collectionId: string, conflictId: string): string; + + /** + * @summary Given a database, collection and conflict id, this creates a conflict link. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} documentId -The document Id\ + * @param {string} attachmentId -The attachment Id + * @returns {string} -A conflict link in the format of dbs/{0}/colls/{1}/conflicts/{2} with {0} being a Uri escaped version of the databaseId, + * {1} being collectionId and {2} being the conflictId + * @description Would be used when creating a Conflict in Azure DocumentDB database service. + */ + static createAttachmentUri(databaseId: string, collectionId: string, documentId: string, attachmentId: string): string; + + /** + * @summary Given a database and collection, this creates a partition key ranges link in the Azure DocumentDB database service. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @returns {string} -A partition key ranges link in the format of dbs/{0}/colls/{1}/pkranges with {0} being a Uri escaped version of the databaseId and {1} being collectionId + */ + static createPartitionKeyRangesUri(databaseId: string, collectionId: string): string; +} + export type MediaReadMode = 'Buffered' | 'Streamed'; export type ConsistencyLevel = 'Strong' | 'BoundedStaleness' | 'Session' | 'Eventual'; export type IndexingMode = 'Consistent' | 'Lazy'; diff --git a/types/dookie/dookie-tests.ts b/types/dookie/dookie-tests.ts index 476538b8de..e672d59de6 100644 --- a/types/dookie/dookie-tests.ts +++ b/types/dookie/dookie-tests.ts @@ -1,4 +1,4 @@ -import {push, pull} from 'dookie'; +import { push, pull } from 'dookie'; (async () => { await push('mongodb://localhost:27017/test', {test: [{ok: 1}, {ok: 2}]}); diff --git a/types/dot-prop/dot-prop-tests.ts b/types/dot-prop/dot-prop-tests.ts index b7687bb64b..420fe2d320 100644 --- a/types/dot-prop/dot-prop-tests.ts +++ b/types/dot-prop/dot-prop-tests.ts @@ -1,11 +1,23 @@ +/// +import dotProp = require('dot-prop'); +import { get, has, set } from 'dot-prop'; -import * as dotProp from 'dot-prop'; - -dotProp.get({foo: {bar: 'unicorn'}}, 'foo.bar'); +get({foo: {bar: 'unicorn'}}, 'foo.bar'); dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep'); +dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep', 'default value'); dotProp.get({foo: {'dot.dot': 'unicorn'}}, 'foo.dot\\.dot'); const obj = {foo: {bar: 'a'}}; -dotProp.set(obj, 'foo.bar', 'b'); +set(obj, 'foo.bar', 'b'); +console.log(obj); dotProp.set(obj, 'foo.baz', 'x'); -dotProp.set(obj, 'foo.dot\\.dot', 'unicorn'); +console.log(obj); + +has({foo: {bar: 'unicorn'}}, 'foo.bar'); +dotProp.has({foo: {bar: 'unicorn'}}, 'foo.bar'); + +dotProp.delete(obj, 'foo.bar'); +console.log(obj); +( obj).foo.bar = {x: 'y', y: 'x'}; +dotProp.delete(obj, 'foo.bar.x'); +console.log(obj); diff --git a/types/dot-prop/index.d.ts b/types/dot-prop/index.d.ts index b8d9ce406c..31877dbd9e 100644 --- a/types/dot-prop/index.d.ts +++ b/types/dot-prop/index.d.ts @@ -1,8 +1,17 @@ -// Type definitions for dot-prop -// Project: https://github.com/sindresorhus/dot-prop +// Type definitions for dot-prop 4.1 +// Project: https://github.com/sindresorhus/dot-prop#readme // Definitions by: Sam Verschueren +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +interface DotProp { + get(obj: object, path: string, defaultValue?: any): any; + set(obj: object, path: string, value: any): void; + has(obj: object, path: string): boolean; + delete(obj: object, path: string): boolean; +} -export declare function get(object: any, path: string): any; -export declare function set(object: any, path: string, value: any): void; +declare const dotProp: DotProp; + +export = dotProp; diff --git a/types/dot-prop/tsconfig.json b/types/dot-prop/tsconfig.json index f404606239..9569bb6470 100644 --- a/types/dot-prop/tsconfig.json +++ b/types/dot-prop/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "dot-prop-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/dot-prop/tslint.json b/types/dot-prop/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dot-prop/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dot-prop/v2/dot-prop-tests.ts b/types/dot-prop/v2/dot-prop-tests.ts new file mode 100644 index 0000000000..f9991f8d5b --- /dev/null +++ b/types/dot-prop/v2/dot-prop-tests.ts @@ -0,0 +1,10 @@ +import * as dotProp from 'dot-prop'; + +dotProp.get({foo: {bar: 'unicorn'}}, 'foo.bar'); +dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep'); +dotProp.get({foo: {'dot.dot': 'unicorn'}}, 'foo.dot\\.dot'); + +const obj = {foo: {bar: 'a'}}; +dotProp.set(obj, 'foo.bar', 'b'); +dotProp.set(obj, 'foo.baz', 'x'); +dotProp.set(obj, 'foo.dot\\.dot', 'unicorn'); diff --git a/types/dot-prop/v2/index.d.ts b/types/dot-prop/v2/index.d.ts new file mode 100644 index 0000000000..86964e32a7 --- /dev/null +++ b/types/dot-prop/v2/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for dot-prop 2.x +// Project: https://github.com/sindresorhus/dot-prop +// Definitions by: Sam Verschueren +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function get(object: any, path: string): any; +export function set(object: any, path: string, value: any): void; diff --git a/types/dot-prop/v2/tsconfig.json b/types/dot-prop/v2/tsconfig.json new file mode 100644 index 0000000000..2e274e84da --- /dev/null +++ b/types/dot-prop/v2/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "dot-prop": ["dot-prop/v2"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dot-prop-tests.ts" + ] +} diff --git a/types/dot-prop/v2/tslint.json b/types/dot-prop/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dot-prop/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/draft-js/draft-js-tests.tsx b/types/draft-js/draft-js-tests.tsx index 4315611765..46f90a8a31 100644 --- a/types/draft-js/draft-js-tests.tsx +++ b/types/draft-js/draft-js-tests.tsx @@ -1,6 +1,6 @@ import * as React from "react"; import * as ReactDOM from "react-dom"; -import {Map} from "immutable"; +import { Map } from "immutable"; import { ContentBlock, diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index 1019df8fce..73c248df03 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -5,6 +5,7 @@ // Yale Cason // Ryan Schwers // Michael Wu +// Willis Plummer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -863,7 +864,7 @@ declare namespace Draft { static getDataObjectForLinkURL(uri: URI): Object; static handleKeyCommand(editorState: EditorState, command: DraftEditorCommand): EditorState; - static handleKeyCommand(editorState: EditorState, command: string): EditorState; + static handleKeyCommand(editorState: EditorState, command: string): null; static insertSoftNewline(editorState: EditorState): EditorState; @@ -888,7 +889,7 @@ declare namespace Draft { */ static toggleInlineStyle(editorState: EditorState, inlineStyle: string): EditorState; - static toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string): EditorState; + static toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string | null): EditorState; /** * When a collapsed cursor is at the start of an empty styled block, allow diff --git a/types/duplexer3/duplexer3-tests.ts b/types/duplexer3/duplexer3-tests.ts new file mode 100644 index 0000000000..557437597c --- /dev/null +++ b/types/duplexer3/duplexer3-tests.ts @@ -0,0 +1,47 @@ +import * as stream from 'stream'; +import duplexer3 = require('duplexer3'); + +const writable = new stream.Writable({objectMode: true}); +const readable = new stream.Readable({objectMode: true}); + +writable._write = (input, encoding, done) => { + if (readable.push(input)) { + return done(); + } else { + readable.once('drain', <(...args: any[]) => void> done); + } +}; + +readable._read = n => { + // no-op +}; + +// simulate the readable thing closing after a bit +writable.once('finish', () => { + setTimeout(() => { + readable.push(null); + }, 500); +}); + +const duplex = duplexer3(writable, readable); +const duplex2 = duplexer3({bubbleErrors: true, allowHalfOpen: true}, writable, readable); + +duplex.on('data', e => { + console.log('got data', JSON.stringify(e)); +}); + +duplex.on('finish', () => { + console.log('got finish event'); +}); + +duplex.on('end', () => { + console.log('got end event'); +}); + +duplex.write('oh, hi there', () => { + console.log('finished writing'); +}); + +duplex.end(() => { + console.log('finished ending'); +}); diff --git a/types/duplexer3/index.d.ts b/types/duplexer3/index.d.ts new file mode 100644 index 0000000000..82693b86bf --- /dev/null +++ b/types/duplexer3/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for duplexer3 0.1 +// Project: https://github.com/floatdrop/duplexer3 +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as stream from 'stream'; + +export = duplexer3; + +declare function duplexer3(writableStream: NodeJS.WritableStream, readableStream: NodeJS.ReadableStream): stream.Duplex; +declare function duplexer3(options: duplexer3.Options, writableStream: NodeJS.WritableStream, readableStream: NodeJS.ReadableStream): stream.Duplex; + +declare namespace duplexer3 { + interface Options extends stream.DuplexOptions { + bubbleErrors?: boolean; + } +} diff --git a/types/duplexer3/tsconfig.json b/types/duplexer3/tsconfig.json new file mode 100644 index 0000000000..36ac16d2c7 --- /dev/null +++ b/types/duplexer3/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", + "duplexer3-tests.ts" + ] +} diff --git a/types/duplexer3/tslint.json b/types/duplexer3/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/duplexer3/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dygraphs/index.d.ts b/types/dygraphs/index.d.ts index fb6f4b997d..33db704b3b 100644 --- a/types/dygraphs/index.d.ts +++ b/types/dygraphs/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for dygraphs 1.1.1 +// Type definitions for dygraphs 1.1.2 // Project: http://dygraphs.com // Definitions by: Dan Vanderkam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,7 +8,7 @@ declare namespace dygraphs { type DataArray = number[][]; - type Data = string|DataArray|google.visualization.DataTable; + type Data = string | DataArray | google.visualization.DataTable; interface PerSeriesOptions { /** @@ -112,7 +112,7 @@ declare namespace dygraphs { * Function to call to format the tick values that appear along an axis. This is usually set * on a per-axis basis. */ - axisLabelFormatter?: (v: number|Date, granularity: number, opts: (name: string) => any, dygraph: Dygraph) => any; + axisLabelFormatter?: (v: number | Date, granularity: number, opts: (name: string) => any, dygraph: Dygraph) => any; /** * Width (in pixels) of the containing divs for x- and y-axis labels. For the y-axis, this @@ -224,7 +224,7 @@ declare namespace dygraphs { pixels: number, opts: (name: string) => any, dygraph: Dygraph, - vals: number[]) => Array<{v: number, label: string}>; + vals: number[]) => Array<{ v: number, label: string }>; /** @@ -267,6 +267,58 @@ declare namespace dygraphs { labelsKMG2?: boolean; } + interface SeriesLegendData { + /** + * Assigned or generated series color + */ + color: string; + /** + * Series line dash + */ + dashHTML: string; + /** + * Whether currently focused or not + */ + isHighlighted: boolean; + /** + * Whether the series line is inside the selected/zoomed region + */ + isVisible: boolean; + /** + * Assigned label to this series + */ + label: string; + /** + * Generated label html for this series + */ + labelHTML: string; + /** + * y value of this series + */ + y: number; + /** + * Generated html for y value + */ + yHTML: string; + } + interface LegendData { + /** + * x value of highlighted points + */ + x: number; + /** + * Generated HTML for x value + */ + xHTML: string; + /** + * Series data for the highlighted points + */ + series: SeriesLegendData[]; + /** + * Dygraph object for this graph + */ + dygraph: Dygraph; + } interface Options extends PerSeriesOptions, PerAxisOptions { /** * Set this option to animate the transition between zoom windows. Applies to programmatic @@ -510,14 +562,14 @@ declare namespace dygraphs { * Show data labels in an external div, rather than on the graph. This value can either be a * div element or a div id. */ - labelsDiv?: string|HTMLElement; + labelsDiv?: string | HTMLElement; /** * Additional styles to apply to the currently-highlighted points div. For example, { * 'fontWeight': 'bold' } will make the labels bold. In general, it is better to use CSS to * style the .dygraph-legend class than to use this property. */ - labelsDivStyles?: {[cssProperty: string]: string}; + labelsDivStyles?: { [cssProperty: string]: string }; /** * Width (in pixels) of the div which shows information on the currently-highlighted points. @@ -547,6 +599,11 @@ declare namespace dygraphs { */ legend?: 'always' | 'follow' | 'onmouseover'; + /** + * for details see https://github.com/danvk/dygraphs/pull/683 + */ + legendFormatter?: (legendData: LegendData) => string; + /** * A value representing the farthest a graph may be panned, in percent of the display. For * example, a value of 0.1 means that the graph can only be panned 10% pased the edges of the @@ -813,7 +870,7 @@ declare namespace dygraphs { * you specified in your CSV file, e.g. "2010-09-13". * You must set either x or xval. */ - x?: number|string; + x?: number | string; /** * numeric value of the point, or millis since epoch. @@ -867,7 +924,7 @@ declare namespace dygraphs { declare class Dygraph { constructor( container: HTMLElement | string, - data: dygraphs.Data|(()=>dygraphs.Data), + data: dygraphs.Data | (() => dygraphs.Data), options?: dygraphs.Options); /** @@ -1104,7 +1161,7 @@ declare class Dygraph { * over the graph, disabling closest-series highlighting. Call clearSelection() * to unlock it. */ - setSelection(row: number|boolean, seriesName?: string, locked?: boolean): void; + setSelection(row: number | boolean, seriesName?: string, locked?: boolean): void; /** * Clears the current selection (i.e. points that were highlighted by moving diff --git a/types/easy-session/index.d.ts b/types/easy-session/index.d.ts index 0d96c61783..9a449b5322 100644 --- a/types/easy-session/index.d.ts +++ b/types/easy-session/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/DeadAlready/node-easy-session // Definitions by: Karl Düüna // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/ebongarde-root/ebongarde-root-tests.ts b/types/ebongarde-root/ebongarde-root-tests.ts index f40eec7172..7286f811c6 100644 --- a/types/ebongarde-root/ebongarde-root-tests.ts +++ b/types/ebongarde-root/ebongarde-root-tests.ts @@ -1,3 +1,3 @@ -import {ROOT} from 'ebongarde-root'; +import { ROOT } from 'ebongarde-root'; console.log(ROOT); diff --git a/types/electron-json-storage/electron-json-storage-tests.ts b/types/electron-json-storage/electron-json-storage-tests.ts index dd0504f8b6..3abc584a46 100644 --- a/types/electron-json-storage/electron-json-storage-tests.ts +++ b/types/electron-json-storage/electron-json-storage-tests.ts @@ -1,5 +1,3 @@ -/// - import electron = require('electron'); import storage = require('electron-json-storage'); diff --git a/types/electron-json-storage/index.d.ts b/types/electron-json-storage/index.d.ts index 23b26920af..428b784638 100644 --- a/types/electron-json-storage/index.d.ts +++ b/types/electron-json-storage/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/jviotti/electron-json-storage // Definitions by: Sam Saint-Pettersen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.1 export declare function get(key: string, callback: (error: any, data: Object) => void): void; export declare function set(key: string, json: Object, callback: (error: any) => void): void; diff --git a/types/electron-json-storage/package.json b/types/electron-json-storage/package.json new file mode 100644 index 0000000000..b68da5cd37 --- /dev/null +++ b/types/electron-json-storage/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "electron": "^1.7.5" + } +} diff --git a/types/electron-notifications/index.d.ts b/types/electron-notifications/index.d.ts index 3bda7f4ef9..870fcb1bbc 100644 --- a/types/electron-notifications/index.d.ts +++ b/types/electron-notifications/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/blainesch/electron-notifications // Definitions by: Daniel Pereira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as Electron from 'electron'; diff --git a/types/electron-notifications/package.json b/types/electron-notifications/package.json new file mode 100644 index 0000000000..b68da5cd37 --- /dev/null +++ b/types/electron-notifications/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "electron": "^1.7.5" + } +} diff --git a/types/electron-notify/index.d.ts b/types/electron-notify/index.d.ts index 225ab9de9e..16f786d379 100644 --- a/types/electron-notify/index.d.ts +++ b/types/electron-notify/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/hankbao/electron-notify // Definitions by: Daniel Pereira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// @@ -18,7 +19,7 @@ export interface ICustomConfig { appIcon?: string, pathToModule?: string, logging?: boolean, - defaultWindow?: Electron.BrowserWindowOptions, + defaultWindow?: Electron.BrowserWindowConstructorOptions, defaultStyleContainer?: any, defaultStyleAppIcon?: any, defaultStyleImage?: any, @@ -57,4 +58,4 @@ export function closeAll(): void; export function getTemplatePath(): string; -export function setTemplatePath(path: string): void; \ No newline at end of file +export function setTemplatePath(path: string): void; diff --git a/types/electron-notify/package.json b/types/electron-notify/package.json new file mode 100644 index 0000000000..b68da5cd37 --- /dev/null +++ b/types/electron-notify/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "electron": "^1.7.5" + } +} diff --git a/types/electron-window-state/electron-window-state-tests.ts b/types/electron-window-state/electron-window-state-tests.ts index 8a345d0ec9..62ba0599f7 100644 --- a/types/electron-window-state/electron-window-state-tests.ts +++ b/types/electron-window-state/electron-window-state-tests.ts @@ -1,6 +1,6 @@ -import {app, BrowserWindow} from 'electron'; +import { app, BrowserWindow } from 'electron'; import windowStateKeeper = require('electron-window-state'); let win: Electron.BrowserWindow = null; diff --git a/types/electron-window-state/index.d.ts b/types/electron-window-state/index.d.ts index 1ff10ed7d5..1ff0a15878 100644 --- a/types/electron-window-state/index.d.ts +++ b/types/electron-window-state/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mawie81/electron-window-state // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/types/electron-window-state/package.json b/types/electron-window-state/package.json new file mode 100644 index 0000000000..b68da5cd37 --- /dev/null +++ b/types/electron-window-state/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "electron": "^1.7.5" + } +} diff --git a/types/email-templates/email-templates-tests.ts b/types/email-templates/email-templates-tests.ts index 9f9097609e..3c4493402c 100644 --- a/types/email-templates/email-templates-tests.ts +++ b/types/email-templates/email-templates-tests.ts @@ -1,9 +1,9 @@ import EmailTemplates = require('email-templates'); -var EmailTemplate = EmailTemplates.EmailTemplate; -var template = new EmailTemplate("./"); -var templateWithOptions = new EmailTemplate('./', {sassOptions: {}, juiceOptions: {}}); -var users = [ +const EmailTemplate = EmailTemplates.EmailTemplate; +const template = new EmailTemplate("./"); +const templateWithOptions = new EmailTemplate('./', {disableJuice: true, sassOptions: {}, juiceOptions: {}}); +const users = [ { email: 'pappa.pizza@spaghetti.com', name: { @@ -18,8 +18,12 @@ var users = [ last: 'Geppetto' } } -] +]; -var templates = users.map(function(user) { - return template.render(user); -}) +const templates = users.map((user) => { + return template.render(user) + .then((results) => { + const {html, subject, text} = results; + return html; + }); +}); diff --git a/types/email-templates/index.d.ts b/types/email-templates/index.d.ts index 5fdd7054f3..d76c23aed3 100644 --- a/types/email-templates/index.d.ts +++ b/types/email-templates/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for node-email-templates +// Type definitions for node-email-templates 2.6 // Project: https://github.com/niftylettuce/node-email-templates // Definitions by: Cyril Schumacher +// Matus Gura // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** @@ -28,23 +29,18 @@ interface EmailTemplateResults { } /** - * @summary Interface for callback of email callback. - * @interface + * @summary Callback signature. */ -interface EmailTemplateCallback { - /** - * @summary Callback signature. - */ - (err: Object, results: EmailTemplateResults): void; -} +type EmailTemplateCallback = (err: any, results: EmailTemplateResults) => void; /** * @summary Interface for email-template options * @interface */ interface EmailTemplateOptions { - sassOptions?: any; + disableJuice?: boolean; juiceOptions?: any; + sassOptions?: any; } declare module "email-templates" { @@ -52,7 +48,7 @@ declare module "email-templates" { * @summary Email template class. * @class */ - export class EmailTemplate { + class EmailTemplate { /** * @summary Constructor. * @param {string} templateDir The template directory. @@ -61,9 +57,96 @@ declare module "email-templates" { /** * @summary Render a single template. - * @param {EmailTemplateCallback|Object} locals The variables or callback function. - * @param {EmailTemplateCallback} callback The callback function. + * @param locals The template variables. + * @param locale The language code. */ - render(locals: EmailTemplateCallback|Object, callback?: EmailTemplateCallback): void | Promise; + render(locals: any, locale?: string): Promise; + + /** + * @summary Render a single template. + * @param callback The callback function. + */ + render(callback: EmailTemplateCallback): void; + + /** + * @summary Render a single template. + * @param locals The template variables. + * @param callback The callback function. + */ + render(locals: any, callback: EmailTemplateCallback): void; + + /** + * @summary Render a single template. + * @param locals The template variables. + * @param locale The language code. + * @param callback The callback function. + */ + render(locals: any, locale: string, callback: EmailTemplateCallback): void; + + /** + * @summary Render text + * @param locals The template variables. + * @param locale The language code. + */ + renderText(locals: any, locale?: string): Promise; + + /** + * @summary Render text + * @param locals The template variables. + * @param callback The language code. + */ + renderText(locals: any, callback: EmailTemplateCallback): void; + + /** + * @summary Render text + * @param locals The template variables. + * @param locale The language code. + * @param callback The language code. + */ + renderText(locals: any, locale: string, callback: EmailTemplateCallback): void; + + /** + * @summary Render subject + * @param locals The template variables. + * @param locale The language code. + */ + renderSubject(locals: any, locale?: string): Promise; + + /** + * @summary Render subject + * @param locals The template variables. + * @param callback The language code. + */ + renderSubject(locals: any, callback: EmailTemplateCallback): void; + + /** + * @summary Render subject + * @param locals The template variables. + * @param locale The language code. + * @param callback The language code. + */ + renderSubject(locals: any, locale: string, callback: EmailTemplateCallback): void; + + /** + * @summary Render HTML + * @param locals The template variables. + * @param locale The language code. + */ + renderHtml(locals: any, locale?: string): Promise; + + /** + * @summary Render HTML + * @param locals The template variables. + * @param callback The language code. + */ + renderHtml(locals: any, callback: EmailTemplateCallback): void; + + /** + * @summary Render HTML + * @param locals The template variables. + * @param locale The language code. + * @param callback The language code. + */ + renderHtml(locals: any, locale: string, callback: EmailTemplateCallback): void; } } diff --git a/types/email-templates/tsconfig.json b/types/email-templates/tsconfig.json index bc97b20dbc..cf59410224 100644 --- a/types/email-templates/tsconfig.json +++ b/types/email-templates/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "email-templates-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/email-templates/tslint.json b/types/email-templates/tslint.json new file mode 100644 index 0000000000..e765bc9e16 --- /dev/null +++ b/types/email-templates/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-single-declare-module": false + } +} diff --git a/types/engine.io-client/engine.io-client-tests.ts b/types/engine.io-client/engine.io-client-tests.ts new file mode 100644 index 0000000000..4a73136cef --- /dev/null +++ b/types/engine.io-client/engine.io-client-tests.ts @@ -0,0 +1,77 @@ +import engine = require('engine.io'); +import client = require('engine.io-client'); + +let server: engine.Server; +let socket: client.Socket; +let options: client.SocketOptions = {}; + +options.agent = false; +options.upgrade = true; +options.forceJSONP = false; +options.jsonp = false; +options.forceBase64 = false; +options.enablesXDR = false; +options.timestampRequests = true; +options.timestampParam = 't'; +options.policyPort = 843; +options.path = '/engine.io'; +options.transports = ['websocket']; +options.transportOptions = {}; +options.rememberUpgrade = true; +options.pfx = ''; +options.key = ''; +options.passphrase = ''; +options.cert = ''; +options.ca = ''; +options.ciphers = undefined; +options.rejectUnauthorized = true; +options.perMessageDeflate = false; +options.extraHeaders = {foo: 'bar'}; +options.onlyBinaryUpgrades = true; +options.forceNode = false; +options.localAddress = 'localhost'; + +socket = client("ws://localhost:32767", options); +socket.on('close', (mes, detail) => { + console.log('CLOSE', mes, detail); +}); +socket.on('error', (err) => { + console.log('ERROR', err); +}); + +server = engine.listen(8000, {pingTimeout: 100, pingInterval: 30}); +server.on("connection", socket => { + socket.send('hello'); +}); + +socket = client("ws://localhost:8000"); +socket.on("message", (data) => { + console.log('MESSAGE', data); +}); +socket.on('close', (mes, detail) => { + console.log('CLOSE', mes, detail); +}); +socket.on('ping', () => { + console.log('client ping callback'); +}); +socket.on('pong', () => { + console.log('client pong callback'); +}); +socket.on('flush', () => { + console.log('client flush callback'); +}); +socket.on('drain', () => { + console.log('client drain callback'); +}); +socket.on("open", () => { + socket.send("hi", {compress: false}, () => { + console.log('client send callback'); + setTimeout(() => { + socket.close(); + setTimeout(() => { + server.close(); + server.httpServer!.close(); + }, 200); + }, 200); + }); +}); diff --git a/types/engine.io-client/index.d.ts b/types/engine.io-client/index.d.ts new file mode 100644 index 0000000000..0407c86fed --- /dev/null +++ b/types/engine.io-client/index.d.ts @@ -0,0 +1,184 @@ +// Type definitions for engine.io-client 3.1 +// Project: https://github.com/socketio/engine.io-client +// Definitions by: KentarouTakeda +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import http = require('http'); + +declare namespace client { + type Transport = 'polling'|'websocket'; + type Message = string|ArrayBuffer|ArrayBufferView|Blob; + interface MessageOptions { + compress?: boolean; + } + interface SocketOptions { + /** + * http.Agent to use, defaults to false (NodeJS only) + */ + agent?: http.Agent|false; + /** + * defaults to true, whether the client should try to upgrade the transport from long-polling to something better. + */ + upgrade?: boolean; + /** + * forces JSONP for polling transport. + */ + forceJSONP?: boolean; + /** + * determines whether to use JSONP when necessary for polling. + * If disabled (by settings to false) an error will be emitted (saying "No transports available") + * if no other transports are available. If another transport is available + * for opening a connection (e.g. WebSocket) that transport will be used instead. + */ + jsonp?: boolean; + /** + * forces base 64 encoding for polling transport even when XHR2 responseType is available and WebSocket even if the used standard supports binary. + */ + forceBase64?: boolean; + /** + * enables XDomainRequest for IE8 to avoid loading bar flashing with click sound. default to false because XDomainRequest has a flaw of not sending cookie. + */ + enablesXDR?: boolean; + /** + * whether to add the timestamp with each transport request. Note: polling requests are always stamped unless this option is explicitly set to false (false) + */ + timestampRequests?: boolean; + /** + * timestamp parameter (t) + */ + timestampParam?: string; + /** + * port the policy server listens on (843) + */ + policyPort?: number; + /** + * path to connect to, default is /engine.io + */ + path?: string; + /** + * a list of transports to try (in order). Defaults to ['polling', 'websocket']. Engine always attempts to connect directly with the first one, provided the feature detection test for it passes. + */ + transports?: Transport[]; + /** + * hash of options, indexed by transport name, overriding the common options for the given transport + */ + transportOptions?: {[key: string]: SocketOptions}; + /** + * defaults to false. If true and if the previous websocket connection to the server succeeded, + * the connection attempt will bypass the normal upgrade process and will initially try websocket. + * A connection attempt following a transport error will use the normal upgrade process. + * It is recommended you turn this on only when using SSL/TLS connections, + * or if you know that your network does not block websockets. + */ + rememberUpgrade?: boolean; + /** + * Certificate, Private key and CA certificates to use for SSL. Can be used in Node.js client environment to manually specify certificate information. + */ + pfx?: string; + /** + * Private key to use for SSL. Can be used in Node.js client environment to manually specify certificate information. + */ + key?: string; + /** + * A string of passphrase for the private key or pfx. Can be used in Node.js client environment to manually specify certificate information. + */ + passphrase?: string; + /** + * Public x509 certificate to use. Can be used in Node.js client environment to manually specify certificate information. + */ + cert?: string; + /** + * An authority certificate or array of authority certificates to check the remote host against. + * Can be used in Node.js client environment to manually specify certificate information. + */ + ca?: string|string[]; + /** + * A string describing the ciphers to use or exclude. Consult the cipher format list for details on the format. + * Can be used in Node.js client environment to manually specify certificate information. + */ + ciphers?: string; + /** + * If true, the server certificate is verified against the list of supplied CAs. + * An 'error' event is emitted if verification fails. Verification happens at the connection level, + * before the HTTP request is sent. Can be used in Node.js client environment to manually specify certificate information. + */ + rejectUnauthorized?: boolean; + /** + * parameters of the WebSocket permessage-deflate extension (see ws module api docs). Set to false to disable. (true) + */ + perMessageDeflate?: any; + /** + * Headers that will be passed for each request to the server (via xhr-polling and via websockets). + * These values then can be used during handshake or for special proxies. Can only be used in Node.js client environment. + */ + extraHeaders?: {[header: string]: string}; + /** + * whether transport upgrades should be restricted to transports supporting binary data (false) + */ + onlyBinaryUpgrades?: boolean; + /** + * Uses NodeJS implementation for websockets - even if there is a native Browser-Websocket available, + * which is preferred by default over the NodeJS implementation. (This is useful when using hybrid platforms + * like nw.js or electron) (false, NodeJS only) + */ + forceNode?: boolean; + /** + * the local IP address to connect to + */ + localAddress?: string; + } + + interface UpgradeError extends Error { + transport: string; + } + + class Socket { + protocol?: number; + binaryType?: 'arraybuffer'|'blob'; + + /* + * open: Fired upon successful connection. + * flush: Fired upon completing a buffer flush + * drain: Fired after drain event of transport if writeBuffer is empty + * ping: Fired upon flushing a ping packet (ie: actual packet write out) + * pong: Fired upon receiving a pong packet. + */ + on(ev: 'open'|'flush'|'drain'|'ping'|'pong' , cb: () => void): this; + /* + * Fired when data is received from the server. + */ + on(ev: 'message' , cb: (data: string|ArrayBuffer) => void): this; + /* + * Fired upon disconnection. In compliance with the WebSocket API spec, this event may be fired even if the open event does not occur (i.e. due to connection error or close()). + */ + on(ev: 'close' , cb: (mes: string, detail?: Error) => void): this; + /* + * Fired when an error occurs. + */ + on(ev: 'error' , cb: (err: Error) => void): this; + /* + * Fired if an error occurs with a transport we're trying to upgrade to. + */ + on(ev: 'upgradeError' , cb: (err: UpgradeError) => void): this; + /* + * Fired upon upgrade success, after the new transport is set + */ + on(ev: 'upgrade' , cb: (transport: any) => void): this; + + /** + * Sends a message to the server + */ + send(message: Message, opts?: MessageOptions, cb?: () => void): this; + + /** + * Disconnects the client. + */ + close(): this; + } +} + +declare function client(url?: string, opts?: client.SocketOptions): client.Socket; + +export = client; diff --git a/types/engine.io-client/tsconfig.json b/types/engine.io-client/tsconfig.json new file mode 100644 index 0000000000..aacd3365c5 --- /dev/null +++ b/types/engine.io-client/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "dom", + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "noImplicitReturns": true, + "strict": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "engine.io-client-tests.ts" + ] +} diff --git a/types/engine.io-client/tslint.json b/types/engine.io-client/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/engine.io-client/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/engine.io/engine.io-tests.ts b/types/engine.io/engine.io-tests.ts new file mode 100644 index 0000000000..4199393b5d --- /dev/null +++ b/types/engine.io/engine.io-tests.ts @@ -0,0 +1,168 @@ +import engine = require('engine.io'); +import http = require('http'); + +let serverOptions: engine.ServerOptions; +let server: engine.Server; +let httpServer: http.Server; +let attachOptions: engine.AttachOptions; +let serverAttachOptions: engine.ServerAttachOptions; + +serverOptions = {}; +serverOptions = { + pingTimeout: 60000, + pingInterval: 25000, + upgradeTimeout: 10000, + maxHttpBufferSize: 10E7, + transports: ['polling', 'websocket'], + allowUpgrades: true, + perMessageDeflate: true, + httpCompression: true, + cookie: 'io', + cookiePath: '/', + wsEngine: 'ws', + initialPacket: new Buffer([0, 1, 2, 3, 4, 5]), + allowRequest: (req, cb) => { + console.log(req.url); + cb(null, true); + } +}; +attachOptions = { + path: '/engine.io' , + destroyUpgrade: true, + destroyUpgradeTimeout: 1000, +}; +attachOptions.handlePreflightRequest = true; +attachOptions.handlePreflightRequest = false; +attachOptions.handlePreflightRequest = (server, req, res) => { + console.log(server.clientsCount); + console.log(req.httpVersion); + console.log(res.finished); +}; +serverAttachOptions = Object.assign({}, serverOptions, attachOptions); + +console.log(engine.protocol); + +httpServer = http.createServer(); +httpServer.listen(8000); + +server = engine(httpServer); +server.close(); + +server = engine(httpServer, serverOptions); +server.close(); + +httpServer.close(); + +server = engine.listen(8000); +server.httpServer!.close(); +server.close(); + +server = engine.listen(8000, serverOptions); +server.httpServer!.close(); +server.close(); + +server = engine.listen(8000, serverOptions, () => {}); +server.httpServer!.close(); +server.close(); + +httpServer = http.createServer(); +httpServer.listen(8000); +server = engine.attach(httpServer); +server.close(); +httpServer.close(); + +httpServer = http.createServer(); +httpServer.listen(8000); +server = engine.attach(httpServer, serverOptions); +server.close(); +httpServer.close(); + +httpServer = http.createServer(); +httpServer.listen(8000); +server = engine.attach(httpServer, attachOptions); +server.close(); +httpServer.close(); + +httpServer = http.createServer(); +httpServer.listen(8000); +server = engine.attach(httpServer, serverAttachOptions); +server.close(); +httpServer.close(); + +server = new engine.Server(); +server.close(); + +server = new engine.Server(); +server.close(); + +httpServer = http.createServer(); +httpServer.listen(8000); +server = new engine.Server(serverOptions); +server.attach(httpServer); +server.attach(httpServer, attachOptions); +server.close(); +httpServer.close(); + +server.generateId = (req) => Math.floor(Math.random() * 100000).toString(); + +httpServer = http.createServer(); +httpServer.listen(8000); +server = new engine.Server(serverOptions); +httpServer.on('upgrade', (req, socket, head) => { + server.handleUpgrade(req, socket, head); +}); +httpServer.on('request', (req, res) => { + server.handleRequest(req, res); +}); + +console.log(server.clients); +console.log(server.clientsCount); + +server.on('connection', (socket) => { + console.log(socket.id); + console.log(socket.server.getMaxListeners()); + console.log(socket.request.headers); + console.log(socket.upgraded); + console.log(socket.readyState); + console.log(server.clients[socket.id].id); + + socket.on('close', (reason, description) => { + console.log('CLOSE', reason, description && description.message); + }); + socket.on('message', (message) => { + console.log('MESSAGE', message); + }); + socket.on('error', err => { + console.log('ERROR', err); + }); + socket.on('flush', buffer => { + console.log('FLUSH', buffer); + }); + socket.on('drain', () => { + console.log('DRAIN'); + }); + socket.on('packet', packet => { + console.log('PACKET', packet.type, packet.data); + }); + socket.on('packetCreate', packet => { + console.log('PACKETCREATE', packet.type, packet.data); + }); + + socket.send('utf 8 string', {compress: false}, () => { + console.log("SENDCALLBACK"); + }); + socket.send(new Buffer([0, 1, 2, 3, 4, 5])); // binary data +}); + +server.once('flush', (socket, buffer) => { + console.log(socket.id); + console.log(buffer[0].type); + console.log(buffer[0].options); + console.log(buffer[0].data); +}); +server.once('drain', (socket) => { + console.log(socket.id); +}); + +server.close(); +httpServer.close(); diff --git a/types/engine.io/index.d.ts b/types/engine.io/index.d.ts new file mode 100644 index 0000000000..2d1be7643e --- /dev/null +++ b/types/engine.io/index.d.ts @@ -0,0 +1,229 @@ +// Type definitions for engine.io 3.1 +// Project: https://github.com/socketio/engine.io +// Definitions by: KentarouTakeda +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import http = require('http'); +import net = require('net'); +import { EventEmitter } from "events"; + +declare namespace engine { + type Message = string|Buffer|ArrayBuffer|ArrayBufferView; + type Transport = "polling"|"websocket"; + interface Packet { + type: string; + options?: MessageOptions; + data?: Message; + } + type AllowRequestFunction = (req: http.IncomingMessage, fn: (err: string|null|undefined, success: boolean) => void) => void; + + interface ServerOptions { + /** + * how many ms without a pong packet to consider the connection closed (60000) + */ + pingTimeout?: number; + /** + * how many ms before sending a new ping packet (25000) + */ + pingInterval?: number; + /** + * how many ms before an uncompleted transport upgrade is cancelled (10000) + */ + upgradeTimeout?: number; + /** + * how many bytes or characters a message can be, before closing the session (to avoid DoS). Default value is 10E7. + */ + maxHttpBufferSize?: number; + /** + * A function that receives a given handshake or upgrade request as its first parameter, + * and can decide whether to continue or not. The second argument is a function that needs + * to be called with the decided information: fn(err, success), where success is a boolean + * value where false means that the request is rejected, and err is an error code. + */ + allowRequest?: AllowRequestFunction; + /** + * to allow connections to (['polling', 'websocket']) + */ + transports?: engine.Transport[]; + /** + * whether to allow transport upgrades (true) + */ + allowUpgrades?: boolean; + /** + * parameters of the WebSocket permessage-deflate extension (see ws module api docs). Set to false to disable. (true) + */ + perMessageDeflate?: any; + /** + * parameters of the http compression for the polling transports (see zlib api docs). Set to false to disable. (true) + */ + httpCompression?: any; + /** + * name of the HTTP cookie that contains the client sid to send as part of handshake response headers. Set to false to not send one. (io) + */ + cookie?: string|boolean; + /** + * path of the above cookie option. If false, no path will be sent, + * which means browsers will only send the cookie on the engine.io + * attached path (/engine.io). Set false to not save io cookie + * on all requests. (/) + */ + cookiePath?: string|boolean; + /** + * If true HttpOnly io cookie cannot be accessed by client-side APIs, + * such as JavaScript. (true) This option has no effect + * if cookie or cookiePath is set to false. + */ + cookieHttpOnly?: boolean; + /** + * what WebSocket server implementation to use. Specified module must + * conform to the ws interface (see ws module api docs). Default value is ws. + * An alternative c++ addon is also available by installing uws module. + */ + wsEngine?: "ws"|"uws"; + /** + * an optional packet which will be concatenated to the handshake packet emitted by Engine.IO. + */ + initialPacket?: Message; + } + interface AttachOptions { + /** + * name of the path to capture (/engine.io). + */ + path?: string; + /** + * destroy unhandled upgrade requests (true) + */ + destroyUpgrade?: boolean; + /** + * milliseconds after which unhandled requests are ended (1000) + */ + destroyUpgradeTimeout?: number; + /** + * whether to let engine.io handle the OPTIONS requests. You can also pass a custom function to handle the requests (true) + */ + handlePreflightRequest?: boolean|((server: Server, req: http.IncomingMessage, res: http.ServerResponse) => void); + } + interface ServerAttachOptions extends ServerOptions, AttachOptions {} + + interface MessageOptions { + compress?: boolean; + } + + /** + * The main server/manager. Inherits from EventEmitter. + */ + class Server extends EventEmitter { + /** + * hash of connected clients by id. + */ + clients: {[sid: string]: Socket}; + /** + * number of connected clients. + */ + clientsCount: number; + + /** + * Initializes the server + */ + constructor(opts?: engine.ServerOptions); + /** + * Fired when a new connection is established. + */ + on(ev: 'connection'|'drain', fn: (socket: Socket) => void): this; + on(ev: 'flush', fn: (socket: Socket, buffer: Packet[]) => void): this; + /** + * Closes all clients + */ + close(): this; + readonly httpServer?: http.Server; + /** + * Called internally when a Engine request is intercepted. + */ + handleRequest(req: http.IncomingMessage, res: http.ServerResponse): this; + /** + * Called internally when a Engine ws upgrade is intercepted. + */ + handleUpgrade(req: http.IncomingMessage, socket: net.Socket, head: Buffer): this; + /** + * Attach this Server instance to an http.Server + * Captures upgrade requests for a http.Server. In other words, makes a regular http.Server WebSocket-compatible. + */ + attach(http: http.Server, opts?: AttachOptions): this; + /** + * Generate a socket id. + * Overwrite this method to generate your custom socket id. + */ + generateId(req: http.IncomingMessage): string; + } + + /** + * A representation of a client. Inherits from EventEmitter. + */ + class Socket extends EventEmitter { + /** + * unique identifier + */ + id: string; + /** + * engine parent reference + */ + server: Server; + /** + * request that originated the Socket + */ + request: http.IncomingMessage; + /** + * whether the transport has been upgraded + */ + upgraded: boolean; + /** + * readyState + */ + readyState: 'opening'|'open'|'closing'|'closed'; + + /** + * Sends a message, performing message = toString(arguments[0]) unless sending binary data, which is sent as is. + */ + send(message: Message, opts?: MessageOptions, fn?: ((transport: any) => void)): void; + + /** + * Disconnects the client + */ + close(): this; + + /** + * Fired when the client is disconnected. + */ + on(ev: "close", fn: (reason: string, description?: Error) => void): this; + /** + * Fired when the client sends a message. + */ + on(ev: "message", fn: (data: string|Buffer) => void): this; + /** + * Fired when an error occurs. + */ + on(ev: "error", fn: (err: Error) => void): this; + /** + * Called when the write buffer is being flushed. + */ + on(ev: "flush", fn: (buffer: Packet[]) => void): this; + /** + * Called when the write buffer is drained + */ + on(ev: "drain", fn: () => void): this; + /** + * packet: Called when a socket received a packet (message, ping) + * packetCreate: Called before a socket sends a packet (message, pong) + */ + on(ev: "packet" | "packetCreate", fn: (packet: Packet) => void): this; + } + function attach(http: net.Server, opyts?: engine.ServerAttachOptions): engine.Server; + function listen(port: number, opts?: engine.ServerOptions, fn?: () => void): engine.Server; + const protocol: number; +} + +declare function engine(httpServer?: net.Server, opts?: engine.ServerOptions): engine.Server; + +export = engine; diff --git a/types/engine.io/tsconfig.json b/types/engine.io/tsconfig.json new file mode 100644 index 0000000000..4ec2d12abc --- /dev/null +++ b/types/engine.io/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strict": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "engine.io-tests.ts" + ] +} diff --git a/types/engine.io/tslint.json b/types/engine.io/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/engine.io/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 01ecfa90d8..e1fdba2027 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -3,7 +3,6 @@ // Definitions by: Marian Palkus // Cap3 // Ivo Stratev -// Tom Crockett // jwbay // huhuanming // MartynasZilinskas @@ -11,7 +10,7 @@ // TypeScript Version: 2.3 /// -import { ReactElement, Component, HTMLAttributes as ReactHTMLAttributes, SVGAttributes as ReactSVGAttributes } from "react"; +import { ReactElement, Component, AllHTMLAttributes as ReactHTMLAttributes, SVGAttributes as ReactSVGAttributes } from "react"; export type HTMLAttributes = ReactHTMLAttributes<{}> & ReactSVGAttributes<{}>; diff --git a/types/epub/index.d.ts b/types/epub/index.d.ts index fe4f36ce87..2c2480e91a 100644 --- a/types/epub/index.d.ts +++ b/types/epub/index.d.ts @@ -32,7 +32,7 @@ **/ declare module "epub" { - import {EventEmitter} from "events"; + import { EventEmitter } from "events"; interface TocElement { level: number; diff --git a/types/esprima/index.d.ts b/types/esprima/index.d.ts index f03fd096f9..2d5f933cad 100644 --- a/types/esprima/index.d.ts +++ b/types/esprima/index.d.ts @@ -13,7 +13,7 @@ declare namespace esprima { const version: string; - function parse(code: string, options?: Options): ESTree.Program; + function parse(code: string, options?: Options, delegate?: (node: ESTree.Node, meta: any) => void): ESTree.Program; function tokenize(code: string, options?: Options): Array; interface Token { @@ -101,4 +101,4 @@ declare namespace esprima { YieldExpression: 'YieldExpression' }; -} \ No newline at end of file +} diff --git a/types/estree/estree-tests.ts b/types/estree/estree-tests.ts index ace67225a4..ac2516f18b 100644 --- a/types/estree/estree-tests.ts +++ b/types/estree/estree-tests.ts @@ -89,6 +89,7 @@ declare var awaitExpression: ESTree.AwaitExpression; declare var toplevelStatement: ESTree.Statement | ESTree.ModuleDeclaration; declare var expressionOrPattern: ESTree.Expression | ESTree.Pattern; declare var variableDeclaratorOrExpression: ESTree.VariableDeclaration | ESTree.Expression; +declare var variableDeclaratorOrPattern: ESTree.VariableDeclaration | ESTree.Pattern; declare var literalOrIdentifier: ESTree.Literal | ESTree.Identifier; declare var blockStatementOrExpression: ESTree.BlockStatement | ESTree.Expression; declare var identifierOrExpression: ESTree.Identifier | ESTree.Expression; @@ -156,7 +157,7 @@ var expressionMaybe: ESTree.Expression | null | undefined = forStatement.update; // ForInStatement var forInStatement: ESTree.ForInStatement; -variableDeclaratorOrExpression = forInStatement.left; +variableDeclaratorOrPattern = forInStatement.left; expression = forInStatement.right; // Expression @@ -723,3 +724,33 @@ switch (moduleSpecifier.type) { default: never = moduleSpecifier; } + +switch (forInStatement.left.type) { + case 'Identifier': + identifier = forInStatement.left; + break; + case 'ObjectPattern': + objectPattern = forInStatement.left; + break; + case 'ArrayPattern': + arrayPattern = forInStatement.left; + break; + case 'MemberExpression': + memberExpression = forInStatement.left; + break; +} + +switch (forOfStatement.left.type) { + case 'Identifier': + identifier = forOfStatement.left; + break; + case 'ObjectPattern': + objectPattern = forOfStatement.left; + break; + case 'ArrayPattern': + arrayPattern = forOfStatement.left; + break; + case 'MemberExpression': + memberExpression = forOfStatement.left; + break; +} diff --git a/types/estree/index.d.ts b/types/estree/index.d.ts index b7a4005add..23c5b19f86 100644 --- a/types/estree/index.d.ts +++ b/types/estree/index.d.ts @@ -58,6 +58,7 @@ export interface Program extends BaseNode { type: "Program"; sourceType: "script" | "module"; body: Array; + comments?: Array; } interface BaseFunction extends BaseNode { @@ -89,6 +90,7 @@ export interface EmptyStatement extends BaseStatement { export interface BlockStatement extends BaseStatement { type: "BlockStatement"; body: Array; + innerComments?: Array; } export interface ExpressionStatement extends BaseStatement { @@ -169,7 +171,7 @@ export interface ForStatement extends BaseStatement { } interface BaseForXStatement extends BaseStatement { - left: VariableDeclaration | Expression; + left: VariableDeclaration | Pattern; right: Expression; body: Statement; } diff --git a/types/exceljs/exceljs-tests.ts b/types/exceljs/exceljs-tests.ts index 95147c7726..12b3337cb8 100644 --- a/types/exceljs/exceljs-tests.ts +++ b/types/exceljs/exceljs-tests.ts @@ -1,4 +1,7 @@ import * as Excel from 'exceljs'; +import * as stream from 'stream'; +import * as fs from 'fs'; +import * as Bluebird from 'bluebird'; // most examples taken and adapted from README.md @@ -18,65 +21,446 @@ workbook.views = [ } ]; -const worksheet: Excel.Worksheet = workbook.addWorksheet('My Sheet'); +const worksheet = workbook.addWorksheet('My Sheet'); + +workbook.eachSheet((worksheet, sheetId) => null); + const worksheet2 = workbook.getWorksheet('My Sheet'); const worksheet3 = workbook.getWorksheet(1); -const sheet = workbook.addWorksheet('My Sheet', {views: [{showGridLines: false}]}); +const sheet1 = workbook.addWorksheet('My Sheet', { + pageSetup: { fitToPage: true, fitToHeight: 5, fitToWidth: 7 }, + properties: { tabColor: { argb: 'FFC0000' } }, +}); +const sheet2 = workbook.addWorksheet('My Sheet', { + pageSetup: { paperSize: 9, orientation: 'landscape' }, + views: [ + { state: 'frozen', xSplit: 1, ySplit: 1 }, + { state: 'normal', showGridLines: false }, + { state: 'split', activePane: 'bottomLeft', } + ] +}); + +worksheet.properties.outlineLevelCol = 2; +worksheet.properties.defaultRowHeight = 15; + +worksheet.pageSetup.margins = { + left: 0.7, right: 0.7, + top: 0.75, bottom: 0.75, + header: 0.3, footer: 0.3 +}; + +worksheet.pageSetup.printArea = 'A1:G20'; +worksheet.pageSetup.printTitlesRow = '1:3'; + +worksheet.views = [ + { state: 'frozen', xSplit: 2, ySplit: 3, topLeftCell: 'G10', activeCell: 'A1' }, + { state: 'split', xSplit: 2000, ySplit: 3000, topLeftCell: 'G10', activeCell: 'A1' }, +]; + +worksheet.autoFilter = { from: 'A1', to: 'C1' }; +worksheet.autoFilter = { from: { row: 3, column: 1 }, to: { row: 5, column: 12 } }; +worksheet.autoFilter = { from: 'D3', to: { row: 7, column: 5 } }; + +worksheet.columns = [ + { header: 'Id', key: 'id', width: 10 }, + { header: 'Name', key: 'name', width: 32 }, + { header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 } +]; + +const idCol = worksheet.getColumn('id'); +const nameCol = worksheet.getColumn('B'); +const dobCol = worksheet.getColumn(3); + +dobCol.header = 'Date of Birth'; +dobCol.header = ['Date of Birth', 'A.K.A. D.O.B.']; +dobCol.key = 'dob'; +dobCol.width = 15; +dobCol.hidden = true; +worksheet.getColumn(4).outlineLevel = 0; +const cl1 = worksheet.getColumn(4).collapsed; + +dobCol.eachCell((cell, rowNumber) => null); + +dobCol.eachCell({ includeEmpty: true }, (cell, rowNumber) => null); + +worksheet.spliceColumns(3, 2); + +const newCol3Values = [1, 2, 3, 4, 5]; +const newCol4Values = ['one', 'two', 'three', 'four', 'five']; +worksheet.spliceColumns(3, 1, newCol3Values, newCol4Values); + +worksheet.addRow({ id: 1, name: 'John Doe', dob: new Date(1970, 1, 1) }); +worksheet.addRow({ id: 2, name: 'Jane Doe', dob: new Date(1965, 1, 7) }); +worksheet.addRow([3, 'Sam', new Date()]); +const rowValues = []; +rowValues[1] = 4; +rowValues[5] = 'Kyle'; +rowValues[9] = new Date(); +worksheet.addRow(rowValues); +const rows = [ + [5, 'Bob', new Date()], + { id: 6, name: 'Barbara', dob: new Date() }, +]; +worksheet.addRows(rows); + +const row = worksheet.getRow(5); +const row1 = worksheet.lastRow; + +row.height = 42.5; +row.hidden = true; +worksheet.getRow(4).outlineLevel = 0; +worksheet.getRow(5).outlineLevel = 1; +worksheet.getRow(4).collapsed; -const row: Excel.Row = worksheet.addRow([3, 'Sam', new Date()]); row.getCell(1).value = 5; +row.getCell('name').value = 'Zeb'; +row.getCell('C').value = new Date(); -worksheet.eachRow((row: Excel.Row, rowNumber: number): void => { - // nothing -}); +const row2 = worksheet.getRow(4).values; -row.eachCell((cell: Excel.Cell, colNumber: number): void => { - // nothing -}); +row.values = [1, 2, 3]; + +const values = []; +values[5] = 7; +values[10] = 'Hello, World!'; +row.values = values; + +row.values = { id: 13, name: 'Thing 1', dob: new Date() }; + +worksheet.eachRow((row, rowNumber) => null); +worksheet.eachRow({ includeEmpty: true }, (row, rowNumber) => null); + +row.eachCell((cell, colNumber) => null); +row.eachCell({ includeEmpty: true }, (cell, colNumber) => null); + +worksheet.spliceRows(4, 3); + +const newRow3Values = [1, 2, 3, 4, 5]; +const newRow4Values = ['one', 'two', 'three', 'four', 'five']; +worksheet.spliceRows(3, 1, newRow3Values, newRow4Values); + +row.splice(3, 2); + +row.splice(4, 1, 'new value 1', 'new value 2'); + +row.commit(); + +const rowSize = row.cellCount; +const numValues = row.actualCellCount; + +worksheet.getCell('C3').value = new Date(1968, 5, 1); +const isDate = worksheet.getCell('C3').type === Excel.ValueType.Date; worksheet.mergeCells('A4:B5'); -worksheet.getCell('A1').numFmt = '0.00%'; -worksheet.getCell('A1').font = { - name: 'Comic Sans MS', - family: 4, - size: 16, - underline: true, - bold: true +worksheet.getCell('B5').value = 'Hello, World!'; +const master = worksheet.getCell('B5').master === worksheet.getCell('A4'); + +worksheet.unMergeCells('A4'); + +worksheet.mergeCells('G10', 'H11'); +worksheet.mergeCells(10, 11, 12, 13); + +worksheet.getCell('A1').name = 'PI'; +worksheet.getCell('A1').names = ['thing1', 'thing2']; +worksheet.getCell('A1').removeName('thing1'); + +worksheet.getCell('A1').dataValidation = { + type: 'list', + allowBlank: true, + formulae: ['"One,Two,Three,Four"'] }; +worksheet.getCell('A1').dataValidation = { + type: 'list', + allowBlank: true, + formulae: ['$D$5:$F$5'] +}; + +worksheet.getCell('A1').dataValidation = { + type: 'whole', + operator: 'notEqual', + showErrorMessage: true, + formulae: [5], + errorStyle: 'error', + errorTitle: 'Five', + error: 'The value must not be Five' +}; + +worksheet.getCell('A1').dataValidation = { + type: 'decimal', + operator: 'between', + allowBlank: true, + showInputMessage: true, + formulae: [1.5, 7], + promptTitle: 'Decimal', + prompt: 'The value must between 1.5 and 7' +}; + +worksheet.getCell('A1').dataValidation = { + type: 'textLength', + operator: 'lessThan', + showErrorMessage: true, + allowBlank: true, + formulae: [15] +}; + +worksheet.getCell('A1').dataValidation = { + type: 'date', + operator: 'lessThan', + showErrorMessage: true, + allowBlank: true, + formulae: [new Date(2016, 0, 1)] +}; + +worksheet.getCell('A1').value = null; +worksheet.getCell('A1').value = 5; +worksheet.getCell('A2').value = 3.14159; +worksheet.getCell('A1').value = 'Hello, World!'; +worksheet.getCell('A1').value = new Date(2017, 2, 15); +worksheet.getCell('A1').value = { text: 'www.mylink.com', hyperlink: 'http://www.mylink.com' }; +worksheet.getCell('A1').value = { text: 'Sheet2', hyperlink: '#\\"Sheet2\\"!A1' }; +worksheet.getCell('A3').value = { formula: 'A1+A2', result: 7 }; +worksheet.getCell('B3').value = { sharedFormula: 'A3', result: 10 }; +worksheet.getCell('A1').value = true; +worksheet.getCell('A2').value = false; +worksheet.getCell('A1').value = { error: '#N/A' }; +worksheet.getCell('A2').value = { error: '#VALUE!' }; +worksheet.getCell('A1').value = { + richText: [ + { text: 'This is ' }, + { font: { italic: true }, text: 'italic' } + ], +}; +worksheet.getCell('A3').formula === 'A1+A2'; +worksheet.getCell('A3').result === 7; + +const isMaster = worksheet.getCell('A3').formulaType === Excel.FormulaType.Master; +const isShared = worksheet.getCell('B3').formulaType === Excel.FormulaType.Shared; + +worksheet.getCell('A1').numFmt = '0.00%'; +worksheet.columns = [ + { header: 'Id', key: 'id', width: 10 }, + { header: 'Name', key: 'name', width: 32, style: { font: { name: 'Arial Black' } } }, + { header: 'D.O.B.', key: 'DOB', width: 10, style: { numFmt: 'dd/mm/yyyy' } } +]; + +worksheet.getColumn(3).numFmt = '"£"#,##0.00;[Red]\-"£"#,##0.00'; + +worksheet.getRow(2).font = { + name: 'Comic Sans MS', + family: 4, + size: 16, + underline: 'double', + bold: true, +}; + +worksheet.getCell('A1').numFmt = '# ?/?'; +worksheet.getCell('B1').numFmt = '0.00%'; + +worksheet.getCell('A1').font = { + name: 'Comic Sans MS', + family: 4, + size: 16, + underline: true, + bold: true +}; + +worksheet.getCell('A2').font = { + name: 'Arial Black', + color: { argb: 'FF00FF00' }, + family: 2, + size: 14, + italic: true +}; + +const font = { name: 'Arial', size: 12 }; +worksheet.getCell('A3').font = font; +font.size = 20; + worksheet.getCell('A1').alignment = { vertical: 'top', horizontal: 'left' }; worksheet.getCell('B1').alignment = { vertical: 'middle', horizontal: 'center' }; worksheet.getCell('C1').alignment = { vertical: 'bottom', horizontal: 'right' }; worksheet.getCell('D1').alignment = { wrapText: true }; worksheet.getCell('E1').alignment = { indent: 1 }; +worksheet.getCell('F1').alignment = { textRotation: 30 }; +worksheet.getCell('G1').alignment = { textRotation: -45 }; +worksheet.getCell('H1').alignment = { textRotation: 'vertical' }; worksheet.getCell('A1').border = { - top: {style: 'thin'}, - left: {style: 'thin'}, - bottom: {style: 'thin'}, - right: {style: 'thin'} + top: { style: 'thin' }, + left: { style: 'thin' }, + bottom: { style: 'thin' }, + right: { style: 'thin' } }; worksheet.getCell('A3').border = { - top: {style: 'double', color: {argb: 'FF00FF00'}}, - left: {style: 'double', color: {argb: 'FF00FF00'}}, - bottom: {style: 'double', color: {argb: 'FF00FF00'}}, - right: {style: 'double', color: {argb: 'FF00FF00'}} + top: { style: 'double', color: { argb: 'FF00FF00' } }, + left: { style: 'double', color: { argb: 'FF00FF00' } }, + bottom: { style: 'double', color: { argb: 'FF00FF00' } }, + right: { style: 'double', color: { argb: 'FF00FF00' } } +}; + +worksheet.getCell('A5').border = { + diagonal: { up: true, down: true, style: 'thick', color: { argb: 'FFFF0000' } } }; worksheet.getCell('A1').fill = { - type: 'pattern', - pattern: 'solid', - fgColor: {argb: 'FFFF0000'} + type: 'pattern', + pattern: 'darkVertical', + fgColor: { argb: 'FFFF0000' } }; -workbook.xlsx.readFile("/home/john/bla.xlsx") - .then((): void => { - // use workbook - }); +worksheet.getCell('A2').fill = { + type: 'pattern', + pattern: 'darkTrellis', + fgColor: { argb: 'FFFFFF00' }, + bgColor: { argb: 'FF0000FF' } +}; -workbook.xlsx.writeFile("/home/john/bla.xlsx") - .then((): void => { - // done - }); +worksheet.getCell('A3').fill = { + type: 'gradient', + gradient: 'angle', + degree: 0, + stops: [ + { position: 0, color: { argb: 'FF0000FF' } }, + { position: 0.5, color: { argb: 'FFFFFFFF' } }, + { position: 1, color: { argb: 'FF0000FF' } } + ] +}; + +worksheet.getCell('A2').fill = { + type: 'gradient', + gradient: 'path', + center: { left: 0.5, top: 0.5 }, + stops: [ + { position: 0, color: { argb: 'FFFF0000' } }, + { position: 1, color: { argb: 'FF00FF00' } } + ] +}; + +worksheet.getCell('A1').value = { + richText: [ + { + text: 'This is ', + font: { name: 'Calibri', size: 12, color: { theme: 0 }, family: 2, scheme: 'minor' }, + }, + { + text: 'a', + font: { italic: true, size: 12, color: { theme: 0 }, name: 'Calibri', scheme: 'minor' }, + }, + { + text: ' ', + font: { size: 12, color: { theme: 1 }, name: 'Calibri', family: 2, scheme: 'minor' }, + }, + { + text: 'colorful', + font: { size: 12, color: { argb: 'FFFF6600' }, name: 'Calibri', scheme: 'minor' }, + }, + { + text: ' text ', + font: { size: 12, color: { theme: 1 }, name: 'Calibri', family: 2, scheme: 'minor' }, + }, + { + text: 'with', + font: { size: 12, color: { argb: 'FFCCFFCC' }, name: 'Calibri', scheme: 'minor' }, + }, + { + text: ' in-cell ', + font: { size: 12, color: { theme: 1 }, name: 'Calibri', family: 2, scheme: 'minor' }, + }, + { + text: 'format', + font: { bold: true, size: 12, name: 'Calibri', family: 2, scheme: 'minor' }, + } + ] +}; + +worksheet.columns = [ + { header: 'Id', key: 'id', width: 10 }, + { header: 'Name', key: 'name', width: 32 }, + { header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 } +]; +worksheet.getColumn(3).outlineLevel = 1; +worksheet.getRow(3).outlineLevel = 1; +worksheet.properties.outlineLevelCol = 1; +worksheet.properties.outlineLevelRow = 1; + +const imageId1 = workbook.addImage({ + filename: 'path/to/image.jpg', + extension: 'jpeg', +}); +const imageId2 = workbook.addImage({ + buffer: fs.readFileSync('path/to.image.png'), + extension: 'png', +}); + +worksheet.addBackgroundImage(imageId1); +worksheet.addImage(imageId2, 'B2:D6'); +worksheet.addImage(imageId2, { + tl: { col: 1.5, row: 1.5 }, + br: { col: 3.5, row: 5.5 } +}); + +workbook.xlsx.readFile('./1.xlsx').then(() => null); +(new stream.Stream()).pipe(workbook.xlsx.createInputStream()); + +workbook.xlsx.writeFile('./1.xlsx').then(() => null); +workbook.xlsx.write(new stream.Stream()).then(() => null); + +workbook.csv.readFile('./1.xlsx').then(worksheet => null); +workbook.csv.read(new stream.Stream()).then(worksheet => null); + +(new stream.Stream()).pipe(workbook.csv.createInputStream()); + +const options1 = { dateFormats: ['DD/MM/YYYY'] }; +workbook.csv.readFile('./1.xlsx', options1).then(worksheet => null); + +const options2 = { + map(value: any, index: number) { + switch (index) { + case 0: + // column 1 is string + return value; + case 1: + // column 2 is a date + return new Date(value); + case 2: + // column 3 is JSON of a formula value + return JSON.parse(value); + default: + // the rest are numbers + return parseFloat(value); + } + } +}; +workbook.csv.readFile('./1.xlsx', options2).then(worksheet => null); + +workbook.csv.writeFile('./1.xlsx').then(() => null); + +// write to a stream +workbook.csv.write(new stream.Stream()).then(() => null); + +const workbookWriter = new Excel.stream.xlsx.WorkbookWriter({ + filename: './streamed-workbook.xlsx', + useStyles: true, + useSharedStrings: true +}); + +worksheet.addRow({ + id: 'i', + name: 'theName', + etc: 'someOtherDetail' +}).commit(); + +worksheet.mergeCells('A1:B2'); +worksheet.getCell('A1').value = 'I am merged'; +worksheet.getCell('C1').value = 'I am not'; +worksheet.getCell('C2').value = 'Neither am I'; +worksheet.getRow(2).commit(); + +worksheet.commit(); + +workbook.commit().then(() => null); + +Excel.config.setValue('promise', Bluebird); diff --git a/types/exceljs/index.d.ts b/types/exceljs/index.d.ts index 259eaccae1..be82b7d7f9 100644 --- a/types/exceljs/index.d.ts +++ b/types/exceljs/index.d.ts @@ -1,7 +1,353 @@ -// Type definitions for exceljs 0.4 +// Type definitions for exceljs 0.5 // Project: https://github.com/guyonroche/exceljs // Definitions by: Rogier Schouten +// Ali Taheri Moghaddar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Writable, Stream } from 'stream'; + +export const enum RelationshipType { + None = 0, + OfficeDocument = 1, + Worksheet = 2, + CalcChain = 3, + SharedStrings = 4, + Styles = 5, + Theme = 6, + Hyperlink = 7 +} + +export const enum DocumentType { + Xlsx = 1 +} + +export const enum PaperSize { + Legal = 5, + Executive = 7, + A4 = 9, + A5 = 11, + B5 = 13, + Envelope_10 = 20, + Envelope_DL = 27, + Envelope_C5 = 28, + Envelope_B5 = 34, + Envelope_Monarch = 37, + Double_Japan_Postcard_Rotated = 82, + K16_197x273_mm = 119, +} + +export interface WorksheetViewCommon { + /** + * Sets the worksheet view's orientation to right-to-left, `false` by default + */ + rightToLeft?: boolean; + + /** + * The currently selected cell + */ + activeCell?: string; + + /** + * Shows or hides the ruler in Page Layout, `true` by default + */ + showRuler?: boolean; + + /** + * Shows or hides the row and column headers (e.g. A1, B1 at the top and 1,2,3 on the left, + * `true` by default + */ + showRowColHeaders?: boolean; + + /** + * Shows or hides the gridlines (shown for cells where borders have not been defined), + * `true` by default + */ + showGridLines?: boolean; + + /** + * Percentage zoom to use for the view, `100` by default + */ + zoomScale?: number; + + /** + * Normal zoom for the view, `100` by default + */ + zoomScaleNormal?: number; +} + +export interface WorksheetViewNormal { + /** + * Controls the view state + */ + state?: 'normal'; + + /** + * Presentation style + */ + style?: 'pageBreakPreview' | 'pageLayout'; +} + +export interface WorksheetViewFrozen { + /** + * Where a number of rows and columns to the top and left are frozen in place. + * Only the bottom left section will scroll + */ + state: 'frozen'; + + /** + * Presentation style + */ + style?: 'pageBreakPreview'; + + /** + * How many columns to freeze. To freeze rows only, set this to 0 or undefined + */ + xSplit?: number; + + /** + * How many rows to freeze. To freeze columns only, set this to 0 or undefined + */ + ySplit?: number; + + /** + * Which cell will be top-left in the bottom-right pane. Note: cannot be a frozen cell. + * Defaults to first unfrozen cell + */ + topLeftCell?: string; +} + +export interface WorksheetViewSplit { + /** + * Where the view is split into 4 sections, each semi-independently scrollable. + */ + state: 'split'; + + /** + * Presentation style + */ + style?: 'pageBreakPreview' | 'pageLayout'; + + /** + * How many points from the left to place the splitter. + * To split vertically, set this to 0 or undefined + */ + xSplit?: number; + + /** + * How many points from the top to place the splitter. + * To split horizontally, set this to 0 or undefined + */ + ySplit?: number; + + /** + * Which cell will be top-left in the bottom-right pane + */ + topLeftCell?: string; + + /** + * Which pane will be active + */ + activePane?: 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight'; +} + +export type WorksheetView = + & WorksheetViewCommon + & (WorksheetViewNormal | WorksheetViewFrozen | WorksheetViewSplit); + +export interface WorkbookView { + x?: number; + y?: number; + width?: number; + height?: number; + firstSheet?: number; + activeTab?: number; + visibility?: string; +} + +export type FillPatterns = + | 'none' | 'solid' + | 'darkVertical' | 'darkHorizontal' | 'darkGrid' | 'darkTrellis' | 'darkDown' | 'darkUp' + | 'lightVertical' | 'lightHorizontal' | 'lightGrid' | 'lightTrellis' | 'lightDown' | 'lightUp' + | 'darkGray' | 'mediumGray' | 'lightGray' | 'gray125' | 'gray0625'; + +export interface FillPattern { + type: 'pattern'; + pattern: FillPatterns; + fgColor?: Color; + bgColor?: Color; +} + +export interface GradientStop { + position: number; + color: Color; +} + +export interface FillGradientAngle { + type: 'gradient'; + gradient: 'angle'; + + /** + * For 'angle' gradient, specifies the direction of the gradient. 0 is from the left to the right. + * Values from 1 - 359 rotates the direction clockwise + */ + degree: number; + + /** + * Specifies the gradient colour sequence. Is an array of objects containing position and + * color starting with position 0 and ending with position 1. + * Intermediary positions may be used to specify other colours on the path. + */ + stops: GradientStop[]; +} + +export interface FillGradientPath { + type: 'gradient'; + gradient: 'path'; + + /** + * For 'path' gradient. Specifies the relative coordinates for the start of the path. + * 'left' and 'top' values range from 0 to 1 + */ + center: { left: number; top: number }; + + /** + * Specifies the gradient colour sequence. Is an array of objects containing position and + * color starting with position 0 and ending with position 1. + * Intermediary positions may be used to specify other colours on the path. + */ + stops: GradientStop[]; +} + +export type Fill = FillPattern | FillGradientAngle | FillGradientPath; + +export interface Font { + name?: string; + size?: number; + family?: number; + scheme?: 'minor' | 'major' | 'none'; + charset?: number; + color?: Color; + bold?: boolean; + italic?: boolean; + underline?: boolean | 'none' | 'single' | 'double' | 'singleAccounting' | 'doubleAccounting'; + strike?: boolean; + outline?: boolean; +} + +export type BorderStyle = + | 'thin' | 'dotted' | 'hair' | 'medium' | 'double' | 'thick' | 'dashDot' + | 'dashDotDot' | 'slantDashDot' | 'mediumDashed' | 'mediumDashDotDot' | 'mediumDashDot'; + +export interface Color { + /** + * Hex string for alpha-red-green-blue e.g. FF00FF00 + */ + argb?: string; + + /** + * Choose a theme by index + */ + theme?: number; +} + +export interface Border { + style?: BorderStyle; + color?: Color; +} + +export interface BorderDiagonal extends Border { + up?: boolean; + down?: boolean; +} + +export interface Borders { + top?: Border; + left?: Border; + bottom?: Border; + right?: Border; + diagonal?: BorderDiagonal; +} + +export interface Margins { + top?: number; + left?: number; + bottom?: number; + right?: number; + header?: number; + footer?: number; +} + +export const enum ReadingOrder { + LeftToRight = 1, + RightToLeft = 2, +} + +export interface Alignment { + horizontal?: 'left' | 'center' | 'right' | 'fill' | 'justify' | 'centerContinuous' | 'distributed'; + vertical?: 'top' | 'middle' | 'bottom' | 'distributed' | 'justify'; + wrapText?: boolean; + indent?: number; + readingOrder?: 'rtl' | 'ltr'; + textRotation?: number | 'vertical'; +} + +export interface Style { + numFmt?: string; + font?: Font; + alignment?: Alignment; + border?: Borders; + fill?: Fill; +} + +export type DataValidationOperator = + | 'between' | 'notBetween' | 'equal' | 'notEqual' | 'greaterThan' | 'lessThan' + | 'greaterThanOrEqual' | 'lessThanOrEqual'; + +export interface DataValidation { + type: 'list' | 'whole' | 'decimal' | 'date' | 'textLength' | 'custom'; + formulae: any[]; + allowBlank?: boolean; + operator?: DataValidationOperator; + error?: string; + errorTitle?: string; + errorStyle?: string; + prompt?: string; + promptTitle?: string; + showErrorMessage?: boolean; + showInputMessage?: boolean; +} + +export interface CellErrorValue { + error: '#N/A' | '#REF!' | '#NAME?' | '#DIV/0!' | '#NULL!' | '#VALUE!' | '#NUM!'; +} + +export interface RichText { + text: string; + font?: Font; +} + +export interface CellRichTextValue { + richText: RichText[]; +} + +export interface CellHyperlinkValue { + text: string; + hyperlink: string; +} + +export interface CellFormulaValue { + formula: string; + result: number | string | Date; +} + +export interface CellSharedFormulaValue { + sharedFormula: string; + readonly formula?: string; + result: number | string | Date; +} export const enum ValueType { Null = 0, @@ -23,170 +369,449 @@ export const enum FormulaType { Shared = 2 } -export const enum RelationshipType { - None = 0, - OfficeDocument = 1, - Worksheet = 2, - CalcChain = 3, - SharedStrings = 4, - Styles = 5, - Theme = 6, - Hyperlink = 7 -} +export type CellValue = + | null | number | string | boolean | Date + | CellErrorValue + | CellRichTextValue | CellHyperlinkValue + | CellFormulaValue | CellSharedFormulaValue; -export const enum DocumentType { - Xlsx = 1 -} - -export const enum ReadingOrder { - RightToLeft = 1, - LeftToRight = 2, -} - -export interface ErrorValue { - error: "#N/A" | "#REF!" | "#NAME?" | "#DIV/0!" | "#NULL!" | "#VALUE!" | "#NUM!"; -} - -export interface WorksheetView { - state?: "normal" | "split" | "frozen"; - showRuler?: boolean; - showRowColHeaders?: boolean; - showGridLines?: boolean; - zoomScale?: number; - zoomScaleNormal?: number; - style?: "pageBreakPreview" | "pageLayout"; -} - -export interface WorkbookView { - x?: number; - y?: number; - width?: number; - height?: number; - firstSheet?: number; - activeTab?: number; - visibility?: string; -} - -export interface Fill { - type: "pattern" | "gradient"; - pattern?: "none" | "solid"; - fgColor?: Color; - bgColor?: Color; -} - -export interface Font { - name: string; - size?: number; - family?: number; - schema?: "minor" | "major" | "none"; - charset?: number; - color?: Color; - bold?: boolean; - italic?: boolean; - underline?: true | false | "none" | "single" | "double" | "singleAccounting" | "doubleAccounting"; - strike?: boolean; - outline?: boolean; -} - -export type BorderStyle = - "thin" | "dotted" | "dashDot" | "hair" | "dashDotDot" | "slantDashDot" | "mediumDashed" | "mediumDashDotDot" | - "mediumDashDot" | "medium" | "double" | "thick"; - -export interface Color { +export interface Cell extends Style { /** - * Hex string for alpha-red-green-blue e.g. FF00FF00 + * Assign (or get) a name for a cell (will overwrite any other names that cell had) */ - argb: string; -} + name?: string; -export interface Border { - style?: BorderStyle; - color?: Color; -} - -export interface Borders { - top?: Border; - left?: Border; - bottom?: Border; - right?: Border; -} - -export interface Alignment { - horizontal?: "left" | "center" | "right" | "fill" | "justify" | "centerContinuous" | "distributed"; - vertical?: "top" | "middle" | "bottom" | "distributed" | "justify"; - wrapText?: boolean; - indent?: number; - readingOrder?: "rtl" | "ltr"; - textrotation?: number | "vertical"; -} - -export interface Cell { - border?: Borders; - font?: Font; - alignment?: Alignment; - numFmt?: string; - value?: any; - fill?: Fill; -} - -export interface Row { /** - * The row number + * Assign (or get) an array of names for a cell (cells can have more than one name) + */ + names?: string[]; + + /** + * Cells can define what values are valid or not and provide + * prompting to the user to help guide them. + */ + dataValidation?: DataValidation; + + /** + * Value of the cell + */ + value: CellValue; + + /** + * convenience getter to access the formula + */ + readonly formula: string; + + /** + * convenience getter to access the formula result + */ + readonly result: number | string | Date; + + /** + * The type of the cell's value + */ + readonly type: ValueType; + + /** + * The type of the cell's formula + */ + readonly formulaType: FormulaType; + + /** + * The master cell when the current cell is a merge cell + */ + master?: Cell; + + /** + * The styles of the cell + */ + style: Style; + + /** + * Remove a name from a cell + */ + removeName(name: string): void; +} + +export interface Row extends Style { + /** + * Set a specific row height */ - number: number; height: number; + + /** + * Make row hidden + */ hidden: boolean; - collapsed: boolean; - values: any[]; + + /** + * Get a row as a sparse array + */ + values: any[] | any; + + /** + * Set an outline level for rows + */ outlineLevel?: number; + /** + * Indicate the collapsed state based on outlineLevel + */ + readonly collapsed: boolean; + + /** + * Number of non-empty cells + */ readonly cellCount: number; + + /** + * Number of cells including empty ones + */ readonly actualCellCount: number; - getCell(index: number): Cell; + /** + * Get cell by number, column letter or column key + */ + getCell(indexOrKey: number | string): Cell; + /** + * Iterate over all non-null cells in a row + */ eachCell(callback: (cell: Cell, colNumber: number) => void): void; - eachCell(opts: { includeEmpty: boolean}, callback: (cell: Cell, colNumber: number) => void): void; + + /** + * Iterate over all cells in a row (including empty cells) + */ + eachCell(opt: { includeEmpty: boolean }, callback: (cell: Cell, colNumber: number) => void): void; + + /** + * Cut one or more cells (cells to the right are shifted left) + * + * Note: this operation will not affect other rows + */ + splice(start: number, count: number, ...insert: any[]): void; + + /** + * Commit a completed row to stream + */ + commit(): void; } export interface Column { + /** + * Can be a string to set one row high header or an array to set multi-row high header + */ + header: string | string[]; + + /** + * The name of the properties associated with this column in each row + */ + key: string; + + /** + * The width of the column + */ width: number; + + /** + * Set an outline level for columns + */ + outlineLevel?: number; + + /** + * Hides the column + */ + hidden?: boolean; + + /** + * Styles applied to the column + */ + style?: Style; +} + +export interface ColumnExtension extends Style { + /** + * indicate the collapsed state based on outlineLevel + */ + readonly collapsed: boolean; + + /** + * Iterate over all current cells in this column + */ + eachCell(callback: (cell: Cell, rowNumber: number) => void): void; + + /** + * Iterate over all current cells in this column including empty cells + */ + eachCell(opt: { includeEmpty: boolean }, callback: (cell: Cell, rowNumber: number) => void): void; +} + +export interface PageSetup { + /** + * Whitespace on the borders of the page. Units are inches. + */ + margins?: Margins; + + /** + * Orientation of the page - i.e. taller (`'portrait'`) or wider (`'landscape'`). + * + * `'portrait'` by default + */ + orientation?: 'portrait' | 'landscape'; + + /** + * Horizontal Dots per Inch. Default value is 4294967295 + */ + horizontalDpi?: number; + + /** + * Vertical Dots per Inch. Default value is 4294967295 + */ + verticalDpi?: number; + + /** + * Whether to use fitToWidth and fitToHeight or scale settings. + * + * Default is based on presence of these settings in the pageSetup object - if both are present, + * scale wins (i.e. default will be false) + */ + fitToPage?: boolean; + + /** + * How many pages wide the sheet should print on to. Active when fitToPage is true + * + * Default is 1 + */ + fitToWidth?: number; + + /** + * How many pages high the sheet should print on to. Active when fitToPage is true + * + * Default is 1 + */ + fitToHeight?: number; + + /** + * Percentage value to increase or reduce the size of the print. Active when fitToPage is false + * + * Default is 100 + */ + scale?: number; + + /** + * Which order to print the pages. + * + * Default is `downThenOver` + */ + pageOrder?: 'downThenOver' | 'overThenDown'; + + /** + * Print without colour + * + * false by default + */ + blackAndWhite?: boolean; + + /** + * Print with less quality (and ink) + * + * false by default + */ + draft?: boolean; + + /** + * Where to place comments + * + * Default is `None` + */ + cellComments?: 'atEnd' | 'asDisplayed' | 'None'; + + /** + * Where to show errors + * + * Default is `displayed` + */ + errors?: 'dash' | 'blank' | 'NA' | 'displayed'; + + /** + * What paper size to use (see below) + * + * | Name | Value | + * | ----------------------------- | --------- | + * | Letter | `undefined` | + * | Legal | `5` | + * | Executive | `7` | + * | A4 | `9` | + * | A5 | `11` | + * | B5 (JIS) | `13` | + * | Envelope #10 | `20` | + * | Envelope DL | `27` | + * | Envelope C5 | `28` | + * | Envelope B5 | `34` | + * | Envelope Monarch | `37` | + * | Double Japan Postcard Rotated | `82` | + * | 16K 197x273 mm | `119` | + */ + paperSize?: PaperSize; + + /** + * Whether to show the row numbers and column letters, `false` by default + */ + showRowColHeaders?: boolean; + + /** + * Whether to show grid lines, `false` by default + */ + showGridLines?: boolean; + + /** + * Which number to use for the first page + */ + firstPageNumber?: number; + + /** + * Whether to center the sheet data horizontally, `false` by default + */ + horizontalCentered?: boolean; + + /** + * Whether to center the sheet data vertically, `false` by default + */ + verticalCentered?: boolean; + + /** + * Set Print Area for a sheet, e.g. `'A1:G20'` + */ + printArea?: string; + + /** + * Repeat specific rows on every printed page, e.g. `'1:3'` + */ + printTitlesRow?: string; +} + +export type AutoFilter = string | { + from: string | { row: number; column: number }; + to: string | { row: number; column: number }; +}; + +export interface Image { + extension: 'jpeg' | 'png' | 'gif'; + filename?: string; + buffer?: Buffer; +} + +export interface ImageRange { + tl: { col: number; row: number }; + br: { col: number; row: number }; } export interface Worksheet { + /** + * Contains information related to how a worksheet is printed + */ + pageSetup: PageSetup; + + /** + * Worksheet Properties + */ + properties: WorksheetProperties; + + /** + * Open panes representing the sheet + */ + views: WorksheetView[]; + + /** + * Apply an auto filter to your worksheet. + */ + autoFilter?: AutoFilter; + + /** + * Add column headers and define column keys and widths. + * + * Note: these column structures are a workbook-building convenience only, + * apart from the column width, they will not be fully persisted. + */ + columns?: Column[]; + /** * The total row size of the document. Equal to the row number of the last row that has values. */ - rowCount: number; + readonly rowCount: number; + /** * A count of the number of rows that have values. If a mid-document row is empty, it will not be included in the count. */ - actualRowCount: number; + readonly actualRowCount: number; + /** * The total column size of the document. Equal to the maximum cell count from all of the rows */ - columnCount: number; + readonly columnCount: number; + /** * A count of the number of columns that have values. */ - actualColumnCount: number; + readonly actualColumnCount: number; /** - * Get or create a column + * Get the last editable row in a worksheet (or undefined if there are none) */ - getColumn(index: number): Column; + readonly lastRow: Row | undefined; /** - * Create a new row + * Access an individual columns by key, letter and 1-based column number */ - addRow(data: any[]): Row; + getColumn(indexOrKey: number | string): Column & ColumnExtension; + + /** + * Cut one or more columns (columns to the right are shifted left) + * and optionally insert more + * + * If column properties have been definde, they will be cut or moved accordingly + * + * Known Issue: If a splice causes any merged cells to move, the results may be unpredictable + * + * Also: If the worksheet has more rows than values in the colulmn inserts, + * the rows will still be shifted as if the values existed + */ + spliceColumns(start: number, count: number, ...insert: any[][]): void; + + /** + * Cut one or more rows (rows below are shifted up) + * and optionally insert more + * + * Known Issue: If a splice causes any merged cells to move, the results may be unpredictable + */ + spliceRows(start: number, count: number, ...insert: any[][]): void; + + /** + * Add a couple of Rows by key-value, after the last current row, using the column keys, + * or add a row by contiguous Array (assign to columns A, B & C) + */ + addRow(data: any[] | any): Row; + + /** + * Add multiple rows by providing an array of arrays or key-value pairs + */ + addRows(rows: any[]): void; /** * Get or create row by 0-based index */ getRow(index: number): Row; + + /** + * Iterate over all rows that have values in a worksheet + */ eachRow(callback: (row: Row, rowNumber: number) => void): void; + /** + * Iterate over all rows (including empty rows) in a worksheet + */ + eachRow(opt: { includeEmpty: boolean }, callback: (row: Row, rowNumber: number) => void): void; + /** * Get or create cell */ @@ -194,38 +819,222 @@ export interface Worksheet { /** * Merge cells, either: - * tlbr string - * tl string, br string - * t, l, b, r numbers + * + * tlbr string, e.g. `'A4:B5'` + * + * tl string, br string, e.g. `'G10', 'H11'` + * + * t, l, b, r numbers, e.g. `10,11,12,13` */ mergeCells(a: number | string, b?: number | string, c?: number, d?: number): void; + + /** + * unmerging the cells breaks the style links + */ + unMergeCells(cell: string): void; + + /** + * Using the image id from `Workbook.addImage`, set the background to the worksheet + */ + addBackgroundImage(imageId: string): void; + + /** + * Using the image id from `Workbook.addImage`, + * embed an image within the worksheet to cover a range + */ + addImage(imageId: string, range: string | ImageRange): void; + + /** + * Commit a completed worksheet to stream + */ + commit(): void; +} + +export interface WorksheetProperties { + /** + * Color of the tab + */ + tabColor?: Color; + + /** + * The worksheet column outline level (default: 0) + */ + outlineLevelCol?: number; + + /** + * The worksheet row outline level (default: 0) + */ + outlineLevelRow?: number; + + /** + * Default row height (default: 15) + */ + defaultRowHeight?: number; + + /** + * default: 55 + */ + dyDescent?: number; +} + +export interface AddWorksheetOptions { + properties?: WorksheetProperties; + pageSetup?: PageSetup; + views?: WorksheetView[]; +} + +export interface WorkbookProperties { + /** + * Set workbook dates to 1904 date system + */ + date1904: boolean; } export interface Xlsx { + /** + * read from a file + */ readFile(path: string): Promise; + + /** + * Create input stream for reading + */ + createInputStream(): Writable; + + /** + * write to a file + */ writeFile(path: string): Promise; + + /** + * write to a stream + */ + write(stream: Stream): Promise; } -export interface WorksheetProps { - showGridLines: boolean; +export interface CsvReadOptions { + dateFormats?: string[]; + map?(value: any, index: number): any; +} + +export interface CsvWriteOptions { + dateFormat?: string; +} + +export interface Csv { + /** + * read from a file + */ + readFile(path: string, options?: CsvReadOptions): Promise; + + /** + * read from a stream + */ + read(stream: Stream, options?: CsvReadOptions): Promise; + + /** + * Create input stream for reading + */ + createInputStream(): Writable; + + /** + * write to a file + */ + writeFile(path: string, options?: CsvWriteOptions): Promise; + + /** + * write to a stream + */ + write(stream: Stream, options?: CsvWriteOptions): Promise; } export class Workbook { - constructor(); - creator: string; lastModifiedBy: string; created: Date; modified: Date; lastPrinted: Date; - properties: { - date1904: boolean; - }; + properties: WorkbookProperties; + + /** + * xlsx file format operations + */ + readonly xlsx: Xlsx; + + /** + * csv file format operations + */ + readonly csv: Csv; + + /** + * The Workbook views controls how many separate windows Excel will open when viewing the workbook. + */ views: WorkbookView[]; - addWorksheet(name: string, opts?: { properties?: WorksheetProps, views?: WorksheetView[] }): Worksheet; + /** + * The list of worksheets added to this workbook + */ + worksheets: Worksheet[]; + /** + * Add a new worksheet and return a reference to it + */ + addWorksheet(name: string, options?: AddWorksheetOptions): Worksheet; + + /** + * fetch sheet by name or id + */ getWorksheet(indexOrName: number | string): Worksheet; - xlsx: Xlsx; + /** + * Iterate over all sheets. + * + * Note: `workbook.worksheets.forEach` will still work but this is better. + */ + eachSheet(callback: (worksheet: Worksheet, id: number) => void): void; + + /** + * Add Image to Workbook and return the id + */ + addImage(img: Image): string; + + /** + * Commit a completed workbook to stream and close the stream + */ + commit(): Promise; +} + +export namespace config { + function setValue(key: 'promise', promise: any): void; +} + +export namespace stream { + namespace xlsx { + interface WorkbookWriterOptions { + /** + * Specifies a writable stream to write the XLSX workbook to. + */ + stream?: Stream; + + /** + * If stream not specified, this field specifies the path to a file to write the XLSX workbook to. + */ + filename?: string; + + /** + * Specifies whether to use shared strings in the workbook. Default is false + */ + useSharedStrings?: boolean; + + /** + * Specifies whether to add style information to the workbook. + * Styles can add some performance overhead. Default is false + */ + useStyles?: boolean; + } + + class WorkbookWriter extends Workbook { + constructor(options: WorkbookWriterOptions); + } + } } diff --git a/types/execa/execa-tests.ts b/types/execa/execa-tests.ts index fd7428d1ae..abdbfd6dad 100644 --- a/types/execa/execa-tests.ts +++ b/types/execa/execa-tests.ts @@ -54,6 +54,15 @@ execa.shell('echo unicorns') execa('echo', ['unicorns']).stdout.pipe(process.stdout); execa('echo', ['unicorns']).stderr.pipe(process.stderr); +execa('forever', {extendEnv: false}).pid; +execa('forever', {argv0: 'hi'}).pid; +execa('forever', {localDir: '~'}).pid; +execa('forever', {reject: false}).pid; +execa('forever', {cleanup: false}).pid; +execa('forever', {stdin: 1}).pid; +execa('forever', {stdout: 'ignore'}).pid; +execa('forever', {stderr: undefined}).pid; + async () => { const { stdout } = await execa('noop', ['foo'], { stripEof: false }); assert(stdout === 'foo\n'); diff --git a/types/execa/index.d.ts b/types/execa/index.d.ts index df868e4d15..df2c0d9d83 100644 --- a/types/execa/index.d.ts +++ b/types/execa/index.d.ts @@ -1,21 +1,33 @@ -// Type definitions for execa 0.6 +// Type definitions for execa 0.7 // Project: https://github.com/sindresorhus/execa#readme // Definitions by: Douglas Duteil +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// -import { ExecOptions, SpawnOptions, SpawnSyncOptions, SpawnSyncReturns, ChildProcess } from "child_process"; +import { ChildProcess, ExecOptions, SpawnOptions, SpawnSyncOptions } from "child_process"; import { Stream } from 'stream'; +type StdIOOption = 'pipe' | 'ipc' | 'ignore' | number | Stream | undefined | null; + interface ExecaOptions { input: string | Buffer | Stream; preferLocal: boolean; stripEof: boolean; + extendEnv: boolean; + argv0: string; + localDir: string; + reject: boolean; + cleanup: boolean; + stdin: StdIOOption; + stdout: StdIOOption; + stderr: StdIOOption; } type Options = SpawnOptions & ExecaOptions & ExecOptions; +type SyncOptions = SpawnSyncOptions & ExecaOptions & ExecOptions; interface ExecaReturns { cmd: string; @@ -42,10 +54,10 @@ declare namespace execa { function stdout(file: string, args?: string[], options?: Partial): Promise; function stderr(file: string, options?: Partial): Promise; function stderr(file: string, args?: string[], options?: Partial): Promise; - function shell(command: string, options?: SpawnOptions): ExecaChildProcess; - function sync(file: string, options?: SpawnSyncOptions): ExecaReturns; - function sync(file: string, args?: string[], options?: SpawnSyncOptions): ExecaReturns; - function shellSync(command: string, options?: SpawnOptions): ExecaReturns; + function shell(command: string, options?: Partial): ExecaChildProcess; + function sync(file: string, options?: Partial): ExecaReturns; + function sync(file: string, args?: string[], options?: Partial): ExecaReturns; + function shellSync(command: string, options?: Partial): ExecaReturns; } export = execa; diff --git a/types/expect/expect-tests.ts b/types/expect/expect-tests.ts index 6238a63c60..41bdbe5581 100644 --- a/types/expect/expect-tests.ts +++ b/types/expect/expect-tests.ts @@ -1,6 +1,6 @@ /// -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', () => { diff --git a/types/express-jwt/express-jwt-tests.ts b/types/express-jwt/express-jwt-tests.ts index 190c85ce4b..798818b728 100644 --- a/types/express-jwt/express-jwt-tests.ts +++ b/types/express-jwt/express-jwt-tests.ts @@ -17,4 +17,15 @@ var jwtCheck = jwt({ secret: 'shhhhhhared-secret' }); jwtCheck.unless = unless; -app.use(jwtCheck.unless({ path: '/api/login' })); \ No newline at end of file +app.use(jwtCheck.unless({ path: '/api/login' })); + +app.use(function (err: any, req: express.Request, res: express.Response, next: express.NextFunction) { + if (err) { + if (err instanceof jwt.UnauthorizedError) { + res.status(err.status); + res.end(); + } + } else { + next(err); + } +}); \ No newline at end of file diff --git a/types/express-jwt/index.d.ts b/types/express-jwt/index.d.ts index d75dfa9adf..ec7aeb64f7 100644 --- a/types/express-jwt/index.d.ts +++ b/types/express-jwt/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for express-jwt // Project: https://www.npmjs.org/package/express-jwt -// Definitions by: Wonshik Kim , Kacper Polak +// Definitions by: Wonshik Kim , Kacper Polak , Sl1MBoy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import express = require('express'); @@ -36,6 +36,14 @@ declare namespace jwt { export interface RequestHandler extends express.RequestHandler { unless: typeof unless; } + + export class UnauthorizedError extends Error { + name: string; + message: string; + code: string; + status: number; + inner: Error + } } declare global { namespace Express { diff --git a/types/falcor-express/index.d.ts b/types/falcor-express/index.d.ts index b149df75b9..c8a65e9f6c 100644 --- a/types/falcor-express/index.d.ts +++ b/types/falcor-express/index.d.ts @@ -7,6 +7,6 @@ -import {Request, Response, Handler} from 'express'; +import { Request, Response, Handler } from 'express'; import {DataSource} from 'falcor'; declare function dataSourceRoute(getDataSource: (req: Request, res: Response) => DataSource): Handler; diff --git a/types/falcor-http-datasource/falcor-http-datasource-tests.ts b/types/falcor-http-datasource/falcor-http-datasource-tests.ts index b341274a19..e014706df1 100644 --- a/types/falcor-http-datasource/falcor-http-datasource-tests.ts +++ b/types/falcor-http-datasource/falcor-http-datasource-tests.ts @@ -1,5 +1,5 @@ import HttpDataSource from 'falcor-http-datasource'; -import {Model} from 'falcor'; +import { Model } from 'falcor'; const model = new Model({ source: new HttpDataSource('/model.json') diff --git a/types/falcor-json-graph/falcor-json-graph-tests.ts b/types/falcor-json-graph/falcor-json-graph-tests.ts index 992ede0053..1b082c4720 100644 --- a/types/falcor-json-graph/falcor-json-graph-tests.ts +++ b/types/falcor-json-graph/falcor-json-graph-tests.ts @@ -1,6 +1,6 @@ -import {Key, KeySet, Path, PathSet, ref, atom, error, pathValue, pathInvalidation} from 'falcor-json-graph'; +import { Key, KeySet, Path, PathSet, ref, atom, error, pathValue, pathInvalidation } from 'falcor-json-graph'; const stringKey: Key = "productsById"; const numberKey: Key = 10; diff --git a/types/fast-diff/fast-diff-tests.ts b/types/fast-diff/fast-diff-tests.ts new file mode 100644 index 0000000000..3177bfa7fc --- /dev/null +++ b/types/fast-diff/fast-diff-tests.ts @@ -0,0 +1,16 @@ +import fastDiff = require('fast-diff'); + +let diffs: fastDiff.Diff[]; +diffs = fastDiff("hi there", "hi"); +diffs = fastDiff("hi there", "hi", 1); + +diffs.forEach((diff: fastDiff.Diff) => { + const operation: number = diff[0]; + const text: string = diff[1]; + + switch (diff[0]) { + case fastDiff.EQUAL: break; + case fastDiff.DELETE: break; + case fastDiff.INSERT: break; + } +}); diff --git a/types/fast-diff/index.d.ts b/types/fast-diff/index.d.ts new file mode 100644 index 0000000000..1f306a6e9d --- /dev/null +++ b/types/fast-diff/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for fast-diff 1.1 +// Project: https://github.com/jhchen/fast-diff#readme +// Definitions by: John Renner +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function diff(text1: string, text2: string, cursorPos?: number): diff.Diff[]; + +declare namespace diff { + type Diff = [-1 | 0 | 1, string]; + + const DELETE: -1; + const INSERT: 1; + const EQUAL: 0; +} + +export = diff; diff --git a/types/fast-diff/tsconfig.json b/types/fast-diff/tsconfig.json new file mode 100644 index 0000000000..e89403e0ef --- /dev/null +++ b/types/fast-diff/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", + "fast-diff-tests.ts" + ] +} diff --git a/types/fast-diff/tslint.json b/types/fast-diff/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fast-diff/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/figures/figures-tests.ts b/types/figures/figures-tests.ts new file mode 100644 index 0000000000..f2c25bbe4b --- /dev/null +++ b/types/figures/figures-tests.ts @@ -0,0 +1,5 @@ +import figures = require('figures'); + +let str: string; +str = figures('✔︎ check'); +str = figures.tick; diff --git a/types/figures/index.d.ts b/types/figures/index.d.ts new file mode 100644 index 0000000000..2867326034 --- /dev/null +++ b/types/figures/index.d.ts @@ -0,0 +1,67 @@ +// Type definitions for figures 2.0 +// Project: https://github.com/sindresorhus/figures#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = figures; + +declare function figures(input: string): string; + +declare namespace figures { + const tick: string; + const cross: string; + const star: string; + const square: string; + const squareSmall: string; + const squareSmallFilled: string; + const play: string; + const circle: string; + const circleFilled: string; + const circleDotted: string; + const circleDouble: string; + const circleCircle: string; + const circleCross: string; + const circlePipe: string; + const circleQuestionMark: string; + const bullet: string; + const dot: string; + const line: string; + const ellipsis: string; + const pointer: string; + const pointerSmall: string; + const info: string; + const warning: string; + const hamburger: string; + const smiley: string; + const mustache: string; + const heart: string; + const arrowUp: string; + const arrowDown: string; + const arrowLeft: string; + const arrowRight: string; + const radioOn: string; + const radioOff: string; + const checkboxOn: string; + const checkboxOff: string; + const checkboxCircleOn: string; + const checkboxCircleOff: string; + const questionMarkPrefix: string; + const oneHalf: string; + const oneThird: string; + const oneQuarter: string; + const oneFifth: string; + const oneSixth: string; + const oneSeventh: string; + const oneEighth: string; + const oneNinth: string; + const oneTenth: string; + const twoThirds: string; + const twoFifths: string; + const threeQuarters: string; + const threeFifths: string; + const threeEighths: string; + const fourFifths: string; + const fiveSixths: string; + const fiveEighths: string; + const sevenEighth: string; +} diff --git a/types/figures/tsconfig.json b/types/figures/tsconfig.json new file mode 100644 index 0000000000..595779c25d --- /dev/null +++ b/types/figures/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", + "figures-tests.ts" + ] +} diff --git a/types/figures/tslint.json b/types/figures/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/figures/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/file-saver/file-saver-tests.ts b/types/file-saver/file-saver-tests.ts index c76815a6fb..1cc06f58ba 100644 --- a/types/file-saver/file-saver-tests.ts +++ b/types/file-saver/file-saver-tests.ts @@ -1,6 +1,6 @@ -import {saveAs as importedSaveAs} from "file-saver"; +import { saveAs as importedSaveAs } from "file-saver"; function testImportedSaveAs() { var data: Blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"}); var filename: string = 'hello world.txt'; diff --git a/types/file-type/file-type-tests.ts b/types/file-type/file-type-tests.ts index 1ce0bf6bdf..ecfd658a1a 100644 --- a/types/file-type/file-type-tests.ts +++ b/types/file-type/file-type-tests.ts @@ -1,5 +1,4 @@ -"use strict"; +import fileType = require("file-type"); -import fileType = require("file-type") - -fileType(new Buffer([0xFF, 0xD8, 0xFF])) +fileType(new Buffer([0xFF, 0xD8, 0xFF])); +fileType(new Uint8Array([0xFF, 0xD8, 0xFF])); diff --git a/types/file-type/index.d.ts b/types/file-type/index.d.ts index 3a88fe0a94..95217430eb 100644 --- a/types/file-type/index.d.ts +++ b/types/file-type/index.d.ts @@ -1,16 +1,17 @@ -// Type definitions for file-type +// Type definitions for file-type 5.2 // Project: https://github.com/sindresorhus/file-type // Definitions by: KIM Jaesuck a.k.a. gim tcaesvk -// Definitions: https://github.com/DefinitelyType/DefinitelyTyped +// BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// export = FileType; -declare function FileType(buf: Buffer): FileType.FileTypeResult; +declare function FileType(buf: Buffer | Uint8Array): FileType.FileTypeResult; declare namespace FileType { - export interface FileTypeResult { + interface FileTypeResult { ext: string; mime: string; } diff --git a/types/file-type/tslint.json b/types/file-type/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/file-type/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/filenamify/filenamify-tests.ts b/types/filenamify/filenamify-tests.ts new file mode 100644 index 0000000000..212ff424cf --- /dev/null +++ b/types/filenamify/filenamify-tests.ts @@ -0,0 +1,10 @@ +import * as filenamify from 'filenamify'; + +filenamify(''); +// => 'foo!bar' + +filenamify('foo:"bar"', {replacement: '🐴'}); +// => 'foo🐴bar' + +filenamify.path('/some/!path'); +// => '/some/path' diff --git a/types/filenamify/index.d.ts b/types/filenamify/index.d.ts new file mode 100644 index 0000000000..981b04443d --- /dev/null +++ b/types/filenamify/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for filenamify 2.0 +// Project: https://github.com/sindresorhus/filenamify +// Definitions by: Junyoung Choi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function filenamify(input: string, options?: filenamify.Options): string; + +declare namespace filenamify { + interface Options { + replacement: string; + } + function path(input: string, options?: filenamify.Options): string; +} + +export = filenamify; diff --git a/types/filenamify/tsconfig.json b/types/filenamify/tsconfig.json new file mode 100644 index 0000000000..aec1f33988 --- /dev/null +++ b/types/filenamify/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", + "filenamify-tests.ts" + ] +} diff --git a/types/filenamify/tslint.json b/types/filenamify/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/filenamify/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/finalhandler/finalhandler-tests.ts b/types/finalhandler/finalhandler-tests.ts index af3550a4f4..81b9565404 100644 --- a/types/finalhandler/finalhandler-tests.ts +++ b/types/finalhandler/finalhandler-tests.ts @@ -1,5 +1,5 @@ -import {ServerRequest, ServerResponse} from "http"; +import { ServerRequest, ServerResponse } from "http"; import * as finalHandler from "finalhandler"; let req: ServerRequest; diff --git a/types/finalhandler/index.d.ts b/types/finalhandler/index.d.ts index a238c0d2a5..baad707772 100644 --- a/types/finalhandler/index.d.ts +++ b/types/finalhandler/index.d.ts @@ -5,7 +5,7 @@ /// -import {ServerRequest, ServerResponse} from "http"; +import { ServerRequest, ServerResponse } from "http"; declare function finalHandler(req: ServerRequest, res: ServerResponse, options?: finalHandler.Options): (err: any) => void; diff --git a/types/fixed-data-table/fixed-data-table-tests.tsx b/types/fixed-data-table/fixed-data-table-tests.tsx index 96c17a4a9a..cdbd46eb6c 100644 --- a/types/fixed-data-table/fixed-data-table-tests.tsx +++ b/types/fixed-data-table/fixed-data-table-tests.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import {Table, Cell, Column, CellProps} from "fixed-data-table"; +import { Table, Cell, Column, CellProps } from "fixed-data-table"; // create your Table class MyTable1 extends React.Component { diff --git a/types/flat/flat-tests.ts b/types/flat/flat-tests.ts index 68699326c3..324ee3bb14 100644 --- a/types/flat/flat-tests.ts +++ b/types/flat/flat-tests.ts @@ -1,6 +1,6 @@ -import {flatten, unflatten} from "flat"; +import { flatten, unflatten } from "flat"; namespace TestFlatten { let options: { diff --git a/types/form-data/form-data-tests.ts b/types/form-data/form-data-tests.ts index 93457df3be..526fb5bce9 100644 --- a/types/form-data/form-data-tests.ts +++ b/types/form-data/form-data-tests.ts @@ -1,5 +1,3 @@ -/// - import FormData = require('form-data'); import fs = require('fs'); import http = require('http'); @@ -8,43 +6,45 @@ import fetch from 'node-fetch'; import * as ImportUsingES6Syntax from 'form-data'; -() => { - var form = new FormData(); +(() => { + const form = new FormData(); form.append('my_field', 'my value'); form.append('my_buffer', new Buffer(10)); form.append('my_file', fs.createReadStream('/foo/bar.jpg')); -} -() => { - var form = new FormData(); + const num: number = form.getLengthSync(); + const bool: boolean = form.hasKnownLength(); +})(); - http.request({ path: 'http://nodejs.org/images/logo.png' }, function (response) { +(() => { + const form = new FormData(); + + http.request({ path: 'http://nodejs.org/images/logo.png' }, response => { form.append('my_field', 'my value'); form.append('my_buffer', new Buffer(10)); form.append('my_logo', response); }); -} +})(); -() => { - var form = new FormData(); +(() => { + const form = new FormData(); form.append('my_field', 'my value'); form.append('my_buffer', new Buffer(10)); form.append('my_logo', request('http://nodejs.org/images/logo.png')); -} +})(); -() => { - var form = new FormData(); - form.submit('http://example.org/', function (err, res) { +(() => { + const form = new FormData(); + form.submit('http://example.org/', (err, res) => { // res – response object (http.IncomingMessage) // res.resume(); }); -} +})(); - -() => { - var form = new FormData(); - var request = http.request({ +(() => { + const form = new FormData(); + const request = http.request({ method: 'post', host: 'example.org', path: '/upload', @@ -53,89 +53,86 @@ import * as ImportUsingES6Syntax from 'form-data'; form.pipe(request); - request.on('response', function (res: any) { + request.on('response', res => { console.log(res.statusCode); }); -} +})(); - -() => { - var form = new FormData(); - form.submit('example.org/upload', function (err, res) { +(() => { + const form = new FormData(); + form.submit('example.org/upload', (err, res) => { + const r: http.IncomingMessage = res; console.log(res.statusCode); }); -} +})(); -() => { - var CRLF = '\r\n'; - var form = new FormData(); - var buffer = new Buffer(''); +(() => { + const CRLF = '\r\n'; + const form = new FormData(); + const buffer = new Buffer(''); - var options = { + const options = { header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF, knownLength: 1 }; form.append('my_buffer', buffer, options); - form.submit('http://example.com/', function (err, res) { + form.submit('http://example.com/', (err, res) => { if (err) throw err; console.log('Done'); }); -} +})(); -() => { - var form = new FormData(); +(() => { + const form = new FormData(); form.submit({ host: 'example.com', path: '/probably.php?extra=params', auth: 'username:password' - }, function (err, res) { + }, (err, res) => { console.log(res.statusCode); }); -} +})(); -() => { - var form = new FormData(); +(() => { + const form = new FormData(); form.submit({ host: 'example.com', path: '/surelynot.php', headers: { 'x-test-header': 'test-header-value' } - }, function (err, res) { + }, (err, res) => { console.log(res.statusCode); }); -} +})(); -() => { - var formData = { +(() => { + const formData = { my_field: 'my_value', my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), }; - request.post({ url: 'http://service.com/upload', formData: formData }, function (err, httpResponse, body) { + request.post({ url: 'http://service.com/upload', formData }, (err, httpResponse, body) => { if (err) { return console.error('upload failed:', err); } console.log('Upload successful! Server responded with:', body); }); -} +})(); -() => { - var form = new FormData(); +(() => { + const form = new FormData(); form.append('a', 1); fetch('http://example.com', { method: 'POST', body: form }) - .then(function (res) { - return res.json(); - }).then(function (json) { + .then(res => res.json()) + .then(json => { console.log(json); }); -} +})(); -() => { - var form = new FormData(); - form.getLength((err: Error, length: number): void => { - // nothing - }); -} +(() => { + const form = new FormData(); + form.getLength((err: Error, length: number): void => {}); +})(); diff --git a/types/form-data/index.d.ts b/types/form-data/index.d.ts index e4bd6ca2e1..9b102b287f 100644 --- a/types/form-data/index.d.ts +++ b/types/form-data/index.d.ts @@ -1,26 +1,42 @@ -// Type definitions for form-data -// Project: https://github.com/felixge/node-form-data -// Definitions by: Carlos Ballesteros Velasco , Leon Yu +// Type definitions for form-data 2.2 +// Project: https://github.com/form-data/form-data +// Definitions by: Carlos Ballesteros Velasco +// Leon Yu +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Imported from: https://github.com/soywiz/typescript-node-definitions/form-data.d.ts /// +import * as stream from 'stream'; +import * as http from 'http'; export = FormData; -import * as stream from "stream"; - declare class FormData extends stream.Readable { - append(key: string, value: any, options?: any): void; - getHeaders(): FormData.Dictionary; - submit(params: string | Object, callback: (error: any, response: any) => void): any; + append(key: string, value: any, options?: FormData.AppendOptions | string): void; + getHeaders(): FormData.Headers; + submit(params: string | FormData.SubmitOptions, callback?: (error: Error | undefined, response: http.IncomingMessage) => void): http.ClientRequest; getBoundary(): string; - getLength(callback: (err: Error, length: number) => void): void; + getLength(callback: (err: Error | undefined, length: number) => void): void; + getLengthSync(): number; + hasKnownLength(): boolean; } declare namespace FormData { - interface Dictionary { - [key: string]: T; + interface Headers { + [key: string]: any; + } + + interface AppendOptions { + header?: string | Headers; + knownLength?: number; + filename?: string; + filepath?: string; + contentType?: string; + } + + interface SubmitOptions extends http.RequestOptions { + protocol?: 'https:' | 'http:'; } } diff --git a/types/form-data/tslint.json b/types/form-data/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/form-data/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/from2/from2-tests.ts b/types/from2/from2-tests.ts new file mode 100644 index 0000000000..8ad402c2ed --- /dev/null +++ b/types/from2/from2-tests.ts @@ -0,0 +1,75 @@ +import from = require('from2'); + +function fromString(str: string) { + return from((size, next) => { + if (str.length <= 0) { + return next(null, null); + } + + const chunk = str.slice(0, size); + str = str.slice(size); + + next(null, chunk); + }); +} + +fromString('hello world').pipe(process.stdout); + +let stream: NodeJS.ReadableStream; +stream = from((size, next) => next(null, 'foo')); +stream = from((size, next) => next(null, new Buffer(1))); +stream = from((size, next) => next(null, new Uint8Array(1))); +stream = from((size, next) => next(null, null)); +stream = from(['foo', new Buffer(1), new Uint8Array(1), null]); +// following should fail: +// stream = from((size, next) => next(null, {})); + +stream = from({objectMode: false}, (size, next) => next(null, 'foo')); +stream = from({objectMode: false}, (size, next) => next(null, new Buffer(1))); +stream = from({objectMode: false}, (size, next) => next(null, new Uint8Array(1))); +stream = from({objectMode: false}, (size, next) => next(null, null)); +stream = from({objectMode: false}, ['foo', new Buffer(1), new Uint8Array(1), null]); +// following should fail: +// stream = from({objectMode: false}, (size, next) => next(null, {})); + +stream = from({highWaterMark: 1}, (size, next) => next(null, 'foo')); +stream = from({highWaterMark: 1}, (size, next) => next(null, new Buffer(1))); +stream = from({highWaterMark: 1}, (size, next) => next(null, new Uint8Array(1))); +stream = from({highWaterMark: 1}, (size, next) => next(null, null)); +stream = from({highWaterMark: 1}, ['foo', new Buffer(1), new Uint8Array(1), null]); +// following should fail: +// stream = from({highWaterMark: 1}, (size, next) => next(null, {})); + +stream = from({objectMode: true}, (size, next) => next(null, {})); +stream = from({objectMode: true}, (size, next) => next(null, null)); +stream = from({objectMode: true}, [1, 'foo', {}, null]); + +stream = from.obj((size, next) => next(null, {})); +stream = from.obj((size, next) => next(null, null)); +stream = from.obj([1, 'foo', {}, null]); + +stream = from.obj({objectMode: true}, (size, next) => next(null, {})); +stream = from.obj({objectMode: true}, (size, next) => next(null, null)); +stream = from.obj({objectMode: true}, [1, 'foo', {}, null]); +// following should fail: +// stream = from.obj({objectMode: false}, [1, 'foo', {}, null]); +stream = from.obj({highWaterMark: 1}, (size, next) => next(null, {})); +stream = from.obj({highWaterMark: 1}, (size, next) => next(null, null)); +stream = from.obj({highWaterMark: 1}, [1, 'foo', {}, null]); + +let Ctor: from.From2Ctor; +Ctor = from.ctor({objectMode: false}); +Ctor = from.ctor(); +stream = new Ctor((size, next) => next(null, 'foo')); +stream = new Ctor((size, next) => next(null, new Buffer(1))); +stream = new Ctor((size, next) => next(null, new Uint8Array(1))); +stream = new Ctor((size, next) => next(null, null)); +stream = new Ctor(['foo', new Buffer(1), new Uint8Array(1), null]); +// following should fail: +// stream = new Ctor((size, next) => next(null, {})); + +let Ctor2: from.From2Ctor; +Ctor2 = from.ctor({objectMode: true}); +stream = new Ctor2((size, next) => next(null, {})); +stream = new Ctor2((size, next) => next(null, null)); +stream = new Ctor2([1, 'foo', {}, null]); diff --git a/types/from2/index.d.ts b/types/from2/index.d.ts new file mode 100644 index 0000000000..59872471b9 --- /dev/null +++ b/types/from2/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for from2 2.3 +// Project: https://github.com/hughsk/from2 +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as stream from 'stream'; + +export = from2; + +declare function from2(read: from2.ReadInput): NodeJS.ReadableStream; +declare function from2(opts: from2.ObjectModeOptions, read: from2.ReadObjectInput): NodeJS.ReadableStream; +declare function from2(opts: from2.Options, read: from2.ReadInput): NodeJS.ReadableStream; + +declare namespace from2 { + function obj(read: ReadObjectInput): NodeJS.ReadableStream; + function obj(opts: { objectMode?: true } & stream.ReadableOptions, read: ReadObjectInput): NodeJS.ReadableStream; + + function ctor(opts?: Options): From2Ctor; + function ctor(opts: ObjectModeOptions): From2Ctor; + + type ObjectModeOptions = { objectMode: true } & stream.ReadableOptions; + type Options = { objectMode?: false } & stream.ReadableOptions; + + type From2Ctor = new(read: R) => NodeJS.ReadableStream; + + type ReadObjectInput = ReadCallback | any[]; + type ReadInput = ReadCallback | Chunk[]; + type ReadCallback = (size: number, next: N) => void; + type NextCallback = (err: any | undefined, chunk: Chunk) => void; + type NextObjectCallback = (err: any | undefined, chunk: any) => void; + type Chunk = string | Buffer | Uint8Array | null; +} diff --git a/types/from2/tsconfig.json b/types/from2/tsconfig.json new file mode 100644 index 0000000000..e632fe943f --- /dev/null +++ b/types/from2/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", + "from2-tests.ts" + ] +} diff --git a/types/from2/tslint.json b/types/from2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/from2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fs-extra-promise/fs-extra-promise-tests.ts b/types/fs-extra-promise/fs-extra-promise-tests.ts index c50115871b..30794946f3 100644 --- a/types/fs-extra-promise/fs-extra-promise-tests.ts +++ b/types/fs-extra-promise/fs-extra-promise-tests.ts @@ -15,6 +15,7 @@ let path: string; let data: any; let object: object; let buf: Buffer; +let strOrBuf: string | Buffer; let buffer: NodeBuffer; let modeNum: number; let modeStr: string; @@ -167,7 +168,7 @@ fs.readFile(filename, (err: Error, data: NodeBuffer) => { }); buffer = fs.readFileSync(filename); str = fs.readFileSync(filename, encoding); -buf = fs.readFileSync(filename, openOpts); +strOrBuf = fs.readFileSync(filename, openOpts); fs.writeFile(filename, data, errorCallback); fs.writeFile(filename, data, { encoding }, errorCallback); diff --git a/types/fs-extra/fs-extra-tests.ts b/types/fs-extra/fs-extra-tests.ts index 39f3a9d37a..903474e273 100644 --- a/types/fs-extra/fs-extra-tests.ts +++ b/types/fs-extra/fs-extra-tests.ts @@ -1,5 +1,5 @@ -import * as fs from 'fs-extra'; -import * as Path from 'path'; +import * as fs from "fs-extra"; +import * as Path from "path"; const len = 2; const src = ""; @@ -213,6 +213,16 @@ fs.lchmodSync(path, modeStr); fs.statSync(path); fs.lstatSync(path); +fs.read(0, new Buffer(""), 0, 0, null).then(x => { + const a = x.buffer; + const b = x.bytesRead; +}); + +fs.write(0, new Buffer(""), 0, 0, null).then(x => { + const a = x.buffer; + const b = x.bytesWritten; +}); + // $ExpectType Promise fs.writeFile("foo.txt", "i am foo", { encoding: "utf-8" }); diff --git a/types/fs-extra/index.d.ts b/types/fs-extra/index.d.ts index 49a056bce7..0231cac2d2 100644 --- a/types/fs-extra/index.d.ts +++ b/types/fs-extra/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for fs-extra 3.0 +// Type definitions for fs-extra 4.0 // Project: https://github.com/jprichardson/node-fs-extra // Definitions by: Alan Agius , // midknight41 , @@ -172,7 +172,7 @@ export function open(path: string | Buffer, flags: string | number, mode: number export function open(path: string | Buffer, flags: string | number, mode?: number): Promise; export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; -export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null): Promise<[number, Buffer]>; +export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null): Promise; export function readFile(file: string | Buffer | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; export function readFile(file: string | Buffer | number, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; @@ -233,8 +233,8 @@ export function write(fd: number, buffer: Buffer, offset: number, length: number export function write(fd: number, data: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; export function write(fd: number, data: any, offset: number, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; export function write(fd: number, data: any, offset: number, encoding: string, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; -export function write(fd: number, buffer: Buffer, offset: number, length: number, position?: number | null): Promise<[number, Buffer]>; -export function write(fd: number, data: any, offset: number, encoding?: string): Promise<[number, string]>; +export function write(fd: number, buffer: Buffer, offset: number, length: number, position?: number | null): Promise; +export function write(fd: number, data: any, offset: number, encoding?: string): Promise; export function writeFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; export function writeFile(file: string | Buffer | number, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): Promise; @@ -292,3 +292,13 @@ export interface WriteOptions { flag?: string; mode?: number; } + +export interface ReadResult { + bytesRead: number; + buffer: Buffer; +} + +export interface WriteResult { + bytesWritten: number; + buffer: Buffer; +} diff --git a/types/geokdbush/index.d.ts b/types/geokdbush/index.d.ts index 4ece8ff98d..117a1c10e9 100644 --- a/types/geokdbush/index.d.ts +++ b/types/geokdbush/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {KDBush} from 'kdbush'; +import { KDBush } from 'kdbush'; export function around( index: KDBush, diff --git a/types/get-stream/index.d.ts b/types/get-stream/index.d.ts index 9dafe344ae..19c7c6067b 100644 --- a/types/get-stream/index.d.ts +++ b/types/get-stream/index.d.ts @@ -1,18 +1,19 @@ // Type definitions for get-stream 3.0 // Project: https://github.com/sindresorhus/get-stream#readme // Definitions by: Douglas Duteil +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -import {Stream} from 'stream'; +import { Stream } from 'stream'; interface Options { /** * Encoding of the incoming stream. * @default 'utf8' */ - encoding?: string; + encoding?: BufferEncoding | 'buffer'; /** * Maximum length of the returned string. If it exceeds this value before * the stream ends, the promise will be rejected. @@ -27,8 +28,8 @@ interface Options { * stream, indicating that there is no more data to be read. * The stream is switched to flowing mode. */ -declare function getStrem(stream: Stream, options?: Options): Promise; -declare namespace getStrem { +declare function getStream(stream: Stream, options?: Options): Promise; +declare namespace getStream { /** * Get the `stream` as an array of values. * @@ -58,4 +59,4 @@ declare namespace getStrem { function buffer(stream: Stream, options?: Options): Promise; } -export = getStrem; +export = getStream; diff --git a/types/gl-matrix/gl-matrix-tests.ts b/types/gl-matrix/gl-matrix-tests.ts index 6325ff5cd4..3642cca521 100644 --- a/types/gl-matrix/gl-matrix-tests.ts +++ b/types/gl-matrix/gl-matrix-tests.ts @@ -1,5 +1,5 @@ // common -import {vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat} from "gl-matrix"; +import { vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat } from "gl-matrix"; var outVal: number; var outBool: boolean; diff --git a/types/global-tunnel-ng/global-tunnel-ng-tests.ts b/types/global-tunnel-ng/global-tunnel-ng-tests.ts new file mode 100644 index 0000000000..b906e3b56c --- /dev/null +++ b/types/global-tunnel-ng/global-tunnel-ng-tests.ts @@ -0,0 +1,48 @@ +import * as globalTunnel from 'global-tunnel-ng'; + +globalTunnel.initialize({ + host: '10.0.0.10', + port: 8080, + proxyAuth: 'userId:password', // optional authentication + sockets: 50 // optional pool size for each http and https +}); + +globalTunnel.end(); + +globalTunnel.initialize({ + connect: 'neither', + host: '10.0.0.10', + port: 3128 +}); + +globalTunnel.initialize({ + connect: 'neither', + protocol: 'https:', + host: '10.0.0.10', + port: 3129 +}); + +globalTunnel.initialize({ + connect: 'both', + host: '10.0.0.10', + port: 3130 +}); + +globalTunnel.initialize({ + connect: 'both', + protocol: 'https:', + host: '10.0.0.10', + port: 3130, + proxyHttpsOptions: { + // use this config for app -> proxy + }, + originHttpsOptions: { + // use this config for proxy -> origin + } +}); + +globalTunnel.initialize(); + +const proxyUrl: string | null = globalTunnel.proxyUrl; +const proxyConfig: globalTunnel.Options | null = globalTunnel.proxyConfig; +const isProxying: boolean = globalTunnel.isProxying; diff --git a/types/global-tunnel-ng/index.d.ts b/types/global-tunnel-ng/index.d.ts new file mode 100644 index 0000000000..80f73f491f --- /dev/null +++ b/types/global-tunnel-ng/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for global-tunnel-ng 2.1 +// Project: https://github.com/salesforce/global-tunnel +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function initialize(options?: Options | string): void; + +export function end(): void; + +export const proxyUrl: string | null; +export const proxyConfig: Options | null; +export const isProxying: boolean; + +export interface Options { + host: string; + port: number; + connect?: 'neither' | 'https' | 'both'; + protocol?: 'http:' | 'https:'; + proxyAuth?: string; + sockets?: number; + proxyHttpsOptions?: { [key: string]: any }; + originHttpsOptions?: { [key: string]: any }; +} diff --git a/types/global-tunnel-ng/tsconfig.json b/types/global-tunnel-ng/tsconfig.json new file mode 100644 index 0000000000..fa1974819d --- /dev/null +++ b/types/global-tunnel-ng/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", + "global-tunnel-ng-tests.ts" + ] +} diff --git a/types/global-tunnel-ng/tslint.json b/types/global-tunnel-ng/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/global-tunnel-ng/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/google-libphonenumber/google-libphonenumber-tests.ts b/types/google-libphonenumber/google-libphonenumber-tests.ts index 9f6fd2e7e7..f9e7c4bf8e 100644 --- a/types/google-libphonenumber/google-libphonenumber-tests.ts +++ b/types/google-libphonenumber/google-libphonenumber-tests.ts @@ -1,6 +1,6 @@ import libphonenumber = require('google-libphonenumber'); -import {PhoneNumberFormat, PhoneNumberUtil, AsYouTypeFormatter} from 'google-libphonenumber'; +import { PhoneNumberFormat, PhoneNumberUtil, AsYouTypeFormatter } from 'google-libphonenumber'; () => { // Require `PhoneNumberFormat`. diff --git a/types/google.visualization/index.d.ts b/types/google.visualization/index.d.ts index 9e26c3bb2b..d5967384f1 100644 --- a/types/google.visualization/index.d.ts +++ b/types/google.visualization/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Google Visualisation Apis // Project: https://developers.google.com/chart/ -// Definitions by: Dan Ludwig , Gregory Moore , Dan Manastireanu , Michael Cheng +// Definitions by: Dan Ludwig , Gregory Moore , Dan Manastireanu , Michael Cheng , Ivan Bisultanov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace google { @@ -412,6 +412,8 @@ declare namespace google { export interface ChartArea { top?: any; left?: any; + right?: any; + bottom?: any; width?: any; height?: any; } diff --git a/types/googlemaps/index.d.ts b/types/googlemaps/index.d.ts index b36032d298..2fea0028b8 100644 --- a/types/googlemaps/index.d.ts +++ b/types/googlemaps/index.d.ts @@ -1163,7 +1163,7 @@ declare namespace google.maps { export interface GeocoderComponentRestrictions { administrativeArea?: string; - country?: string; + country?: string | string[]; locality?: string; postalCode?: string; route?: string; diff --git a/types/got/got-tests.ts b/types/got/got-tests.ts new file mode 100644 index 0000000000..29370358be --- /dev/null +++ b/types/got/got-tests.ts @@ -0,0 +1,152 @@ +import got = require('got'); +import cookie = require('cookie'); +import FormData = require('form-data'); +import * as fs from 'fs'; +import * as http from 'http'; + +let str: string; +let buf: Buffer; +let obj: object; + +got('todomvc.com') + .then(response => { + str = response.body; + }) + .catch((error: got.GotError) => { + console.log(error.response.body); + }); + +got('todomvc.com').cancel(); + +got('todomvc.com', {json: true}).then(response => obj = response.body); +got('todomvc.com', {json: true, body: {}}).then(response => obj = response.body); +got('todomvc.com', {json: true, body: [{}]}).then(response => obj = response.body); +got('todomvc.com', {json: true, form: true}).then(response => obj = response.body); +got('todomvc.com', {json: true, form: true, encoding: null}).then(response => obj = response.body); +got('todomvc.com', {json: true, form: true, encoding: null, hostname: 'todomvc'}).then(response => obj = response.body); + +got('todomvc.com', {form: true}).then(response => str = response.body); +got('todomvc.com', {form: true, body: {}}).then(response => str = response.body); +got('todomvc.com', {form: true, body: [{}]}).then(response => str = response.body); +got('todomvc.com', {form: true, body: [{}], encoding: null}).then(response => buf = response.body); +got('todomvc.com', {form: true, body: [{}], encoding: 'utf8'}).then(response => str = response.body); +got('todomvc.com', { + form: true, + body: [{}], + encoding: 'utf8', + hostname: 'todomvc' +}).then(response => str = response.body); +// following must lead to type checking error: got('todomvc.com', {form: true, body: ''}).then(response => str = response.body); + +got('todomvc.com', {encoding: null, hostname: 'todomvc'}).then(response => buf = response.body); +got('todomvc.com', {encoding: 'utf8', hostname: 'todomvc'}).then(response => str = response.body); + +got('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); + +got.get('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); +got.post('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); +got.put('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); +got.patch('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); +got.head('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); +got.delete('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); + +got.stream('todomvc.com').pipe(fs.createWriteStream('index.html')); + +fs.createReadStream('index.html').pipe(got.stream.get('todomvc.com')); +fs.createReadStream('index.html').pipe(got.stream.post('todomvc.com')); +fs.createReadStream('index.html').pipe(got.stream.put('todomvc.com')); +fs.createReadStream('index.html').pipe(got.stream.patch('todomvc.com')); +fs.createReadStream('index.html').pipe(got.stream.head('todomvc.com')); +fs.createReadStream('index.html').pipe(got.stream.delete('todomvc.com')); + +let req: http.ClientRequest; +let res: http.IncomingMessage | undefined; +let opts: got.GotOptions; +let err: got.GotError; + +const stream = got.stream('todomvc.com'); +stream.addListener('request', (r) => req = r); +stream.addListener('response', (r) => res = r); +stream.addListener('redirect', (r, o) => { + res = r; + opts = o; +}); +stream.addListener('error', (e, b, r) => { + err = e; + res = r; +}); + +stream.on('request', (r) => req = r); +stream.on('response', (r) => res = r); +stream.on('redirect', (r, o) => { + res = r; + opts = o; +}); +stream.on('error', (e, b, r) => { + err = e; + res = r; +}); + +stream.once('request', (r) => req = r); +stream.once('response', (r) => res = r); +stream.once('redirect', (r, o) => { + res = r; + opts = o; +}); +stream.once('error', (e, b, r) => { + err = e; + res = r; +}); + +stream.prependListener('request', (r) => req = r); +stream.prependListener('response', (r) => res = r); +stream.prependListener('redirect', (r, o) => { + res = r; + opts = o; +}); +stream.prependListener('error', (e, b, r) => { + err = e; + res = r; +}); + +stream.prependOnceListener('request', (r) => req = r); +stream.prependOnceListener('response', (r) => res = r); +stream.prependOnceListener('redirect', (r, o) => { + res = r; + opts = o; +}); +stream.prependOnceListener('error', (e, b, r) => { + err = e; + res = r; +}); + +stream.removeListener('request', (r) => req = r); +stream.removeListener('response', (r) => res = r); +stream.removeListener('redirect', (r, o) => { + res = r; + opts = o; +}); +stream.removeListener('error', (e, b, r) => { + err = e; + res = r; +}); + +got('google.com', { + headers: { + cookie: cookie.serialize('foo', 'bar') + } +}); + +const form = new FormData(); + +form.append('my_file', fs.createReadStream('/foo/bar.jpg')); + +got.post('google.com', { + body: form +}); + +got('todomvc.com', { + headers: { + 'user-agent': `my-module/ (https://github.com/username/my-module)` + } +}); diff --git a/types/got/index.d.ts b/types/got/index.d.ts new file mode 100644 index 0000000000..fe498d5b34 --- /dev/null +++ b/types/got/index.d.ts @@ -0,0 +1,155 @@ +// Type definitions for got 7.1 +// Project: https://github.com/sindresorhus/got#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +import * as http from 'http'; +import * as nodeStream from 'stream'; + +export = got; + +declare const got: got.GotFn & + Record<'get' | 'post' | 'put' | 'patch' | 'head' | 'delete', got.GotFn> & + { + stream: got.GotStreamFn & Record<'get' | 'post' | 'put' | 'patch' | 'head' | 'delete', got.GotStreamFn> + }; + +declare namespace got { + // tslint:disable unified-signatures + interface GotFn { + (url: GotUrl): GotPromise; + (url: GotUrl, options: GotJSONOptions): GotPromise; + (url: GotUrl, options: GotFormOptions): GotPromise; + (url: GotUrl, options: GotFormOptions): GotPromise; + (url: GotUrl, options: GotBodyOptions): GotPromise; + (url: GotUrl, options: GotBodyOptions): GotPromise; + } + // tslint:disable unified-signatures + + type GotStreamFn = (url: GotUrl, options?: GotOptions) => GotEmitter & nodeStream.Duplex; + + type GotUrl = string | http.RequestOptions | URL; + + interface GotBodyOptions extends GotOptions { + body?: string | Buffer | nodeStream.Readable; + } + + interface GotJSONOptions extends GotOptions { + body?: object; + form?: boolean; + json: true; + } + + interface GotFormOptions extends GotOptions { + body?: {[key: string]: any}; + form: true; + json?: boolean; + } + + type GotOptions = http.RequestOptions & { + encoding?: E; + query?: string | object; + timeout?: number | TimeoutOptions; + retries?: number | RetryFunction; + followRedirect?: boolean; + decompress?: boolean; + useElectronNet?: boolean; + }; + + interface TimeoutOptions { + connect?: number; + socket?: number; + request?: number; + } + + type RetryFunction = (retry: number, error: any) => number; + + interface Response extends http.IncomingMessage { + body: B; + url: string; + requestUrl: string; + redirectUrls?: string[]; + } + + type GotPromise = Promise> & { cancel(): void }; + + interface GotEmitter { + addListener(event: 'request', listener: (req: http.ClientRequest) => void): this; + addListener(event: 'response', listener: (res: http.IncomingMessage) => void): this; + addListener(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions) => void): this; + addListener(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + + on(event: 'request', listener: (req: http.ClientRequest) => void): this; + on(event: 'response', listener: (res: http.IncomingMessage) => void): this; + on(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions) => void): this; + on(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + + once(event: 'request', listener: (req: http.ClientRequest) => void): this; + once(event: 'response', listener: (res: http.IncomingMessage) => void): this; + once(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions) => void): this; + once(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + + prependListener(event: 'request', listener: (req: http.ClientRequest) => void): this; + prependListener(event: 'response', listener: (res: http.IncomingMessage) => void): this; + prependListener(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions) => void): this; + prependListener(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + + prependOnceListener(event: 'request', listener: (req: http.ClientRequest) => void): this; + prependOnceListener(event: 'response', listener: (res: http.IncomingMessage) => void): this; + prependOnceListener(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions) => void): this; + prependOnceListener(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + + removeListener(event: 'request', listener: (req: http.ClientRequest) => void): this; + removeListener(event: 'response', listener: (res: http.IncomingMessage) => void): this; + removeListener(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions) => void): this; + removeListener(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + } + + type GotError = RequestError | ReadError | ParseError | HTTPError | MaxRedirectsError | UnsupportedProtocolError; + + interface RequestError extends StdError { + name: 'RequestError'; + } + + interface ReadError extends StdError { + name: 'ReadError'; + } + + interface ParseError extends StdError { + name: 'ParseError'; + statusCode: number; + statusMessage: string; + } + + interface HTTPError extends StdError { + name: 'HTTPError'; + statusCode: number; + statusMessage: string; + headers: http.IncomingHttpHeaders; + } + + interface MaxRedirectsError extends StdError { + name: 'MaxRedirectsError'; + statusCode: number; + statusMessage: string; + redirectUrls: string[]; + } + + interface UnsupportedProtocolError extends StdError { + name: 'UnsupportedProtocolError'; + } + + interface StdError extends Error { + code?: string; + host?: string; + hostname?: string; + method?: string; + path?: string; + protocol?: string; + url?: string; + response?: any; + } +} diff --git a/types/got/tsconfig.json b/types/got/tsconfig.json new file mode 100644 index 0000000000..be639b3c17 --- /dev/null +++ b/types/got/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", + "got-tests.ts" + ] +} diff --git a/types/got/tslint.json b/types/got/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/got/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/graphql-date/graphql-date-tests.ts b/types/graphql-date/graphql-date-tests.ts index 07542c8c0d..14a6882646 100644 --- a/types/graphql-date/graphql-date-tests.ts +++ b/types/graphql-date/graphql-date-tests.ts @@ -1,4 +1,4 @@ -import {GraphQLObjectType} from 'graphql'; +import { GraphQLObjectType } from 'graphql'; import * as GraphQLDate from 'graphql-date'; const fooType = new GraphQLObjectType({ diff --git a/types/graphql-date/index.d.ts b/types/graphql-date/index.d.ts index 20cd74d61e..35ad44f7e1 100644 --- a/types/graphql-date/index.d.ts +++ b/types/graphql-date/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Eric Naeseth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {GraphQLScalarType} from 'graphql'; +import { GraphQLScalarType } from 'graphql'; declare const date: GraphQLScalarType; diff --git a/types/graphql-type-json/graphql-type-json-tests.ts b/types/graphql-type-json/graphql-type-json-tests.ts index 3282681845..8d2435270e 100644 --- a/types/graphql-type-json/graphql-type-json-tests.ts +++ b/types/graphql-type-json/graphql-type-json-tests.ts @@ -1,4 +1,4 @@ -import {GraphQLObjectType, GraphQLInputObjectType} from "graphql"; +import { GraphQLObjectType, GraphQLInputObjectType } from "graphql"; import * as GraphQLJSON from "graphql-type-json"; const TestType = new GraphQLObjectType({ diff --git a/types/graphql-type-json/index.d.ts b/types/graphql-type-json/index.d.ts index 7d41b83013..c9549b946d 100644 --- a/types/graphql-type-json/index.d.ts +++ b/types/graphql-type-json/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/taion/graphql-type-json#readme // Definitions by: Pavel Ivanov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {GraphQLScalarType} from "graphql"; +import { GraphQLScalarType } from "graphql"; declare const GraphQLJSON: GraphQLScalarType; export = GraphQLJSON; diff --git a/types/graphql/error/GraphQLError.d.ts b/types/graphql/error/GraphQLError.d.ts index 857f25b593..fbafcb1e30 100644 --- a/types/graphql/error/GraphQLError.d.ts +++ b/types/graphql/error/GraphQLError.d.ts @@ -9,7 +9,6 @@ import { Source } from '../language/source'; * GraphQL document and/or execution result that correspond to the Error. */ export class GraphQLError extends Error { - /** * A message describing the Error for debugging purposes. * @@ -40,7 +39,7 @@ export class GraphQLError extends Error { /** * An array of GraphQL AST Nodes corresponding to this error. */ - nodes?: Array | undefined; + nodes?: ASTNode[] | undefined; /** * The source GraphQL document corresponding to this error. @@ -51,7 +50,7 @@ export class GraphQLError extends Error { * An array of character offsets within the source GraphQL document * which correspond to this error. */ - positions?: Array | undefined; + positions?: number[] | undefined; /** * The original error thrown from a field resolver during execution. @@ -60,9 +59,9 @@ export class GraphQLError extends Error { constructor( message: string, - nodes?: Array, + nodes?: any[], source?: Source, - positions?: Array, + positions?: number[], path?: Array, originalError?: Error, ); diff --git a/types/graphql/error/formatError.d.ts b/types/graphql/error/formatError.d.ts index 5b974d5461..fbb31cdb23 100644 --- a/types/graphql/error/formatError.d.ts +++ b/types/graphql/error/formatError.d.ts @@ -6,13 +6,13 @@ import { GraphQLError } from './GraphQLError'; */ export function formatError(error: GraphQLError): GraphQLFormattedError; -export type GraphQLFormattedError = { - message: string, - locations?: Array, - path?: Array -}; +export interface GraphQLFormattedError { + message: string; + locations?: GraphQLErrorLocation[]; + path?: Array; +} -export type GraphQLErrorLocation = { - line: number, - column: number -}; +export interface GraphQLErrorLocation { + line: number; + column: number; +} diff --git a/types/graphql/error/index.d.ts b/types/graphql/error/index.d.ts index 50fe58c06a..cfb5b92740 100644 --- a/types/graphql/error/index.d.ts +++ b/types/graphql/error/index.d.ts @@ -1,4 +1,4 @@ export { GraphQLError } from './GraphQLError'; export { syntaxError } from './syntaxError'; export { locatedError } from './locatedError'; -export { formatError, GraphQLFormattedError, GraphQLErrorLocation } from './formatError'; \ No newline at end of file +export { formatError, GraphQLFormattedError, GraphQLErrorLocation } from './formatError'; diff --git a/types/graphql/error/locatedError.d.ts b/types/graphql/error/locatedError.d.ts index 8aca478f03..c827f8ede8 100644 --- a/types/graphql/error/locatedError.d.ts +++ b/types/graphql/error/locatedError.d.ts @@ -7,6 +7,6 @@ import { GraphQLError } from './GraphQLError'; */ export function locatedError( originalError: Error, - nodes: Array, + nodes: T[], path: Array ): GraphQLError; diff --git a/types/graphql/error/syntaxError.d.ts b/types/graphql/error/syntaxError.d.ts index d57b292211..80c4453e03 100644 --- a/types/graphql/error/syntaxError.d.ts +++ b/types/graphql/error/syntaxError.d.ts @@ -9,4 +9,4 @@ export function syntaxError( source: Source, position: number, description: string -): GraphQLError; \ No newline at end of file +): GraphQLError; diff --git a/types/graphql/execution/execute.d.ts b/types/graphql/execution/execute.d.ts index 48ee78840a..782310b6f4 100644 --- a/types/graphql/execution/execute.d.ts +++ b/types/graphql/execution/execute.d.ts @@ -22,7 +22,7 @@ export interface ExecutionContext { rootValue: any; operation: OperationDefinitionNode; variableValues: { [key: string]: any }; - errors: Array; + errors: GraphQLError[]; } /** @@ -32,7 +32,7 @@ export interface ExecutionContext { */ export interface ExecutionResult { data?: { [key: string]: any }; - errors?: Array; + errors?: GraphQLError[]; } /** diff --git a/types/graphql/execution/values.d.ts b/types/graphql/execution/values.d.ts index e6a0be63cc..3f6e909ed7 100644 --- a/types/graphql/execution/values.d.ts +++ b/types/graphql/execution/values.d.ts @@ -10,9 +10,9 @@ import { FieldNode, DirectiveNode, VariableDefinitionNode } from '../language/as */ export function getVariableValues( schema: GraphQLSchema, - varDefNodes: Array, + varDefNodes: VariableDefinitionNode[], inputs: { [key: string]: any } -): { [key: string]: any } +): { [key: string]: any }; /** * Prepares an object map of argument values given a list of argument diff --git a/types/graphql/graphql-tests.ts b/types/graphql/graphql-tests.ts index 58725259e7..7c0210249b 100644 --- a/types/graphql/graphql-tests.ts +++ b/types/graphql/graphql-tests.ts @@ -3,180 +3,180 @@ import * as graphql from 'graphql'; /////////////////////////// // graphql // /////////////////////////// -namespace graphql_tests { +function graphql_tests() { // TODO } /////////////////////////// // graphql/language // /////////////////////////// -namespace language_ast_tests { - // TODOS +function language_ast_tests() { + // TODO } -namespace language_index_tests { - // TODOS +function language_index_tests() { + // TODO } -namespace language_kinds_tests { - // TODOS +function language_kinds_tests() { + // TODO } -namespace language_lexer_tests { - // TODOS +function language_lexer_tests() { + // TODO } -namespace language_location_tests { - // TODOS +function language_location_tests() { + // TODO } -namespace language_parser_tests { - // TODOS +function language_parser_tests() { + // TODO } -namespace language_printer_tests { - // TODOS +function language_printer_tests() { + // TODO } -namespace language_source_tests { - // TODOS +function language_source_tests() { + // TODO } -namespace language_visitor_tests { - // TODOS +function language_visitor_tests() { + // TODO } /////////////////////////// // graphql/type // /////////////////////////// -namespace type_definition_tests { +function type_definition_tests() { // TODO } -namespace type_directives_tests { +function type_directives_tests() { // TODO } -namespace type_introspection_tests { +function type_introspection_tests() { // TODO } -namespace type_scalars_tests { +function type_scalars_tests() { // TODO } -namespace type_schema_tests { +function type_schema_tests() { // TODO } /////////////////////////// // graphql/validation // /////////////////////////// -namespace validation_specifiedRules_tests { - +function validation_specifiedRules_tests() { + // TODO } -namespace validation_validate_tests { - +function validation_validate_tests() { + // TODO } /////////////////////////// // graphql/execution // /////////////////////////// -namespace execution_execute_tests { +function execution_execute_tests() { // TODOS } -namespace execution_values_tests { +function execution_values_tests() { // TODOS } /////////////////////////// // graphql/error // /////////////////////////// -namespace error_GraphQLError { - +function error_GraphQLError() { + // TODOS } -namespace error_formatError { - +function error_formatError() { + // TODOS } -namespace error_locatedError { - +function error_locatedError() { + // TODOS } -namespace error_syntaxError { - +function error_syntaxError() { + // TODOS } /////////////////////////// // graphql/utilities // /////////////////////////// -namespace utilities_TypeInfo_tests { - //TODOS +function utilities_TypeInfo_tests() { + // TODOS } -namespace utilities_assertValidName_tests { - //TODOS +function utilities_assertValidName_tests() { + // TODOS } -namespace utilities_astFromValue_tests { - //TODOS +function utilities_astFromValue_tests() { + // TODOS } -namespace utilities_buildASTSchema_tests { - //TODOS +function utilities_buildASTSchema_tests() { + // TODOS } -namespace utilities_buildClientSchema_tests { - //TODOS +function utilities_buildClientSchema_tests() { + // TODOS } -namespace utilities_concatAST_tests { - //TODOS +function utilities_concatAST_tests() { + // TODOS } -namespace utilities_extendSchema_tests { - //TODOS +function utilities_extendSchema_tests() { + // TODOS } -namespace utilities_getOperationAST_tests { - //TODOS +function utilities_getOperationAST_tests() { + // TODOS } -namespace utilities_index_tests { - //TODOS +function utilities_index_tests() { + // TODOS } -namespace utilities_introspectionQuery_tests { - //TODOS +function utilities_introspectionQuery_tests() { + // TODOS } -namespace utilities_isValidJSValue_tests { - //TODOS +function utilities_isValidJSValue_tests() { + // TODOS } -namespace utilities_isValidLiteralValue_tests { - //TODOS +function utilities_isValidLiteralValue_tests() { + // TODOS } -namespace utilities_schemaPrinter_tests { - //TODOS +function utilities_schemaPrinter_tests() { + // TODOS } -namespace utilities_separateOperations_tests { - //TODOS +function utilities_separateOperations_tests() { + // TODOS } -namespace utilities_typeComparators_tests { - //TODOS +function utilities_typeComparators_tests() { + // TODOS } -namespace utilities_typeFromAST_tests { - //TODOS +function utilities_typeFromAST_tests() { + // TODOS } -namespace utilities_valueFromAST_tests { - //TODOS +function utilities_valueFromAST_tests() { + // TODOS } diff --git a/types/graphql/index.d.ts b/types/graphql/index.d.ts index fbd724ff4a..d4cf14b42f 100644 --- a/types/graphql/index.d.ts +++ b/types/graphql/index.d.ts @@ -1,6 +1,10 @@ // Type definitions for graphql 0.10 // Project: https://www.npmjs.com/package/graphql -// Definitions by: TonyYang , Caleb Meredith , Dominic Watson , Firede , Kepennar +// Definitions by: TonyYang +// Caleb Meredith +// Dominic Watson +// Firede +// Kepennar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -9,12 +13,9 @@ export { graphql } from './graphql'; -/// - // Create and operate on GraphQL type definitions and schema. export * from './type'; - // Parse and operate on GraphQL language source files. export * from './language'; @@ -28,7 +29,6 @@ export { ExecutionResult, } from './execution'; - // Validate GraphQL queries. export { validate, @@ -36,7 +36,6 @@ export { specifiedRules, } from './validation'; - // Create and format GraphQL errors. export { GraphQLError, @@ -45,7 +44,6 @@ export { GraphQLErrorLocation, } from './error'; - // Utilities for operating on GraphQL type schema and parsed sources. export { // The GraphQL query recommended for a full schema introspection. diff --git a/types/graphql/language/ast.d.ts b/types/graphql/language/ast.d.ts index d0f25b65d0..f4bc343ed2 100644 --- a/types/graphql/language/ast.d.ts +++ b/types/graphql/language/ast.d.ts @@ -4,8 +4,7 @@ import { Source } from './source'; * Contains a range of UTF-8 character offsets and token references that * identify the region of the source from which the AST derived. */ -export type Location = { - +export interface Location { /** * The character offset at which this Node begins. */ @@ -30,37 +29,37 @@ export type Location = { * The Source document the AST represents. */ source: Source; -}; +} /** * Represents a range of characters represented by a lexical token * within a Source. */ -export type Token = { - +export interface Token { /** * The kind of Token. */ - kind: '' - | '' - | '!' - | '$' - | '(' - | ')' - | '...' - | ':' - | '=' - | '@' - | '[' - | ']' - | '{' - | '|' - | '}' - | 'Name' - | 'Int' - | 'Float' - | 'String' - | 'Comment'; + kind: + | '' + | '' + | '!' + | '$' + | '(' + | ')' + | '...' + | ':' + | '=' + | '@' + | '[' + | ']' + | '{' + | '|' + | '}' + | 'Name' + | 'Int' + | 'Float' + | 'String' + | 'Comment'; /** * The character offset at which this Node begins. @@ -94,12 +93,13 @@ export type Token = { */ prev?: Token; next?: Token; -}; +} /** * The list of all possible AST node types. */ -export type ASTNode = NameNode +export type ASTNode = + | NameNode | DocumentNode | OperationDefinitionNode | VariableDefinitionNode @@ -139,7 +139,7 @@ export type ASTNode = NameNode // Name -export type NameNode = { +export interface NameNode { kind: 'Name'; loc?: Location; value: string; @@ -147,30 +147,31 @@ export type NameNode = { // Document -export type DocumentNode = { +export interface DocumentNode { kind: 'Document'; loc?: Location; - definitions: Array; + definitions: DefinitionNode[]; } -export type DefinitionNode = OperationDefinitionNode +export type DefinitionNode = + | OperationDefinitionNode | FragmentDefinitionNode - | TypeSystemDefinitionNode // experimental non-spec addition. + | TypeSystemDefinitionNode; // experimental non-spec addition. -export type OperationDefinitionNode = { +export interface OperationDefinitionNode { kind: 'OperationDefinition'; loc?: Location; operation: OperationTypeNode; name?: NameNode; - variableDefinitions?: Array; - directives?: Array; + variableDefinitions?: VariableDefinitionNode[]; + directives?: DirectiveNode[]; selectionSet: SelectionSetNode; } // Note: subscription is an experimental non-spec addition. export type OperationTypeNode = 'query' | 'mutation' | 'subscription'; -export type VariableDefinitionNode = { +export interface VariableDefinitionNode { kind: 'VariableDefinition'; loc?: Location; variable: VariableNode; @@ -178,70 +179,70 @@ export type VariableDefinitionNode = { defaultValue?: ValueNode; } -export type VariableNode = { +export interface VariableNode { kind: 'Variable'; loc?: Location; name: NameNode; } -export type SelectionSetNode = { +export interface SelectionSetNode { kind: 'SelectionSet'; loc?: Location; - selections: Array; + selections: SelectionNode[]; } -export type SelectionNode = FieldNode +export type SelectionNode = + | FieldNode | FragmentSpreadNode - | InlineFragmentNode + | InlineFragmentNode; -export type FieldNode = { +export interface FieldNode { kind: 'Field'; loc?: Location; alias?: NameNode; name: NameNode; - arguments?: Array; - directives?: Array; + arguments?: ArgumentNode[]; + directives?: DirectiveNode[]; selectionSet?: SelectionSetNode; } -export type ArgumentNode = { +export interface ArgumentNode { kind: 'Argument'; loc?: Location; name: NameNode; value: ValueNode; } - // Fragments -export type FragmentSpreadNode = { +export interface FragmentSpreadNode { kind: 'FragmentSpread'; loc?: Location; name: NameNode; - directives?: Array; + directives?: DirectiveNode[]; } -export type InlineFragmentNode = { +export interface InlineFragmentNode { kind: 'InlineFragment'; loc?: Location; typeCondition?: NamedTypeNode; - directives?: Array; + directives?: DirectiveNode[]; selectionSet: SelectionSetNode; } -export type FragmentDefinitionNode = { +export interface FragmentDefinitionNode { kind: 'FragmentDefinition'; loc?: Location; name: NameNode; typeCondition: NamedTypeNode; - directives?: Array; + directives?: DirectiveNode[]; selectionSet: SelectionSetNode; } - // Values -export type ValueNode = VariableNode +export type ValueNode = + | VariableNode | IntValueNode | FloatValueNode | StringValueNode @@ -249,92 +250,91 @@ export type ValueNode = VariableNode | NullValueNode | EnumValueNode | ListValueNode - | ObjectValueNode + | ObjectValueNode; -export type IntValueNode = { +export interface IntValueNode { kind: 'IntValue'; loc?: Location; value: string; } -export type FloatValueNode = { +export interface FloatValueNode { kind: 'FloatValue'; loc?: Location; value: string; } -export type StringValueNode = { +export interface StringValueNode { kind: 'StringValue'; loc?: Location; value: string; } -export type BooleanValueNode = { +export interface BooleanValueNode { kind: 'BooleanValue'; loc?: Location; value: boolean; } -export type NullValueNode = { +export interface NullValueNode { kind: 'NullValue'; loc?: Location; } -export type EnumValueNode = { +export interface EnumValueNode { kind: 'EnumValue'; loc?: Location; value: string; } -export type ListValueNode = { +export interface ListValueNode { kind: 'ListValue'; loc?: Location; - values: Array; + values: ValueNode[]; } -export type ObjectValueNode = { +export interface ObjectValueNode { kind: 'ObjectValue'; loc?: Location; - fields: Array; + fields: ObjectFieldNode[]; } -export type ObjectFieldNode = { +export interface ObjectFieldNode { kind: 'ObjectField'; loc?: Location; name: NameNode; value: ValueNode; } - // Directives -export type DirectiveNode = { +export interface DirectiveNode { kind: 'Directive'; loc?: Location; name: NameNode; - arguments?: Array; + arguments?: ArgumentNode[]; } - // Type Reference -export type TypeNode = NamedTypeNode +export type TypeNode = + | NamedTypeNode | ListTypeNode - | NonNullTypeNode + | NonNullTypeNode; -export type NamedTypeNode = { +export interface NamedTypeNode { kind: 'NamedType'; loc?: Location; name: NameNode; -}; +} -export type ListTypeNode = { +export interface ListTypeNode { kind: 'ListType'; loc?: Location; type: TypeNode; } -export type NonNullTypeNode = { +export interface NonNullTypeNode { kind: 'NonNullType'; loc?: Location; type: NamedTypeNode | ListTypeNode; @@ -342,115 +342,117 @@ export type NonNullTypeNode = { // Type System Definition -export type TypeSystemDefinitionNode = SchemaDefinitionNode +export type TypeSystemDefinitionNode = + | SchemaDefinitionNode | TypeDefinitionNode | TypeExtensionDefinitionNode - | DirectiveDefinitionNode + | DirectiveDefinitionNode; -export type SchemaDefinitionNode = { +export interface SchemaDefinitionNode { kind: 'SchemaDefinition'; loc?: Location; - directives: Array; - operationTypes: Array; + directives: DirectiveNode[]; + operationTypes: OperationTypeDefinitionNode[]; } -export type OperationTypeDefinitionNode = { +export interface OperationTypeDefinitionNode { kind: 'OperationTypeDefinition'; loc?: Location; operation: OperationTypeNode; type: NamedTypeNode; } -export type TypeDefinitionNode = ScalarTypeDefinitionNode +export type TypeDefinitionNode = + | ScalarTypeDefinitionNode | ObjectTypeDefinitionNode | InterfaceTypeDefinitionNode | UnionTypeDefinitionNode | EnumTypeDefinitionNode - | InputObjectTypeDefinitionNode + | InputObjectTypeDefinitionNode; -export type ScalarTypeDefinitionNode = { +export interface ScalarTypeDefinitionNode { kind: 'ScalarTypeDefinition'; loc?: Location; name: NameNode; - directives?: Array; + directives?: DirectiveNode[]; } -export type ObjectTypeDefinitionNode = { +export interface ObjectTypeDefinitionNode { kind: 'ObjectTypeDefinition'; loc?: Location; name: NameNode; - interfaces?: Array; - directives?: Array; - fields: Array; + interfaces?: NamedTypeNode[]; + directives?: DirectiveNode[]; + fields: FieldDefinitionNode[]; } -export type FieldDefinitionNode = { +export interface FieldDefinitionNode { kind: 'FieldDefinition'; loc?: Location; name: NameNode; - arguments: Array; + arguments: InputValueDefinitionNode[]; type: TypeNode; - directives?: Array; + directives?: DirectiveNode[]; } -export type InputValueDefinitionNode = { +export interface InputValueDefinitionNode { kind: 'InputValueDefinition'; loc?: Location; name: NameNode; type: TypeNode; defaultValue?: ValueNode; - directives?: Array; + directives?: DirectiveNode[]; } -export type InterfaceTypeDefinitionNode = { +export interface InterfaceTypeDefinitionNode { kind: 'InterfaceTypeDefinition'; loc?: Location; name: NameNode; - directives?: Array; - fields: Array; + directives?: DirectiveNode[]; + fields: FieldDefinitionNode[]; } -export type UnionTypeDefinitionNode = { +export interface UnionTypeDefinitionNode { kind: 'UnionTypeDefinition'; loc?: Location; name: NameNode; - directives?: Array; - types: Array; + directives?: DirectiveNode[]; + types: NamedTypeNode[]; } -export type EnumTypeDefinitionNode = { +export interface EnumTypeDefinitionNode { kind: 'EnumTypeDefinition'; loc?: Location; name: NameNode; - directives?: Array; - values: Array; + directives?: DirectiveNode[]; + values: EnumValueDefinitionNode[]; } -export type EnumValueDefinitionNode = { +export interface EnumValueDefinitionNode { kind: 'EnumValueDefinition'; loc?: Location; name: NameNode; - directives?: Array; + directives?: DirectiveNode[]; } -export type InputObjectTypeDefinitionNode = { +export interface InputObjectTypeDefinitionNode { kind: 'InputObjectTypeDefinition'; loc?: Location; name: NameNode; - directives?: Array; - fields: Array; + directives?: DirectiveNode[]; + fields: InputValueDefinitionNode[]; } -export type TypeExtensionDefinitionNode = { +export interface TypeExtensionDefinitionNode { kind: 'TypeExtensionDefinition'; loc?: Location; definition: ObjectTypeDefinitionNode; } -export type DirectiveDefinitionNode = { +export interface DirectiveDefinitionNode { kind: 'DirectiveDefinition'; loc?: Location; name: NameNode; - arguments?: Array; - locations: Array; + arguments?: InputValueDefinitionNode[]; + locations: NameNode[]; } diff --git a/types/graphql/language/kinds.d.ts b/types/graphql/language/kinds.d.ts index 3b595beb65..626d350818 100644 --- a/types/graphql/language/kinds.d.ts +++ b/types/graphql/language/kinds.d.ts @@ -63,4 +63,4 @@ export const TYPE_EXTENSION_DEFINITION: 'TypeExtensionDefinition'; // Directive Definitions -export const DIRECTIVE_DEFINITION: 'DirectiveDefinition'; \ No newline at end of file +export const DIRECTIVE_DEFINITION: 'DirectiveDefinition'; diff --git a/types/graphql/language/lexer.d.ts b/types/graphql/language/lexer.d.ts index 5175b5b1e6..4a55f03dc2 100644 --- a/types/graphql/language/lexer.d.ts +++ b/types/graphql/language/lexer.d.ts @@ -18,7 +18,7 @@ export function createLexer( /** * The return type of createLexer. */ -export type Lexer = { +export interface Lexer { source: Source; options: TOptions; @@ -46,7 +46,7 @@ export type Lexer = { * Advances the token stream to the next non-ignored token. */ advance(): Token; -}; +} /** * An exported enum describing the different kinds of tokens that the diff --git a/types/graphql/language/location.d.ts b/types/graphql/language/location.d.ts index 8c638a3a96..4d7a13e314 100644 --- a/types/graphql/language/location.d.ts +++ b/types/graphql/language/location.d.ts @@ -1,6 +1,5 @@ import { Source } from "./source"; - export interface SourceLocation { line: number; column: number; diff --git a/types/graphql/language/parser.d.ts b/types/graphql/language/parser.d.ts index 1458d6736d..5aa195ddd4 100644 --- a/types/graphql/language/parser.d.ts +++ b/types/graphql/language/parser.d.ts @@ -5,14 +5,14 @@ import { Lexer } from "./lexer"; /** * Configuration options to control parser behavior */ -export type ParseOptions = { +export interface ParseOptions { /** * By default, the parser creates AST nodes that know the location * in the source that they correspond to. This configuration flag * disables that behavior for performance or testing. */ - noLocation?: boolean -}; + noLocation?: boolean; +} /** * Given a GraphQL source, parses it into a Document. diff --git a/types/graphql/language/visitor.d.ts b/types/graphql/language/visitor.d.ts index d4c528501e..024b292ed6 100644 --- a/types/graphql/language/visitor.d.ts +++ b/types/graphql/language/visitor.d.ts @@ -38,7 +38,7 @@ export const QueryDocumentKeys: { EnumValueDefinition: string[]; InputObjectTypeDefinition: string[]; TypeExtensionDefinition: string[]; -} +}; export const BREAK: any; diff --git a/types/graphql/tslint.json b/types/graphql/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/graphql/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/graphql/type/definition.d.ts b/types/graphql/type/definition.d.ts index eb64172f40..5b0a2e9181 100644 --- a/types/graphql/type/definition.d.ts +++ b/types/graphql/type/definition.d.ts @@ -10,14 +10,14 @@ import { GraphQLSchema } from './schema'; * These are all of the possible kinds of types. */ export type GraphQLType = - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLInputObjectType | - GraphQLList | - GraphQLNonNull; + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + | GraphQLNonNull; export function isType(type: any): type is GraphQLType; @@ -27,16 +27,15 @@ export function assertType(type: any): GraphQLType; * These types may be used as input types for arguments and directives. */ export type GraphQLInputType = - GraphQLScalarType | - GraphQLEnumType | - GraphQLInputObjectType | - GraphQLList | - GraphQLNonNull< - GraphQLScalarType | - GraphQLEnumType | - GraphQLInputObjectType | - GraphQLList - >; + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList>; export function isInputType(type: GraphQLType): type is GraphQLInputType; @@ -46,20 +45,19 @@ export function assertInputType(type: GraphQLType): GraphQLInputType; * These types may be used as output types as the result of fields. */ export type GraphQLOutputType = - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLList | - GraphQLNonNull< - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLList - >; + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList>; export function isOutputType(type: GraphQLType): type is GraphQLOutputType; @@ -69,8 +67,8 @@ export function assertOutputType(type: GraphQLType): GraphQLOutputType; * These types may describe types which may be leaf values. */ export type GraphQLLeafType = - GraphQLScalarType | - GraphQLEnumType; + | GraphQLScalarType + | GraphQLEnumType; export function isLeafType(type: GraphQLType): type is GraphQLLeafType; @@ -80,9 +78,9 @@ export function assertLeafType(type: GraphQLType): GraphQLLeafType; * These types may describe the parent context of a selection set. */ export type GraphQLCompositeType = - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType; + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType; export function isCompositeType(type: GraphQLType): type is GraphQLCompositeType; @@ -92,8 +90,8 @@ export function assertCompositeType(type: GraphQLType): GraphQLCompositeType; * These types may describe the parent context of a selection set. */ export type GraphQLAbstractType = - GraphQLInterfaceType | - GraphQLUnionType; + | GraphQLInterfaceType + | GraphQLUnionType; export function isAbstractType(type: GraphQLType): type is GraphQLAbstractType; @@ -103,13 +101,13 @@ export function assertAbstractType(type: GraphQLType): GraphQLAbstractType; * These types can all accept null as a value. */ export type GraphQLNullableType = - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLInputObjectType | - GraphQLList; + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList; export function getNullableType( type: T @@ -119,12 +117,12 @@ export function getNullableType( * These named types do not include modifiers like List or NonNull. */ export type GraphQLNamedType = - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLInputObjectType; + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType; export function isNamedType(type: GraphQLType): boolean; @@ -175,9 +173,9 @@ export class GraphQLScalarType { export interface GraphQLScalarTypeConfig { name: string; description?: string; - serialize: (value: any) => TExternal | null | undefined; - parseValue?: (value: any) => TInternal | null | undefined; - parseLiteral?: (valueNode: ValueNode) => TInternal | null | undefined; + serialize(value: any): TExternal | null | undefined; + parseValue?(value: any): TInternal | null | undefined; + parseLiteral?(valueNode: ValueNode): TInternal | null | undefined; } /** @@ -224,17 +222,16 @@ export class GraphQLObjectType { constructor(config: GraphQLObjectTypeConfig); getFields(): GraphQLFieldMap; - getInterfaces(): Array; + getInterfaces(): GraphQLInterfaceType[]; toString(): string; } - export interface GraphQLObjectTypeConfig { name: string; - interfaces?: Thunk>; + interfaces?: Thunk; fields: Thunk>; isTypeOf?: GraphQLIsTypeOfFn; - description?: string + description?: string; } export type GraphQLTypeResolver = ( @@ -258,7 +255,7 @@ export type GraphQLFieldResolver = ( export interface GraphQLResolveInfo { fieldName: string; - fieldNodes: Array; + fieldNodes: FieldNode[]; returnType: GraphQLOutputType; parentType: GraphQLCompositeType; path: ResponsePath; @@ -297,7 +294,7 @@ export interface GraphQLField { name: string; description: string; type: GraphQLOutputType; - args: Array; + args: GraphQLArgument[]; resolve?: GraphQLFieldResolver; isDeprecated?: boolean; deprecationReason?: string; @@ -345,15 +342,15 @@ export class GraphQLInterfaceType { } export interface GraphQLInterfaceTypeConfig { - name: string, - fields: Thunk>, + name: string; + fields: Thunk>; /** * Optionally provide a custom type resolver function. If one is not provided, * the default implementation will call `isTypeOf` on each implementing * Object type. */ - resolveType?: GraphQLTypeResolver, - description?: string + resolveType?: GraphQLTypeResolver; + description?: string; } /** @@ -386,14 +383,14 @@ export class GraphQLUnionType { constructor(config: GraphQLUnionTypeConfig); - getTypes(): Array; + getTypes(): GraphQLObjectType[]; toString(): string; } export interface GraphQLUnionTypeConfig { - name: string, - types: Thunk>, + name: string; + types: Thunk; /** * Optionally provide a custom type resolver function. If one is not provided, * the default implementation will call `isTypeOf` on each implementing @@ -429,7 +426,7 @@ export class GraphQLEnumType { description: string; constructor(config: GraphQLEnumTypeConfig); - getValues(): Array; + getValues(): GraphQLEnumValue[]; getValue(name: string): GraphQLEnumValue; serialize(value: any): string; parseValue(value: any): any; diff --git a/types/graphql/type/directives.d.ts b/types/graphql/type/directives.d.ts index 5e470ddfca..aed6234ef5 100644 --- a/types/graphql/type/directives.d.ts +++ b/types/graphql/type/directives.d.ts @@ -3,7 +3,6 @@ import { GraphQLArgument } from './definition'; - export const DirectiveLocation: { // Operations QUERY: 'QUERY', @@ -27,7 +26,7 @@ export const DirectiveLocation: { INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION', }; -export type DirectiveLocationEnum = any //$Keys +export type DirectiveLocationEnum = keyof typeof DirectiveLocation; /** * Directives are used by the GraphQL runtime as a way of modifying execution @@ -36,8 +35,8 @@ export type DirectiveLocationEnum = any //$Keys export class GraphQLDirective { name: string; description: string; - locations: Array; - args: Array; + locations: DirectiveLocationEnum[]; + args: GraphQLArgument[]; constructor(config: GraphQLDirectiveConfig); } @@ -45,7 +44,7 @@ export class GraphQLDirective { export interface GraphQLDirectiveConfig { name: string; description?: string; - locations: Array; + locations: DirectiveLocationEnum[]; args?: GraphQLFieldConfigArgumentMap; } @@ -72,4 +71,4 @@ export const GraphQLDeprecatedDirective: GraphQLDirective; /** * The full list of specified directives. */ -export const specifiedDirectives: Array; +export const specifiedDirectives: GraphQLDirective[]; diff --git a/types/graphql/type/introspection.d.ts b/types/graphql/type/introspection.d.ts index 0227328b1d..989e34a882 100644 --- a/types/graphql/type/introspection.d.ts +++ b/types/graphql/type/introspection.d.ts @@ -10,7 +10,6 @@ import { } from './definition'; import { GraphQLField } from './definition'; - export const __Schema: GraphQLObjectType; export const __Directive: GraphQLObjectType; export const __DirectiveLocation: GraphQLEnumType; @@ -28,7 +27,7 @@ export const TypeKind: { INPUT_OBJECT: 'INPUT_OBJECT', LIST: 'LIST', NON_NULL: 'NON_NULL', -} +}; export const __TypeKind: GraphQLEnumType; diff --git a/types/graphql/type/scalars.d.ts b/types/graphql/type/scalars.d.ts index 6c01256643..31a33aafad 100644 --- a/types/graphql/type/scalars.d.ts +++ b/types/graphql/type/scalars.d.ts @@ -1,6 +1,5 @@ import { GraphQLScalarType } from './definition'; - export const GraphQLInt: GraphQLScalarType; export const GraphQLFloat: GraphQLScalarType; export const GraphQLString: GraphQLScalarType; diff --git a/types/graphql/type/schema.d.ts b/types/graphql/type/schema.d.ts index 01bd3b1ca5..2d0c5c7f3d 100644 --- a/types/graphql/type/schema.d.ts +++ b/types/graphql/type/schema.d.ts @@ -10,7 +10,6 @@ import { GraphQLDirective, } from './directives'; - /** * Schema Definition * @@ -53,14 +52,14 @@ export class GraphQLSchema { getSubscriptionType(): GraphQLObjectType|null|undefined; getTypeMap(): { [typeName: string]: GraphQLNamedType }; getType(name: string): GraphQLType; - getPossibleTypes(abstractType: GraphQLAbstractType): Array; + getPossibleTypes(abstractType: GraphQLAbstractType): GraphQLObjectType[]; isPossibleType( abstractType: GraphQLAbstractType, possibleType: GraphQLObjectType ): boolean; - getDirectives(): Array; + getDirectives(): GraphQLDirective[]; getDirective(name: string): GraphQLDirective; } @@ -68,6 +67,6 @@ export interface GraphQLSchemaConfig { query: GraphQLObjectType; mutation?: GraphQLObjectType; subscription?: GraphQLObjectType; - types?: Array; - directives?: Array; + types?: GraphQLNamedType[]; + directives?: GraphQLDirective[]; } diff --git a/types/graphql/utilities/TypeInfo.d.ts b/types/graphql/utilities/TypeInfo.d.ts index b4fa855569..98a53d37ef 100644 --- a/types/graphql/utilities/TypeInfo.d.ts +++ b/types/graphql/utilities/TypeInfo.d.ts @@ -36,10 +36,8 @@ export class TypeInfo { leave(node: ASTNode): any; } -export interface getFieldDef { - ( - schema: GraphQLSchema, - parentType: GraphQLType, - fieldNode: FieldNode - ): GraphQLField -} +export type getFieldDef = ( + schema: GraphQLSchema, + parentType: GraphQLType, + fieldNode: FieldNode, +) => GraphQLField; diff --git a/types/graphql/utilities/assertValidName.d.ts b/types/graphql/utilities/assertValidName.d.ts index 6104a26063..5ca2310a26 100644 --- a/types/graphql/utilities/assertValidName.d.ts +++ b/types/graphql/utilities/assertValidName.d.ts @@ -1,2 +1,2 @@ // Helper to assert that provided names are valid. -export function assertValidName(name: string): void; \ No newline at end of file +export function assertValidName(name: string): void; diff --git a/types/graphql/utilities/astFromValue.d.ts b/types/graphql/utilities/astFromValue.d.ts index 3d8ecdd0ec..44745c5e6c 100644 --- a/types/graphql/utilities/astFromValue.d.ts +++ b/types/graphql/utilities/astFromValue.d.ts @@ -1,12 +1,15 @@ import { ValueNode, - //IntValueNode, - //FloatValueNode, - //StringValueNode, - //BooleanValueNode, - //EnumValueNode, - //ListValueNode, - //ObjectValueNode, + /* + TODO: + IntValueNode, + FloatValueNode, + StringValueNode, + BooleanValueNode, + EnumValueNode, + ListValueNode, + ObjectValueNode, + */ } from '../language/ast'; import { GraphQLInputType } from '../type/definition'; @@ -30,4 +33,4 @@ import { GraphQLInputType } from '../type/definition'; export function astFromValue( value: any, type: GraphQLInputType -): ValueNode // Warning: there is a code in bottom: throw new TypeError +): ValueNode; // Warning: there is a code in bottom: throw new TypeError diff --git a/types/graphql/utilities/buildASTSchema.d.ts b/types/graphql/utilities/buildASTSchema.d.ts index 94f4e2a47a..b20c8fc856 100644 --- a/types/graphql/utilities/buildASTSchema.d.ts +++ b/types/graphql/utilities/buildASTSchema.d.ts @@ -2,7 +2,6 @@ import { DocumentNode, Location } from '../language/ast'; import { Source } from '../language/source'; import { GraphQLSchema } from '../type/schema'; - /** * This takes the ast of a schema document produced by the parse function in * src/language/parser.js. @@ -24,5 +23,5 @@ export function getDescription(node: { loc?: Location }): string; /** * A helper function to build a GraphQLSchema directly from a source * document. -*/ + */ export function buildSchema(source: string | Source): GraphQLSchema; diff --git a/types/graphql/utilities/buildClientSchema.d.ts b/types/graphql/utilities/buildClientSchema.d.ts index 391e651f52..166ec43cf7 100644 --- a/types/graphql/utilities/buildClientSchema.d.ts +++ b/types/graphql/utilities/buildClientSchema.d.ts @@ -1,7 +1,6 @@ import { IntrospectionQuery } from './introspectionQuery'; import { GraphQLSchema } from '../type/schema'; - /** * Build a GraphQLSchema for use by client tools. * diff --git a/types/graphql/utilities/concatAST.d.ts b/types/graphql/utilities/concatAST.d.ts index 1f6fcb985f..405ac69936 100644 --- a/types/graphql/utilities/concatAST.d.ts +++ b/types/graphql/utilities/concatAST.d.ts @@ -1,9 +1,8 @@ import { DocumentNode } from '../language/ast'; - /** * Provided a collection of ASTs, presumably each from different files, * concatenate the ASTs together into batched AST, useful for validating many * GraphQL source files which together represent one conceptual application. */ -export function concatAST(asts: Array): DocumentNode; +export function concatAST(asts: DocumentNode[]): DocumentNode; diff --git a/types/graphql/utilities/extendSchema.d.ts b/types/graphql/utilities/extendSchema.d.ts index 60b91e70b2..f7d00b2fee 100644 --- a/types/graphql/utilities/extendSchema.d.ts +++ b/types/graphql/utilities/extendSchema.d.ts @@ -1,7 +1,6 @@ import { DocumentNode } from '../language/ast'; import { GraphQLSchema } from '../type/schema'; - /** * Produces a new schema given an existing schema and a document which may * contain GraphQL type extensions and definitions. The original schema will diff --git a/types/graphql/utilities/findBreakingChanges.d.ts b/types/graphql/utilities/findBreakingChanges.d.ts index 94a74ced90..78d5a5a95b 100644 --- a/types/graphql/utilities/findBreakingChanges.d.ts +++ b/types/graphql/utilities/findBreakingChanges.d.ts @@ -10,7 +10,6 @@ import { } from '../type/definition'; import { GraphQLSchema } from '../type/schema'; - export const BreakingChangeType: { FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND', FIELD_REMOVED: 'FIELD_REMOVED', @@ -20,17 +19,18 @@ export const BreakingChangeType: { VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM', }; -export type BreakingChangeKey = 'FIELD_CHANGED_KIND' +export type BreakingChangeKey = + | 'FIELD_CHANGED_KIND' | 'FIELD_REMOVED' | 'TYPE_CHANGED_KIND' | 'TYPE_REMOVED' | 'TYPE_REMOVED_FROM_UNION' | 'VALUE_REMOVED_FROM_ENUM'; -export type BreakingChange = { +export interface BreakingChange { type: BreakingChangeKey; description: string; -}; +} /** * Given two schemas, returns an Array containing descriptions of all the types @@ -39,7 +39,7 @@ export type BreakingChange = { export function findBreakingChanges( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array +): BreakingChange[]; /** * Given two schemas, returns an Array containing descriptions of any breaking @@ -48,7 +48,7 @@ export function findBreakingChanges( export function findRemovedTypes( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array +): BreakingChange[]; /** * Given two schemas, returns an Array containing descriptions of any breaking @@ -57,7 +57,7 @@ export function findRemovedTypes( export function findTypesThatChangedKind( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array +): BreakingChange[]; /** * Given two schemas, returns an Array containing descriptions of any breaking @@ -67,7 +67,7 @@ export function findTypesThatChangedKind( export function findFieldsThatChangedType( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array; +): BreakingChange[]; /** * Given two schemas, returns an Array containing descriptions of any breaking @@ -76,7 +76,7 @@ export function findFieldsThatChangedType( export function findTypesRemovedFromUnions( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array; +): BreakingChange[]; /** * Given two schemas, returns an Array containing descriptions of any breaking @@ -85,4 +85,4 @@ export function findTypesRemovedFromUnions( export function findValuesRemovedFromEnums( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array; +): BreakingChange[]; diff --git a/types/graphql/utilities/findDeprecatedUsages.d.ts b/types/graphql/utilities/findDeprecatedUsages.d.ts index 58e9ae1685..8f6ff48239 100644 --- a/types/graphql/utilities/findDeprecatedUsages.d.ts +++ b/types/graphql/utilities/findDeprecatedUsages.d.ts @@ -10,4 +10,4 @@ import { GraphQLError } from '../error/GraphQLError'; export function findDeprecatedUsages( schema: GraphQLSchema, ast: DocumentNode -): Array +): GraphQLError[]; diff --git a/types/graphql/utilities/introspectionQuery.d.ts b/types/graphql/utilities/introspectionQuery.d.ts index cb9f0267b6..a89c5c1fec 100644 --- a/types/graphql/utilities/introspectionQuery.d.ts +++ b/types/graphql/utilities/introspectionQuery.d.ts @@ -95,26 +95,25 @@ fragment TypeRef on __Type { */ export const introspectionQuery: string; - export interface IntrospectionQuery { - __schema: IntrospectionSchema + __schema: IntrospectionSchema; } export interface IntrospectionSchema { queryType: IntrospectionNamedTypeRef; mutationType?: IntrospectionNamedTypeRef; subscriptionType?: IntrospectionNamedTypeRef; - types: Array; - directives: Array; + types: IntrospectionType[]; + directives: IntrospectionDirective[]; } export type IntrospectionType = - IntrospectionScalarType | - IntrospectionObjectType | - IntrospectionInterfaceType | - IntrospectionUnionType | - IntrospectionEnumType | - IntrospectionInputObjectType; + | IntrospectionScalarType + | IntrospectionObjectType + | IntrospectionInterfaceType + | IntrospectionUnionType + | IntrospectionEnumType + | IntrospectionInputObjectType; export interface IntrospectionScalarType { kind: 'SCALAR'; @@ -126,43 +125,43 @@ export interface IntrospectionObjectType { kind: 'OBJECT'; name: string; description?: string; - fields: Array; - interfaces: Array; + fields: IntrospectionField[]; + interfaces: IntrospectionNamedTypeRef[]; } export interface IntrospectionInterfaceType { kind: 'INTERFACE'; name: string; description?: string; - fields: Array; - possibleTypes: Array; + fields: IntrospectionField[]; + possibleTypes: IntrospectionNamedTypeRef[]; } export interface IntrospectionUnionType { kind: 'UNION'; name: string; description?: string; - possibleTypes: Array; + possibleTypes: IntrospectionNamedTypeRef[]; } export interface IntrospectionEnumType { kind: 'ENUM'; name: string; description?: string; - enumValues: Array; + enumValues: IntrospectionEnumValue[]; } export interface IntrospectionInputObjectType { kind: 'INPUT_OBJECT'; name: string; description?: string; - inputFields: Array; + inputFields: IntrospectionInputValue[]; } export type IntrospectionTypeRef = - IntrospectionNamedTypeRef | - IntrospectionListTypeRef | - IntrospectionNonNullTypeRef + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + | IntrospectionNonNullTypeRef; export interface IntrospectionNamedTypeRef { kind: string; @@ -182,7 +181,7 @@ export interface IntrospectionNonNullTypeRef { export interface IntrospectionField { name: string; description?: string; - args: Array; + args: IntrospectionInputValue[]; type: IntrospectionTypeRef; isDeprecated: boolean; deprecationReason?: string; @@ -205,6 +204,6 @@ export interface IntrospectionEnumValue { export interface IntrospectionDirective { name: string; description?: string; - locations: Array; - args: Array; + locations: DirectiveLocationEnum[]; + args: IntrospectionInputValue[]; } diff --git a/types/graphql/utilities/isValidJSValue.d.ts b/types/graphql/utilities/isValidJSValue.d.ts index a06706ec2c..cd11014579 100644 --- a/types/graphql/utilities/isValidJSValue.d.ts +++ b/types/graphql/utilities/isValidJSValue.d.ts @@ -8,4 +8,4 @@ import { GraphQLInputType } from '../type/definition'; export function isValidJSValue( value: any, type: GraphQLInputType -): Array +): string[]; diff --git a/types/graphql/utilities/isValidLiteralValue.d.ts b/types/graphql/utilities/isValidLiteralValue.d.ts index 71f7471a70..697c8eb97e 100644 --- a/types/graphql/utilities/isValidLiteralValue.d.ts +++ b/types/graphql/utilities/isValidLiteralValue.d.ts @@ -11,4 +11,4 @@ import { GraphQLInputType } from '../type/definition'; export function isValidLiteralValue( type: GraphQLInputType, valueNode: ValueNode -): Array +): string[]; diff --git a/types/graphql/utilities/separateOperations.d.ts b/types/graphql/utilities/separateOperations.d.ts index b5d9e7439a..4b4106df53 100644 --- a/types/graphql/utilities/separateOperations.d.ts +++ b/types/graphql/utilities/separateOperations.d.ts @@ -5,4 +5,4 @@ import { export function separateOperations( documentAST: DocumentNode -): { [operationName: string]: DocumentNode } +): { [operationName: string]: DocumentNode }; diff --git a/types/graphql/utilities/typeComparators.d.ts b/types/graphql/utilities/typeComparators.d.ts index f9442914d3..16e6acd680 100644 --- a/types/graphql/utilities/typeComparators.d.ts +++ b/types/graphql/utilities/typeComparators.d.ts @@ -7,7 +7,6 @@ import { GraphQLSchema } from '../type/schema'; - /** * Provided two types, return true if the types are equal (invariant). */ diff --git a/types/graphql/utilities/typeFromAST.d.ts b/types/graphql/utilities/typeFromAST.d.ts index ce1c8b061f..c3cacf90df 100644 --- a/types/graphql/utilities/typeFromAST.d.ts +++ b/types/graphql/utilities/typeFromAST.d.ts @@ -5,4 +5,4 @@ import { GraphQLSchema } from '../type/schema'; export function typeFromAST( schema: GraphQLSchema, typeNode: TypeNode -): GraphQLType +): GraphQLType; diff --git a/types/graphql/utilities/valueFromAST.d.ts b/types/graphql/utilities/valueFromAST.d.ts index a292e079ab..24dd435448 100644 --- a/types/graphql/utilities/valueFromAST.d.ts +++ b/types/graphql/utilities/valueFromAST.d.ts @@ -6,7 +6,6 @@ import { ObjectValueNode } from '../language/ast'; - export function valueFromAST( valueNode: ValueNode, type: GraphQLInputType, diff --git a/types/graphql/validation/validate.d.ts b/types/graphql/validation/validate.d.ts index 9f4a9afdad..a4b628777e 100644 --- a/types/graphql/validation/validate.d.ts +++ b/types/graphql/validation/validate.d.ts @@ -19,9 +19,6 @@ import { GraphQLDirective } from '../type/directives'; import { TypeInfo } from '../utilities/TypeInfo'; import { specifiedRules } from './specifiedRules'; - -//type ValidationRule = (context: ValidationContext) => any; - /** * Implements the "Validation" section of the spec. * @@ -38,8 +35,8 @@ import { specifiedRules } from './specifiedRules'; export function validate( schema: GraphQLSchema, ast: DocumentNode, - rules?: Array -): Array; + rules?: any[] +): GraphQLError[]; /** * This uses a specialized visitor which runs multiple visitors in parallel, @@ -51,13 +48,13 @@ export function visitUsingRules( schema: GraphQLSchema, typeInfo: TypeInfo, documentAST: DocumentNode, - rules: Array -): Array; + rules: any[] +): GraphQLError[]; export type NodeWithSelectionSet = OperationDefinitionNode | FragmentDefinitionNode; export interface VariableUsage { - node: VariableNode, - type: GraphQLInputType + node: VariableNode; + type: GraphQLInputType; } /** @@ -69,7 +66,7 @@ export class ValidationContext { constructor(schema: GraphQLSchema, ast: DocumentNode, typeInfo: TypeInfo); reportError(error: GraphQLError): void; - getErrors(): Array; + getErrors(): GraphQLError[]; getSchema(): GraphQLSchema; @@ -77,17 +74,17 @@ export class ValidationContext { getFragment(name: string): FragmentDefinitionNode; - getFragmentSpreads(node: SelectionSetNode): Array; + getFragmentSpreads(node: SelectionSetNode): FragmentSpreadNode[]; getRecursivelyReferencedFragments( operation: OperationDefinitionNode - ): Array; + ): FragmentDefinitionNode[]; - getVariableUsages(node: NodeWithSelectionSet): Array; + getVariableUsages(node: NodeWithSelectionSet): VariableUsage[]; getRecursiveVariableUsages( operation: OperationDefinitionNode - ): Array; + ): VariableUsage[]; getType(): GraphQLOutputType; @@ -100,4 +97,4 @@ export class ValidationContext { getDirective(): GraphQLDirective; getArgument(): GraphQLArgument; -} \ No newline at end of file +} diff --git a/types/gulp-watch/index.d.ts b/types/gulp-watch/index.d.ts index f9855f09a6..8b96e78c97 100644 --- a/types/gulp-watch/index.d.ts +++ b/types/gulp-watch/index.d.ts @@ -5,7 +5,7 @@ /// -import {SrcOptions} from "vinyl-fs"; +import { SrcOptions } from "vinyl-fs"; interface IOptions extends SrcOptions { ignoreInitial?: boolean; diff --git a/types/handlebars/index.d.ts b/types/handlebars/index.d.ts index 56c341aa47..006ef242c3 100644 --- a/types/handlebars/index.d.ts +++ b/types/handlebars/index.d.ts @@ -308,3 +308,7 @@ declare namespace hbs { declare module "handlebars" { export = Handlebars; } + +declare module "handlebars/handlebars.runtime" { + export = Handlebars; +} diff --git a/types/hapi-auth-jwt2/index.d.ts b/types/hapi-auth-jwt2/index.d.ts index 2e5826e044..0109bfb33d 100644 --- a/types/hapi-auth-jwt2/index.d.ts +++ b/types/hapi-auth-jwt2/index.d.ts @@ -2,7 +2,7 @@ // Project: http://github.com/dwyl/hapi-auth-jwt2 // Definitions by: Warren Seymour // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {Request, Response, PluginFunction} from 'hapi'; +import { Request, Response, PluginFunction } from 'hapi'; declare namespace hapiAuthJwt2 { /** diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 91432e1d1f..789a181efd 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -42,7 +42,7 @@ import { type JoiValidationObject = JoiSchema | JoiSchemaMap | (JoiSchema | JoiSchemaMap)[]; import * as Catbox from 'catbox'; -import {MimosOptions} from 'mimos'; +import { MimosOptions } from 'mimos'; import Podium = require('podium'); import * as Shot from 'shot'; diff --git a/types/hasha/hasha-tests.ts b/types/hasha/hasha-tests.ts new file mode 100644 index 0000000000..d0054de81a --- /dev/null +++ b/types/hasha/hasha-tests.ts @@ -0,0 +1,19 @@ +import hasha = require('hasha'); + +let str: string | null; +let buf: Buffer | null; + +str = hasha('unicorn'); +str = hasha('unicorn', {algorithm: 'md5'}); +str = hasha('unicorn', {algorithm: 'md5', encoding: 'latin1'}); +buf = hasha('unicorn', {algorithm: 'md5', encoding: 'buffer'}); + +process.stdin.pipe(hasha.stream()).pipe(process.stdout); + +hasha.fromStream(process.stdin).then(hash => str = hash); +hasha.fromStream(process.stdin, {encoding: 'hex'}).then(hash => str = hash); +hasha.fromStream(process.stdin, {encoding: 'buffer'}).then(hash => buf = hash); + +hasha.fromFile('unicorn.png').then(hash => str = hash); +hasha.fromFile('unicorn.png', {encoding: 'base64'}).then(hash => str = hash); +hasha.fromFile('unicorn.png', {encoding: 'buffer'}).then(hash => buf = hash); diff --git a/types/hasha/index.d.ts b/types/hasha/index.d.ts new file mode 100644 index 0000000000..a158af88a3 --- /dev/null +++ b/types/hasha/index.d.ts @@ -0,0 +1,38 @@ +// Type definitions for hasha 3.0 +// Project: https://github.com/sindresorhus/hasha +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as crypto from "crypto"; + +export = hasha; + +declare function hasha(input: hasha.HashaInput): string; +declare function hasha(input: hasha.HashaInput, options: hasha.HashaOptions): string; +declare function hasha(input: hasha.HashaInput, options: hasha.HashaOptions): Buffer; + +declare namespace hasha { + type HashaInput = string | string[] | Buffer | Buffer[]; + type ToStringEncoding = 'hex' | 'base64' | 'latin1' | 'binary' | undefined; + type HashaEncoding = ToStringEncoding | 'buffer'; + + interface HashaOptions { + encoding?: E; + algorithm?: string; + } + + function stream(options?: HashaOptions): crypto.Hash; + + function fromStream(stream: NodeJS.ReadableStream): Promise; + function fromStream(stream: NodeJS.ReadableStream, options?: HashaOptions): Promise; + function fromStream(stream: NodeJS.ReadableStream, options?: HashaOptions): Promise; + + function fromFile(filePath: string): Promise; + function fromFile(filePath: string, options: HashaOptions): Promise; + function fromFile(filePath: string, options: HashaOptions): Promise; + + function fromFileSync(filePath: string): string; + function fromFileSync(filePath: string, options: HashaOptions): string; + function fromFileSync(filePath: string, options: HashaOptions): Buffer; +} diff --git a/types/hasha/tsconfig.json b/types/hasha/tsconfig.json new file mode 100644 index 0000000000..3aeb5973e8 --- /dev/null +++ b/types/hasha/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", + "hasha-tests.ts" + ] +} diff --git a/types/hasha/tslint.json b/types/hasha/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hasha/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index 4a252c899f..914fb83f96 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -6694,6 +6694,8 @@ declare namespace Highcharts { getOptions(): Options; map(array: any[], fn: Function): any[]; + + wrap(prototype: any, type: string, cb: (proceed: Function, ...args: any[]) => void): void; } /** diff --git a/types/i18next-express-middleware/index.d.ts b/types/i18next-express-middleware/index.d.ts index 6676c5c9fa..f9877b2659 100644 --- a/types/i18next-express-middleware/index.d.ts +++ b/types/i18next-express-middleware/index.d.ts @@ -2,6 +2,7 @@ // Project: http://i18next.com/ // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 declare namespace I18next { interface I18nextOptions extends i18nextExpressMiddleware.I18nextOptions { } @@ -94,8 +95,8 @@ declare module "i18next-express-middleware" { init(services: any, options?: Object, allOptions?: Object): void; } - export function getResourcesHandler(i18next: i18next.I18n, options: Object): express.Handler; - export function handle(i18next: i18next.I18n, options?: Object): express.Handler; + export function getResourcesHandler(i18next: i18next.i18n, options: Object): express.Handler; + export function handle(i18next: i18next.i18n, options?: Object): express.Handler; /** * @summary Gets handler for missing key. @@ -103,5 +104,5 @@ declare module "i18next-express-middleware" { * @param {Object} options The options. * @return {express.Handler} The express handler. */ - export function missingKeyHandler(i18next: i18next.I18n, options: Object): express.Handler; + export function missingKeyHandler(i18next: i18next.i18n, options: Object): express.Handler; } diff --git a/types/i18next-express-middleware/tsconfig.json b/types/i18next-express-middleware/tsconfig.json index a194e6465c..6f42d82105 100644 --- a/types/i18next-express-middleware/tsconfig.json +++ b/types/i18next-express-middleware/tsconfig.json @@ -11,11 +11,6 @@ "typeRoots": [ "../" ], - "paths": { - "i18next": [ - "i18next/v2" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/iconv/iconv-tests.ts b/types/iconv/iconv-tests.ts index 396c207279..d3d9bff917 100644 --- a/types/iconv/iconv-tests.ts +++ b/types/iconv/iconv-tests.ts @@ -1,5 +1,5 @@ import Iconv = require("iconv"); -import {Writable} from "stream"; +import { Writable } from "stream"; const iconv: Iconv.Iconv = new Iconv("utf-8", "cp932"); const iconvFromFunction: Iconv.Iconv = Iconv("utf-8", "cp932"); diff --git a/types/imap-simple/imap-simple-tests.ts b/types/imap-simple/imap-simple-tests.ts index 39236023d5..9161ebb832 100644 --- a/types/imap-simple/imap-simple-tests.ts +++ b/types/imap-simple/imap-simple-tests.ts @@ -81,3 +81,21 @@ imaps.connect(config).then(function (connection) { // { filename: "pay-stub.pdf", data: Buffer() } ] }); }); + +imaps.connect({ + imap: config.imap, + onmail: function (numNewMail) { + //... + }, + onexpunge: function (seqno) { + //... + }, + onupdate: function (seqno, info) { + //... + } +}).then(function (connection) { + connection.on("error", err => { + console.error("imap socket error", err); + }) +}); + diff --git a/types/imap-simple/index.d.ts b/types/imap-simple/index.d.ts index 765c8a5f0a..9f851ae21b 100644 --- a/types/imap-simple/index.d.ts +++ b/types/imap-simple/index.d.ts @@ -1,8 +1,10 @@ -// Type definitions for imap-simple v1.6.3 +// Type definitions for imap-simple v3.1.0 // Project: https://github.com/chadxz/imap-simple // Definitions by: Jeffery Grajkowski // Definitions: https://github.com/psnider/DefinitelyTyped/imap-simple +/// + import Imap = require("imap"); export interface ImapSimpleOptions { @@ -11,6 +13,15 @@ export interface ImapSimpleOptions { /** Time in milliseconds to wait before giving up on a connection attempt. (Deprecated: please use options.imap.authTimeout instead) */ connectTimeout?: number; + + /** Server event emitted when new mail arrives in the currently open mailbox. */ + onmail?: (numNewMail: number) => void; + + /** Server event emitted when a message was expunged externally. seqno is the sequence number (instead of the unique UID) of the message that was expunged. If you are caching sequence numbers, all sequence numbers higher than this value MUST be decremented by 1 in order to stay synchronized with the server and to keep correct continuity. */ + onexpunge?: (seqno: number) => void; + + /** Server event emitted when message metadata (e.g. flags) changes externally. */ + onupdate?: (seqno: number, info: any) => void; } export interface MessageBodyPart extends Imap.ImapMessageBodyInfo { @@ -21,9 +32,10 @@ export interface MessageBodyPart extends Imap.ImapMessageBodyInfo { export interface Message { attributes: Imap.ImapMessageAttributes; parts: MessageBodyPart[]; + seqno: number; } -export class ImapSimple { +export class ImapSimple extends NodeJS.EventEmitter { constructor(imap: Imap); /** Open a mailbox, calling the provided callback with signature (err, boxName), or resolves the returned promise with boxName. */ @@ -48,6 +60,14 @@ export class ImapSimple { /** Moves the specified message(s) in the currently open mailbox to another mailbox. source corresponds to a node-imap MessageSource which specifies the messages to be moved. When completed, either calls the provided callback with signature (err), or resolves the returned promise. */ moveMessage(source: string | string[], boxName: string, callback: (err: Error) => void): void; moveMessage(source: string | string[], boxName: string): Promise; + + /** Adds the provided flag(s) to the specified message(s). uid is the uid of the message you want to add the flag to or an array of uids. flag is either a string or array of strings indicating the flags to add. */ + addFlags(source: string | string[], flag: string | string[], callback: (err: Error) => void): void; + addFlags(source: string | string[], flag: string | string[]): Promise; + + /** Removes the provided flag(s) from the specified message(s). uid is the uid of the message you want to remove the flag from or an array of uids. flag is either a string or array of strings indicating the flags to remove. */ + delFlags(source: string | string[], flag: string | string[], callback: (err: Error) => void): void; + delFlags(source: string | string[], flag: string | string[]): Promise; } export namespace errors { @@ -58,7 +78,6 @@ export namespace errors { } } - /** Main entry point. Connect to an Imap server. */ export function connect(options: ImapSimpleOptions, callback: (err: Error, connection: ImapSimple) => void): void; export function connect(options: ImapSimpleOptions): Promise; diff --git a/types/inherits/index.d.ts b/types/inherits/index.d.ts index 0c8b2f0f8c..4ae7eef4c5 100644 --- a/types/inherits/index.d.ts +++ b/types/inherits/index.d.ts @@ -6,5 +6,5 @@ /// -import {inherits} from "util"; +import { inherits } from "util"; export = inherits; diff --git a/types/into-stream/index.d.ts b/types/into-stream/index.d.ts new file mode 100644 index 0000000000..f682ff10a7 --- /dev/null +++ b/types/into-stream/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for into-stream 3.1 +// Project: https://github.com/sindresorhus/into-stream +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +export = intoStream; + +declare function intoStream(input: intoStream.Input | Promise): NodeJS.ReadableStream; + +declare namespace intoStream { + function obj(input: object | Iterable | Promise>): NodeJS.ReadableStream; + + type Input = Buffer | string | Iterable; +} diff --git a/types/into-stream/into-stream-tests.ts b/types/into-stream/into-stream-tests.ts new file mode 100644 index 0000000000..e1f3a9a7b0 --- /dev/null +++ b/types/into-stream/into-stream-tests.ts @@ -0,0 +1,27 @@ +import intoStream = require('into-stream'); + +function iterableFrom(arr: any[]) { + return { + *[Symbol.iterator]() { + let i = 0; + while (i < arr.length) { + yield arr[i++]; + } + } + }; +} + +intoStream('unicorn').pipe(process.stdout); +intoStream('unicorn'.split('')).pipe(process.stdout); +intoStream(iterableFrom('unicorn'.split(''))).pipe(process.stdout); +intoStream(new Buffer('unicorn')).pipe(process.stdout); +intoStream(Promise.resolve('unicorn')).pipe(process.stdout); + +const f = {foo: true}; +const f2 = [{foo: true}, {bar: true}]; +intoStream.obj(f).pipe(process.stdout); +intoStream.obj(f2).pipe(process.stdout); +intoStream.obj(iterableFrom(f2)).pipe(process.stdout); +intoStream.obj(Promise.resolve(f)).pipe(process.stdout); +intoStream.obj(Promise.resolve(f2)).pipe(process.stdout); +intoStream.obj(Promise.resolve(iterableFrom(f2))).pipe(process.stdout); diff --git a/types/into-stream/tsconfig.json b/types/into-stream/tsconfig.json new file mode 100644 index 0000000000..c48cf3e387 --- /dev/null +++ b/types/into-stream/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", + "into-stream-tests.ts" + ] +} diff --git a/types/into-stream/tslint.json b/types/into-stream/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/into-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-ip/index.d.ts b/types/is-ip/index.d.ts new file mode 100644 index 0000000000..930cb8951d --- /dev/null +++ b/types/is-ip/index.d.ts @@ -0,0 +1,35 @@ +// Type definitions for is-ip 2.0 +// Project: https://github.com/sindresorhus/is-ip#readme +// Definitions by: coderslagoon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Check if input is IPv4 or IPv6. + * + * @param {input} input + * + * @returns {boolean} + */ +declare function isIp(input: string): boolean; + +declare namespace isIp { + /** + * Check if input is IPv4. + * + * @param {input} input + * + * @returns {boolean} + */ + function v4(input: string): boolean; + + /** + * Check if input is IPv6. + * + * @param {input} input + * + * @returns {boolean} + */ + function v6(input: string): boolean; +} + +export = isIp; diff --git a/types/is-ip/is-ip-tests.ts b/types/is-ip/is-ip-tests.ts new file mode 100644 index 0000000000..d062f6dde9 --- /dev/null +++ b/types/is-ip/is-ip-tests.ts @@ -0,0 +1,28 @@ +import * as isIp from "is-ip"; + +isIp("nope"); +// => false + +isIp("127.0.0.1"); +// => true + +isIp("0.0.0.0"); +// => true + +isIp("127.0.0.256"); +// => false + +isIp.v4("127.0.0.1"); +// => true + +isIp.v4("1:2:3:4:5:6:7:8"); +// => false + +isIp.v6("1:2:3:4:5:6:7:8"); +// => true + +isIp.v6("::"); +// => true + +isIp.v6("127.0.0.1"); +// => false diff --git a/types/is-ip/tsconfig.json b/types/is-ip/tsconfig.json new file mode 100644 index 0000000000..be6e5c55e0 --- /dev/null +++ b/types/is-ip/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", + "is-ip-tests.ts" + ] +} diff --git a/types/is-ip/tslint.json b/types/is-ip/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-ip/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-stream/index.d.ts b/types/is-stream/index.d.ts new file mode 100644 index 0000000000..0c24d084d9 --- /dev/null +++ b/types/is-stream/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for is-stream 1.1 +// Project: https://github.com/sindresorhus/is-stream#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as stream from "stream"; + +export = isStream; + +declare function isStream(maybeStream: any): maybeStream is stream.Stream; + +declare namespace isStream { + function writable(maybeWritable: any): maybeWritable is stream.Writable; + function readable(maybeReadable: any): maybeReadable is stream.Readable; + function duplex(maybeDuplex: any): maybeDuplex is stream.Duplex; + function transform(maybeTransform: any): maybeTransform is stream.Transform; +} diff --git a/types/is-stream/is-stream-tests.ts b/types/is-stream/is-stream-tests.ts new file mode 100644 index 0000000000..9d9eb315b4 --- /dev/null +++ b/types/is-stream/is-stream-tests.ts @@ -0,0 +1,24 @@ +import isStream = require('is-stream'); +import * as stream from 'stream'; + +const anyStream: any = new stream.Stream(); + +if (isStream(anyStream)) { + const justStream: stream.Stream = anyStream; +} + +if (isStream.writable(anyStream)) { + const writableStream: stream.Writable = anyStream; +} + +if (isStream.readable(anyStream)) { + const readableStream: stream.Readable = anyStream; +} + +if (isStream.duplex(anyStream)) { + const duplexStream: stream.Duplex = anyStream; +} + +if (isStream.transform(anyStream)) { + const transformStream: stream.Transform = anyStream; +} diff --git a/types/is-stream/tsconfig.json b/types/is-stream/tsconfig.json new file mode 100644 index 0000000000..926737569f --- /dev/null +++ b/types/is-stream/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", + "is-stream-tests.ts" + ] +} diff --git a/types/is-stream/tslint.json b/types/is-stream/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-svg/index.d.ts b/types/is-svg/index.d.ts new file mode 100644 index 0000000000..21e85cd2e2 --- /dev/null +++ b/types/is-svg/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for is-svg 2.1 +// Project: https://github.com/sindresorhus/is-svg#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isSvg; + +declare function isSvg(input: string): boolean; diff --git a/types/is-svg/is-svg-tests.ts b/types/is-svg/is-svg-tests.ts new file mode 100644 index 0000000000..d556a944f9 --- /dev/null +++ b/types/is-svg/is-svg-tests.ts @@ -0,0 +1,3 @@ +import isSvg = require('is-svg'); + +const result: boolean = isSvg(''); diff --git a/types/is-svg/tsconfig.json b/types/is-svg/tsconfig.json new file mode 100644 index 0000000000..9776ba1c77 --- /dev/null +++ b/types/is-svg/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", + "is-svg-tests.ts" + ] +} diff --git a/types/is-svg/tslint.json b/types/is-svg/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-svg/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/japanese-holidays/japanese-holidays-tests.ts b/types/japanese-holidays/japanese-holidays-tests.ts index 32f760360e..a3f77b2dc4 100644 --- a/types/japanese-holidays/japanese-holidays-tests.ts +++ b/types/japanese-holidays/japanese-holidays-tests.ts @@ -1,4 +1,4 @@ -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); diff --git a/types/jdenticon/jdenticon-tests.ts b/types/jdenticon/jdenticon-tests.ts index b26a01696b..aaa5abc531 100644 --- a/types/jdenticon/jdenticon-tests.ts +++ b/types/jdenticon/jdenticon-tests.ts @@ -1,4 +1,4 @@ -import {jdenticon} from "jdenticon"; +import { jdenticon } from "jdenticon"; function testJdenticon() { if (typeof jdenticon.version !== 'string') { diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 633af80085..267f1d4a1a 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -729,7 +729,7 @@ declare namespace jest { type TestResultsProcessor = (testResult: AggregatedResult) => AggregatedResult; type HasteResolver = any; // import HasteResolver from 'jest-resolve'; - type ModuleMocker = any; // import {ModuleMocker} from 'jest-mock'; + type ModuleMocker = any; // import { ModuleMocker } from 'jest-mock'; type ModuleMap = any; // import {ModuleMap} from 'jest-haste-map'; type HasteFS = any; // import {FS as HasteFS} from 'jest-haste-map'; type Runtime = any; // import Runtime from 'jest-runtime'; diff --git a/types/jpm/jpm-tests.ts b/types/jpm/jpm-tests.ts index 526bbe6063..34523f1a14 100644 --- a/types/jpm/jpm-tests.ts +++ b/types/jpm/jpm-tests.ts @@ -100,7 +100,7 @@ console.log(urls.toFilename(urls.URL("http://example.com"))); console.log(urls.DataURL("file:///my/path/file.txt").mimeType); import * as windows from "sdk/windows"; -import {stringify} from "sdk/querystring"; +import { stringify } from "sdk/querystring"; for (let window of windows.browserWindows) { console.info(window.title); } diff --git a/types/jquery-editable-select/index.d.ts b/types/jquery-editable-select/index.d.ts new file mode 100644 index 0000000000..43ae7065ae --- /dev/null +++ b/types/jquery-editable-select/index.d.ts @@ -0,0 +1,71 @@ +// Type definitions for jquery-editable-select 2.2 +// Project: https://github.com/indrimuska/jquery-editable-select +// Definitions by: Vincent Biret +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +declare namespace JQueryEditableSelect { + interface EditableSelectOptions { + /** + * Filter (or not) items in list while typing. + */ + filter?: boolean; + /** + * Easing used for showing and hiding the dropdown list. + */ + effects?: 'default' | 'slide' | 'fade'; + /** + * Duration of the easings (in milliseconds). + */ + duration?: number | 'fast' | 'slow'; + /** + * Where to append the dropdown list in the DOM. + */ + appendTo?: string | JQuery; + /** + * How dropdown list is triggered. + */ + trigger?: 'focus'| 'manual'; + } +} + +interface JQuery { + /** + * Transforms the component. - */ interface EventOrValueHandler { (event: Event): void; - (value: FieldValue, newValue: FieldValue, previousValue: FieldValue): void; + (value: any, newValue: any, previousValue: any): void; } -interface WrappedFieldInputProps { - /** - * An alias for value only when value is a boolean. Provided for - * convenience of destructuring the whole field object into the props of a - * form element. - */ +interface WrappedFieldInputProps extends CommonFieldProps { checked?: boolean; - - /** - * The name prop passed in. - */ - name: string; - - /** - * A function to call when the form field loses focus. - */ - onBlur: EventOrValueHandler>; - - /** - * A function to call when the form field is changed. - */ - onChange: EventOrValueHandler>; - - /** - * A function to call when the form field receives a 'dragStart' event. - * Saves the field value in the event for giving the field it is dropped - * into. - */ - onDragStart: EventOrValueHandler>; - - /** - * A function to call when the form field receives a drop event. - */ - onDrop: EventOrValueHandler>; - - /** - * A function to call when the form field receives focus. - */ - onFocus: EventOrValueHandler>; - - /** - * The value of this form field. It will be a boolean for checkboxes, and - * a string for all other input types. If there is no value in the Redux - * state for this field, it will default to ''. This is to - * ensure that the input is controlled. - */ - value: FieldValue; + value: any; } -/** - * These props are metadata about the state of this field that redux-form is tracking for you. - */ -interface WrappedFieldMetaProps { - - /** - * true if this field currently has focus. It will only work if you are - * passing onFocus to your input element. - */ +interface WrappedFieldMetaProps { active?: boolean; - - /** - * true if this field has been set with the AUTOFILL action and has not since been changed - * with a CHANGE action. This is useful to render the field in a way that the user can tell - * that the value was autofilled for them. - */ autofilled: boolean; - - /** - * true if the form is currently running asynchronous validation because this - * field was blurred. - */ asyncValidating: boolean; - - /** - * true if the field value has changed from its initialized value. - * Opposite of pristine. - */ dirty: boolean; - - /** - * The Redux dispatch function. - */ - dispatch: Dispatch; - - /** - * The error for this field if its value is not passing validation. Both - * synchronous, asynchronous, and submit validation errors will be reported here. - */ + dispatch: Dispatch; error?: any; - - /** - * The name of the form. Could be useful if you want to manually dispatch actions. - */ - form?: string; - - /** - * true if the field value fails validation (has a validation error). - * Opposite of valid. - */ + form: string; + initial: any; invalid: boolean; - - /** - * true if the field value is the same as its initialized value. Opposite - * of dirty. - */ pristine: boolean; - - /** - * true if the field is currently being submitted - */ - submitting?: boolean; - - /** - * true if the form had onSubmit called and failed to submit for any reason. - * A subsequent successful submit will set it back to false. - */ - submitFailed?: boolean; - - /** - * true if the field has been touched. By default this will be set when - * the field is blurred. - */ + submitting: boolean; + submitFailed: boolean; touched: boolean; - - /** - * true if the field value passes validation (has no validation errors). - * Opposite of invalid. - */ valid: boolean; - - /** - * true if this field has ever had focus. It will only work if you are - * passing onFocus to your input element. - */ - visited?: boolean; - - /** - * The warning for this field if its value is not passing warning validation. - */ + visited: boolean; warning?: any; } diff --git a/types/redux-form/lib/FieldArray.d.ts b/types/redux-form/lib/FieldArray.d.ts index 9629eecb27..724f1f19c6 100644 --- a/types/redux-form/lib/FieldArray.d.ts +++ b/types/redux-form/lib/FieldArray.d.ts @@ -1,217 +1,57 @@ -import { Component } from "react"; -import { ComponentConstructor, Validator } from "../index"; +import { Component, ComponentType } from "react"; +import { Validator } from "redux-form"; -/** - * These are the props to give to `FieldArray`. - * Any others will be passed through to your component. - */ -interface BaseFieldArrayProps { - /** - * A string path, in dot-and-bracket notation, corresponding to a value - * in the form values. It may be as simple as 'firstName' or as complicated - * as contact.billing.address[2].phones[1].areaCode. - * - * Required but made optional so interface can be used on decorated components. - */ - name?: string; - - /** - * A Component or stateless function to render the field array. - * - * Required but made optional so interface can be used on decorated components. - */ - component?: ComponentConstructor, - - /** - * Allows you to to provide a field-level validation rule. The function will be given the - * current value of the field and all the other form values. If the field is valid, it - * should return `undefined`, if the field is invalid, it should return an error - * (usually, but not necessarily, a `String`). - */ +interface BaseFieldArrayProps

{ + name: string; + component: ComponentType

, validate?: Validator | Validator[]; - - /** - * Allows you to to provide a field-level warning rule. The function will be given the - * current value of the field and all the other form values. If the field needs a warning, - * it should return the warning (usually, but not necessarily, a `String`). If the field - * does not need a warning, it should return `undefined`. - */ warn?: Validator | Validator[]; - - /** - * If true, the rendered component will be available with the - * getRenderedComponent() method. Defaults to false. Cannot be used if your - * component is a stateless function component. - */ withRef?: boolean; - - props?: any; + props?: P; + rerenderOnEveryChange?: boolean; } -/** - * Declare FieldArray as this interface to specify the generics. - */ -export interface GenericFieldArray extends Component { - - /** - * The name prop that you passed in. - */ +export interface GenericFieldArray extends Component & P> { name: string; - - /** - * true if this field passes validation, false otherwise. - */ valid: boolean; - - /** - * Returns the instance of the rendered component. For this to work, you must - * provide a withRef prop, and your component must not be a stateless function - * component. - */ - getRenderedComponent(): Component & FieldCustomProps>; + getRenderedComponent(): Component & P>; } -/** - * The FieldArray Instance API. - */ -export class FieldArray extends Component implements GenericFieldArray { - - /** - * The name prop that you passed in. - */ +export class FieldArray

extends Component & P> implements GenericFieldArray { name: string; - - /** - * true if this field passes validation, false otherwise. - */ valid: boolean; - - /** - * Returns the instance of the rendered component. For this to work, you must - * provide a withRef prop, and your component must not be a stateless function - * component. - */ - getRenderedComponent(): Component; + getRenderedComponent(): Component & P>; } -/** - * These are props that `FieldArray` will pass to your wrapped component. - */ -interface WrappedFieldArrayProps { - fields: FieldsProps; +interface WrappedFieldArrayProps { + fields: FieldsProps; meta: FieldArrayMetaProps; } -interface FieldsProps { - /** - * A method to iterate over each value of the array. - */ - forEach(callback: (name: string, index: number, fields: FieldsProps) => void): void; +type FieldIterate = (name: string, index: number, fields: FieldsProps) => R; - /** - * A method to get a single value from the array value. - */ - get(index: number): T; - - /** - * A method to get all the values in the array. - */ - getAll(): T[]; - - /** - * A function to insert a new value into the array at any arbitrary index. - */ - insert(index: number, value: T): void; - - /** - * The current length of the array. - */ +interface FieldsProps { + forEach(callback: FieldIterate): void; + get(index: number): FieldValue; + getAll(): FieldValue[]; + insert(index: number, value: FieldValue): void; length: number; - - /** - * A method to iterate over each value of the array. Returns an array of the - * results of each call to the callback. - */ - map(callback: (name: string, index: number, fields: FieldsProps) => any): any; - - /** - * Removes an item from the end of the array. Returns the item removed. - */ - pop(): T; - - /** - * Adds a value to the end of the array. - */ - push(value: T): void; - - /** - * Removes an item from the array at an arbitrary index. - */ + map(callback: FieldIterate): R[]; + pop(): FieldValue; + push(value: FieldValue): void; remove(index: number): void; - - /** - * Removes an item from beginning of the array. Returns the item removed. - */ - shift(): T; - - /** - * Swaps two items in the array at the given indexes. - */ + shift(): FieldValue; swap(indexA: number, indexB: number): void; - - /** - * Adds an item to the beginning of the array. - */ - unshift(value: T): void; + unshift(value: FieldValue): void; } interface FieldArrayMetaProps { - /** - * true if the any of the fields in the field array have changed from their - * initialized value. Opposite of pristine. - */ dirty: boolean; - - /** - * The error for this field array if its value is not passing validation. Both - * synchronous, asynchronous, and submit validation errors will be reported here. - * Array-specific errors should be returned from the validation function as an - * _error key on the array. - */ error?: string; - - /** - * Name of your form provided to `reduxForm()` as the `form` config property. - */ form: string; - - /** - * true if the field array value fails validation (has a validation error). - * Opposite of valid. - */ invalid: boolean; - - /** - * true if the all of the fields in the field array are the same as their - * initialized value. Opposite of dirty. - */ pristine: boolean; - - /** - * true if any of the fields have been touched. - */ - touched: boolean; - - /** - * true if the field value passes validation (has no validation errors). - * Opposite of invalid. - */ + submitting: boolean; valid: boolean; - - /** - * The warning for this field array if its values are not passing warning validation. - * Array-specific errors should be returned from the validation function as an - * `_warning` key on the array. - */ warning?: string; } diff --git a/types/redux-form/lib/Fields.d.ts b/types/redux-form/lib/Fields.d.ts index b2c210ba8c..d3a29dcb13 100644 --- a/types/redux-form/lib/Fields.d.ts +++ b/types/redux-form/lib/Fields.d.ts @@ -1,116 +1,31 @@ -import { Component } from "react"; -import { ComponentConstructor, Formatter, Parser, FieldValue, WrappedFieldProps } from "../index"; +import { Component, ComponentType } from "react"; +import { Formatter, Parser, WrappedFieldProps } from "redux-form"; -/** - * These are the props to give to `Field`. - * Any others will be passed through to your component. - */ -interface BaseFieldsProps { - /** - * An array of strings (or the pseudo-array fields provided by FieldArray), - * in dot-and-bracket notation, corresponding to form values. - * They may be as simple as 'firstName' or as complicated as - * 'contact.billing.address[2].phones[1].areaCode'. - */ +interface BaseFieldsProps

{ names: string[]; - - /** - * A Component or stateless function that will be given all the props necessary - * to render the field inputs. - */ - component?: ComponentConstructor; - - /** - * Formats the value from the Redux store to be displayed in the field input. - * Common use cases are to format Numbers into currencies or Dates into a localized date format. - * - * format is called with the field value and name as arguments and should return the new formatted - * value to be displayed in the field input. - * - * To respect React 15 input behavior there is defaultFormat = value => value == null ? '' : value - * internally used. To disable that you can pass null as format prop. - */ + component?: ComponentType; format?: Formatter | null; - - /** - * Don't use. - */ - props?: any; - - /** - * Parses the value given from the field input component to the type that you want stored in the Redux store. - * Common use cases are to parse currencies into Numbers into currencies or localized date formats into Dates. - * - * parse is called with the field value and name as arguments and should return the new parsed value to be - * stored in the Redux store. - */ + props?: P; parse?: Parser; - - /** - * If true, the rendered component will be available with the getRenderedComponent() method. - * Defaults to false. Cannot be used if your component is a stateless function component. - */ withRef?: boolean; } -/** - * Declare Fields as this interface to specify the generics. - */ -export interface GenericFields extends Component { - /** - * true if the current value of any of the fields is different from the initialized value, false otherwise. - */ +export interface GenericFields

extends Component & P> { dirty: boolean; - - /** - * The names prop that you passed in. - */ names: string[]; - - /** - * true if the all of the current values are the same as the initialized values, false otherwise. - */ pristine: boolean; - - /** - * The current values of the fields. If they are nested, the values will duplicate the structure. - * For example, if your names are [ 'name.first', 'name.last', 'email' ], the values will be - * { name: { first: 'John', last: 'Smith' }, email: 'john@email.com' } - */ - values: { [name: string]: FieldValue }; - - getRenderedComponent(): Component; + values: { [name: string]: any }; + getRenderedComponent(): Component; } -/** - * The Fields Instance API. - */ -export class Fields extends Component implements GenericFields { - /** - * true if the current value of any of the fields is different from the initialized value, false otherwise. - */ +export class Fields

extends Component & P> implements GenericFields

{ dirty: boolean; - - /** - * The names prop that you passed in. - */ names: string[]; - - /** - * true if the all of the current values are the same as the initialized values, false otherwise. - */ pristine: boolean; - - /** - * The current values of the fields. If they are nested, the values will duplicate the structure. - * For example, if your names are [ 'name.first', 'name.last', 'email' ], the values will be - * { name: { first: 'John', last: 'Smith' }, email: 'john@email.com' } - */ - values: { [name: string]: FieldValue }; - - getRenderedComponent(): Component; + values: { [name: string]: any }; + getRenderedComponent(): Component; } -interface WrappedFieldsProps { - [name: string]: WrappedFieldsProps & WrappedFieldProps +interface WrappedFieldsProps { + [name: string]: WrappedFieldsProps & WrappedFieldProps } diff --git a/types/redux-form/lib/Form.d.ts b/types/redux-form/lib/Form.d.ts index 9339348393..fd8321836d 100644 --- a/types/redux-form/lib/Form.d.ts +++ b/types/redux-form/lib/Form.d.ts @@ -1,22 +1,11 @@ -import { Component, HTMLProps, FormEvent } from "react"; +import { Component, FormHTMLAttributes, FormEvent, FormEventHandler } from "react"; import { Dispatch } from "redux"; -import { SubmitHandler, FormProps, FormErrors } from "../index" +import { FormProps, FormErrors, FormSubmitHandler, Omit } from "redux-form"; -interface FormSubmitHandler { - (values: any, dispatch?: Dispatch, props?: FormProps & { [prop: string]: any }): void | FormErrors | Promise; - //(e: FormEvent): void; +interface FormSubmitProp { + onSubmit?: FormSubmitHandler; } -export interface FormComponentProps extends HTMLProps { - /** - * The function to call when form submission is triggered. - */ - onSubmit: FormSubmitHandler; -} +export type FormProps = Omit, "onSubmit"> & FormSubmitProp; -/** - * The Form component is a simple wrapper for the React

component that - * allows the surrounding redux-form-decorated component to trigger its - * onSubmit function. - */ -export class Form extends Component {} +declare class Form extends Component {} diff --git a/types/redux-form/lib/FormSection.d.ts b/types/redux-form/lib/FormSection.d.ts index 9be46ebf80..8be6278f9b 100644 --- a/types/redux-form/lib/FormSection.d.ts +++ b/types/redux-form/lib/FormSection.d.ts @@ -1,15 +1,10 @@ -import { Component } from "react"; +import { Component, ComponentType } from "react"; -interface FormSectionProps { - /** - * The name all child fields should be prefixed with. - */ +export type GenericFormSection

= Component

>; + +export interface FormSectionProps

{ name: string; + component?: string | ComponentType

; } -/** - * The FormSection component makes it easy to split forms into smaller components that are resuable across - * multiple forms. It does this by prefixing the name of Field, Fields and FieldArray children, at any depth, - * with the value specified in the name prop. - */ -export class FormSection extends Component {} +declare class FormSection extends Component {} diff --git a/types/redux-form/lib/SubmissionError.d.ts b/types/redux-form/lib/SubmissionError.d.ts new file mode 100644 index 0000000000..ffe7a0064a --- /dev/null +++ b/types/redux-form/lib/SubmissionError.d.ts @@ -0,0 +1,7 @@ +import { FormErrors } from "redux-form"; + +export interface SubmissionErrorConstructor { + new (errors?: FormErrors): Error; +} + +declare const SubmissionError: SubmissionErrorConstructor; diff --git a/types/redux-form/lib/actions.d.ts b/types/redux-form/lib/actions.d.ts index b126549f68..8508fb2aec 100644 --- a/types/redux-form/lib/actions.d.ts +++ b/types/redux-form/lib/actions.d.ts @@ -1,5 +1,5 @@ import { Action } from "redux"; -import { FormErrors, FormWarnings, FieldType } from "../index"; +import { FormErrors, FormWarnings, FieldType } from "redux-form"; export interface FormAction extends Action { meta: { @@ -7,154 +7,40 @@ export interface FormAction extends Action { }; } -/** - * Inserts an item into a field array at the specified index - */ -export function arrayInsert(form: string, field: string, index: number, value: any): FormAction; +declare function arrayInsert(form: string, field: string, index: number, value: any): FormAction; +declare function arrayMove(form: string, field: string, from: number, to: number): FormAction; +declare function arrayPop(form: string, field: string): FormAction; +declare function arrayPush(form: string, field: string, value: any): FormAction; +declare function arrayRemove(form: string, field: string, index: number): FormAction; +declare function arrayRemoveAll(form: string, field: string): FormAction; +declare function arrayShift(form: string, field: string): FormAction; +declare function arraySplice(form: string, field: string, index: number, removeNum: number, value: any): FormAction; +declare function arraySwap(form: string, field: string, indexA: number, indexB: number): FormAction; +declare function arrayUnshift(form: string, field: string, value: any): FormAction; +declare function autofill(form: string, field: string, value: any): FormAction; +declare function blur(form: string, field: string, value: any): FormAction; +declare function change(form: string, field: string, value: any): FormAction; +declare function destroy(...form: string[]): FormAction; +declare function focus(form: string, field: string): FormAction; -/** - * Moves an item from one index in the array to another. In effect, it performs a remove and an - * insert, so the item already at the `to` position will be bumped to a higher index, not overwritten. - */ -export function arrayMove(form: string, field: string, from: number, to: number): FormAction; - -/** - * Removes an item from the end of a field array - */ -export function arrayPop(form: string, field: string): FormAction; - -/** - * Appends an item to the end of a field array - */ -export function arrayPush(form: string, field: string, value: any): FormAction; - -/** - * Removes an item at the specified index from a field array - */ -export function arrayRemove(form: string, field: string, index: number): FormAction; - -/** - * Removes all items from a field array - */ -export function arrayRemoveAll(form: string, field: string): FormAction; - -/** - * Removes an item from the beginning of a field array - */ -export function arrayShift(form: string, field: string): FormAction; - -/** - * ADVANCED USAGE - Inserts and/or removes items from a field array. Works similarly to Array.splice. - */ -export function arraySplice(form: string, field: string, index: number, removeNum: number, value: any): FormAction; - -/** - * Swaps two items at the specified indexes in a field array - */ -export function arraySwap(form: string, field: string, indexA: number, indexB: number): FormAction; - -/** - * Inserts an item at the beginning of a field array - */ -export function arrayUnshift(form: string, field: string, value: any): FormAction; - -/** - * Saves the value to the field and sets its `autofilled` property to `true`. - */ -export function autofill(form: string, field: string, value: any): FormAction; - -/** - * Saves the value to the field - */ -export function blur(form: string, field: string, value: any): FormAction; - -/** - * Saves the value to the field - */ -export function change(form: string, field: string, value: any): FormAction; - -/** - * Destroys the form, removing all it's state - */ -export function destroy(...form: string[]): FormAction; - -/** - * Marks the given field as active and visited - */ -export function focus(form: string, field: string): FormAction; - -/** - * Sets the initial values in the form with which future data values will be compared to calculate dirty and pristine. - * The data parameter may contain deep nested array and object values that match the shape of your form fields. - * If the keepDirty parameter is true, the values of the currently dirty fields will be retained to avoid overwriting - * user edits. - */ interface InitializeOptions { keepDirty : boolean; keepSubmitSucceeded: boolean; } -export function initialize(form: string, data: any, keepDirty?: boolean | InitializeOptions, options?: InitializeOptions): FormAction; - -/** - * Registers a field with the form. - */ -export function registerField(form: string, name: string, type: FieldType): FormAction; - -/** - * Resets the values in the form back to the values past in with the most recent initialize action. - */ -export function reset(form: string): FormAction; - -/** - * Flips the asyncValidating flag true - */ -export function startAsyncValidation(form: string): FormAction; - -/** - * Flips the asyncValidating flag false and populates asyncError for each field. - */ -export function stopAsyncValidation(form: string, errors?: any): FormAction; - -export function setSubmitFailed(form: string, ...fields: string[]): FormAction; - -export function setSubmitSucceeded(form: string, ...fields: string[]): FormAction; - -/** - * Flips the submitting flag true. - */ -export function startSubmit(form: string): FormAction; - -/** - * Flips the submitting flag false and populates submitError for each field. - */ -export function stopSubmit(form: string, errors?: any): FormAction; - -/** - * Flips the asyncValidating flag false and populates asyncError for each field. - */ -export function stopAsyncValidation(form: string, errors?: any): FormAction; - -/** - * Triggers a submission of the specified form. - */ -export function submit(form: string): FormAction; - -/** - * Marks all the fields passed in as touched. - */ -export function touch(form: string, ...fields: string[]): FormAction; - -/** - * Unregisters a field with the form. - */ -export function unregisterField(form: string, name: string): FormAction; - -/** - * Resets the 'touched' flag for all the fields passed in. - */ -export function untouch(form: string, ...fields: string[]): FormAction; - -export function updateSyncErrors(from: string, syncErrors: FormErrors, error: any): FormAction; - -export function updateSyncWarnings(form: string, syncWarnings: FormWarnings, warning: any): FormAction; +declare function initialize(form: string, data: any, keepDirty?: boolean | InitializeOptions, options?: InitializeOptions): FormAction; +declare function registerField(form: string, name: string, type: FieldType): FormAction; +declare function reset(form: string): FormAction; +declare function startAsyncValidation(form: string): FormAction; +declare function stopAsyncValidation(form: string, errors?: any): FormAction; +declare function setSubmitFailed(form: string, ...fields: string[]): FormAction; +declare function setSubmitSucceeded(form: string, ...fields: string[]): FormAction; +declare function startSubmit(form: string): FormAction; +declare function stopSubmit(form: string, errors?: any): FormAction; +declare function stopAsyncValidation(form: string, errors?: any): FormAction; +declare function submit(form: string): FormAction; +declare function touch(form: string, ...fields: string[]): FormAction; +declare function unregisterField(form: string, name: string): FormAction; +declare function untouch(form: string, ...fields: string[]): FormAction; +declare function updateSyncErrors(from: string, syncErrors: FormErrors, error: any): FormAction; +declare function updateSyncWarnings(form: string, syncWarnings: FormWarnings, warning: any): FormAction; diff --git a/types/redux-form/lib/formValueSelector.d.ts b/types/redux-form/lib/formValueSelector.d.ts new file mode 100644 index 0000000000..579b62b049 --- /dev/null +++ b/types/redux-form/lib/formValueSelector.d.ts @@ -0,0 +1,6 @@ +import { FormStateMap } from "redux-form"; + +declare function formValueSelector( + form: string, + getFormState?: (state: State) => FormStateMap +): (state: State, ...field: string[]) => any; diff --git a/types/redux-form/lib/formValues.d.ts b/types/redux-form/lib/formValues.d.ts new file mode 100644 index 0000000000..fe389e1dff --- /dev/null +++ b/types/redux-form/lib/formValues.d.ts @@ -0,0 +1,13 @@ +import { ComponentClass, ComponentType } from "react"; +import { InjectedFormProps } from "redux-form"; + +declare function formValues< + Values, + P = {} +>(obj: Values): (component: ComponentType

) => ComponentClass

; + +declare function formValues< + FormData = {}, + K extends keyof FormData = keyof FormData, + P = {} +>(...names: K[]): (component: ComponentType

>) => ComponentClass

>; diff --git a/types/redux-form/lib/reducer.d.ts b/types/redux-form/lib/reducer.d.ts index f1dc6315bf..41e077ce56 100644 --- a/types/redux-form/lib/reducer.d.ts +++ b/types/redux-form/lib/reducer.d.ts @@ -2,13 +2,6 @@ import { Action, Reducer } from "redux"; import { FieldType } from "../index"; export interface FormReducer extends Reducer { - /** - * Returns a form reducer that will also pass each action through - * additional reducers specified. The parameter should be an object mapping - * from formName to a (state, action) => nextState reducer. The state - * passed to each reducer will only be the slice that pertains to that - * form. - */ plugin(reducers: FormReducerMapObject): Reducer; } @@ -18,10 +11,6 @@ export interface FormReducerMapObject { [formName: string]: Reducer; } -/** - * Store state - */ - export interface FormStateMap { [formName: string]: FormState; } diff --git a/types/redux-form/lib/reduxForm.d.ts b/types/redux-form/lib/reduxForm.d.ts index f1eac8d928..3f4a615d19 100644 --- a/types/redux-form/lib/reduxForm.d.ts +++ b/types/redux-form/lib/reduxForm.d.ts @@ -1,571 +1,140 @@ import { Component, ComponentClass, + ComponentType, ReactElement, SyntheticEvent, - ReactEventHandler, - StatelessComponent + StatelessComponent, + FormEventHandler } from "react"; import { Dispatch } from "redux"; -import { DataShape, FieldValue, FormErrors, FormWarnings, RegisteredFieldState, ComponentConstructor } from "../index"; +import { + FormErrors, + ErrorOther, + FormWarnings, + WarningOther, + RegisteredFieldState, + FormStateMap +} from "redux-form"; -export function reduxForm( - config: Config -): FormDecorator; +export type FormSubmitHandler = + (values: Partial, dispatch: Dispatch, props: P) => void | FormErrors | Promise; -export function reduxForm( - config: Config -): FormDecorator; - -export function reduxForm( - config: Config -): FormDecorator; - -/** - * This is not entirely correct but Typescript expect input and output for decorators to be the same type. - * Because of that, React HoCs can't be fully defined. https://www.typescriptlang.org/docs/handbook/decorators.html - */ -export interface FormDecorator { - >>(component: T): T; +export interface SubmitHandler { + (handler: FormSubmitHandler): FormEventHandler; + (event: SyntheticEvent): void; } -export interface Config { - /** - * the name of your form and the key to where your form's state will be - * mounted under the redux-form reducer - */ - form?: string; - - /** - * field names for which onBlur should trigger a call to the asyncValidate - * function. Defaults to []. - * - * See Asynchronous Blur Validation Example for more details. - */ - asyncBlurFields?: string[]; - - /** - * a function that takes all the form values, the dispatch function, and - * the props given to your component, and returns a Promise that will - * resolve if the validation is passed, or will reject with an object of - * validation errors in the form { field1: , field2: }. - * - * See Asynchronous Blur Validation Example for more details. - */ - asyncValidate?(values: FormData, dispatch: Dispatch, props: P, blurredField: string): Promise; - - /** - * Whether or not to automatically destroy your form's state in the Redux - * store when your component is unmounted. Defaults to true. - */ - destroyOnUnmount?: boolean; - - /** - * Reinitialize the form every time the initialValues prop changes. - * Defaults to false. - */ - enableReinitialize?: boolean; - - /** - * Whether or not to force unregistration of fields -- use in conjunction - * with destroyOnUnmount. Useful for wizard-type forms where you want to destroy - * fields as they unmount, but not the form's state. Defaults to false, as forms - * are normally unregistered on unmount. - */ - forceUnregisterOnUnmount?: boolean; - - /** - * A function that takes the entire Redux state and returns the state slice - * which corresponds to where the redux-form reducer was mounted. This - * functionality is rarely needed, and defaults to assuming that the reducer - * is mounted under the "form" key. - */ - getFormState?(state: S): any; - - /** - * When set to true and enableReinitialize is also set, the form will retain the value of dirty fields when - * reinitializing. When this option is not set (the default), reinitializing the form replaces all field values. - * This option is useful in situations where the form has live updates or continues to be editable after - * form submission; it prevents reinitialization from overwriting user changes. Defaults to false. - */ - keepDirtyOnReinitialize?: boolean; - - /** - * The values with which to initialize your form in componentWillMount(). - * Particularly useful when Editing Multiple Records, but can also be used - * with single-record forms. The values should be in the form - * { field1: 'value1', field2: 'value2' }. - */ - initialValues?: Partial; - - /** - * A callback function that will be called with all the form values any time - * any of the form values change. - */ - onChange?: (values: any) => void; - - /** - * The function to call with the form data when the handleSubmit() is fired - * from within the form component. If you do not specify it as a prop here, - * you must pass it as a parameter to handleSubmit() inside your form - * component. - */ - onSubmit?: SubmitHandler; - - /** - * A callback function that will be called when a submission fails for whatever reason. - * - * @param errors The errors that caused the submission to fail. - * @param dispatch The Redux `dispatch` function. - * @param submitError The error object that caused the submission to fail. If `errors` is set this will be most - * likely a `SubmissionError`, otherwise it can be any error or null. - * @param props The props passed into your decorated component. - */ - onSubmitFail?(errors: FormErrors, dispatch: Dispatch, submitError: any, props: P): void; - - /** - * A callback function that will be called when a submission succeeds. - * - * @param result Any result that onSubmit has returned - * @param dispatch The Redux dispatch function - * @param props The props passed into your decorated component - */ - onSubmitSuccess?(result: any, dispatch: Dispatch, props: P): void; - - /** - * If specified, all the props normally passed into your decorated - * component directly will be passed under the key specified. Useful if - * using other decorator libraries on the same component to avoid prop - * namespace collisions. - */ - propNamespace?: string; - - /** - * If true, implements `shouldComponentUpdate` and shallowly compares _only_ - * the Redux-connected props that are needed to manage the form state. This - * prevents unnecessary updates, but assumes the component is a "pure" - * component and does not rely on any input or state other than its props and - * the selected Redux store's state. Defaults to true. - */ - pure?: boolean; - - /** - * An optional function you may provide to have full control over when sync validation happens. - */ - shouldValidate?(params: ValidateCallback): boolean; - - /** - * An optional function you may provide to have full control over when async - * validation happens. - */ - shouldAsyncValidate?(params: AsyncValidateCallback): boolean; - - /** - * marks fields as touched when the blur action is fired. Defaults to true. - */ - touchOnBlur?: boolean; - - /** - * marks fields as touched when the change action is fired. Defaults to - * false. - */ - touchOnChange?: boolean; - - /** - * Do not remove submit errors when the change action is fired. Defaults to false. - */ - persistentSubmitErrors?: boolean; - - /** - * a synchronous validation function that takes the form values and props - * passed into your component. If validation passes, it should return {}. - * If validation fails, it should return the validation errors in the form - * { field1: , field2: }. - * Defaults to (values, props) => ({}). - */ - validate?(values: FormData, props: FormProps & P): FormErrors; - - /** - * A synchronous warning function that takes the form values and props passed into your component. - * Warnings work the same as validations, but do not mark a form as invalid. If the warning check passes, - * it should return {}. If the check fails, it should return the warnings in the form - * { field1: , field2: }. Defaults to (values, props) => ({}). - */ - warn?(values: FormData, props: FormProps & P): FormWarnings; -} - -/** - * If your onSubmit function returns a promise, the submitting property will be set to true - * until the promise has been resolved or rejected. If it is rejected with a redux-form - * SubmissionError containing errors in the form { field1: 'error', field2: 'error' } then - * the submission errors will be added to each field (to the error prop) just like async - * validation errors are. If there is an error that is not specific to any field, but applicable - * to the entire form, you may pass that as if it were the error for a field called _error, - * and it will be given as the error prop. - */ -export interface SubmitHandler { - (values: FormData, dispatch: Dispatch, props: FormProps & P): void | FormErrors | Promise; -} - -interface ValidateCallback { - /** - * The values. - */ +export interface ValidateCallback { values: FormData; - - /** - * The next props. - */ - nextProps: any; - - /** - * The current props. - */ - props: any; - - /** - * true if the form is being initially rendered. - */ + nextProps: P & InjectedFormProps; + props: P & InjectedFormProps; initialRender: boolean; - - /** - * The structure object being used internally for values. You may wish to use 'deepEqual' from the structure. - */ structure: any; } -interface AsyncValidateCallback { - /** - * Any existing asynchronous validation errors - */ +export interface AsyncValidateCallback { asyncErrors?: FormErrors; - - /** - * true if the form has ever been initialized with initial values - */ initialized: boolean; - - /** - * The reason to possibly run async validation. It will either be: 'blur' or - * 'submit', depending on whether an async blur field had triggered the async - * validation or if submitting the form has triggered it, respectively. - */ trigger: "blur" | "submit"; - - /** - * The name of the field that has triggered the async validation. May be undefined. - */ blurredField?: string; - - /** - * true if the form is pristine, false if it is dirty - */ pristine: boolean; - - /** - * true if synchronous validation is passing, false if it is failing. - */ syncValidationPasses: boolean; } -/** - * A throwable error that is used to return submit validation errors from onSubmit. - * The purpose being to distinguish promise rejection because of validation errors - * from promise rejection because of AJAX I/O problems or other server errors. - */ -export class SubmissionError extends Error { - errors: FormErrors; - - constructor(errors?: FormErrors); +export interface InjectedArrayProps { + insert(field: string, index: number, value: any): void; + move(field: string, from: number, to: number): void; + pop(field: string): void; + push(field: string, value: any): void; + remove(field: string, index: number): void; + removeAll(field: string): void; + shift(field: string): void; + splice(field: string, index: number, removeNum: number, value: any): void; + swap(field: string, indexA: number, indexB: number): void; + unshift(field: string, value: any): void; } -/** - * The following are methods or properties that you can access on an instance - * of your decorated form component (outermost component named "ReduxForm"). - */ -export interface FormComponent extends ComponentClass

{ - /** - * true if the form data has changed from its initialized values. Opposite - * of pristine. - */ - dirty: boolean; - - /** - * true if the form has validation errors. Opposite of valid. - */ - invalid: boolean; - - /** - * true if the form data is the same as its initialized values. Opposite - * of dirty. - */ - pristine: boolean; - - /** - * An array of objects with fields `name` and `type` for each field - * representing all the fields in the form. Mainly useful for testing. - */ - registeredFields: RegisteredFieldState[]; - - /** - * Resets all the values in the form to the initialized state, making it - * pristine again. - */ - reset(): void; - - /** - * Submits the form. Returns a promise that will be resolved when the form - * is submitted successfully, or rejected if the submission fails. - */ - submit(): Promise; - - /** - * true if the form passes validation (has no validation errors). Opposite - * of invalid. - */ - valid: boolean; - - /** - * The current values of all the fields in the form. - */ - values: FormData; - - /** - * A reference to the instance of the component you decorated with reduxForm(). - * Mainly useful for testing. - */ - wrappedInstance: ReactElement

> -} - -/** - * These are the props that will be passed to your form component. - * Your form component's props can extend this interface if you want - * to use strict checks. - */ -export interface StrictFormProps { - /** - * true if any of the fields have been marked as touched, false otherwise. - */ +export interface InjectedFormProps { anyTouched: boolean; - - /** - * A set of pre-bound action creators for you to operate on array fields in your form. - */ - array: { - /** - * Inserts a value into the given array field in your form. - */ - insert(field: string, index: number, value: FieldValue): void; - - /** - * Moves a value at the given from index to the given to index in - * the given array field in your form. - */ - move(field: string, from: number, to: number): void; - - /** - * Pops a value off of the end of a given array field in your form. - */ - pop(field: string): void; - - /** - * Pushes the given value onto the end of the given array field in your form. - */ - push(field: string, value: FieldValue): void; - - /** - * Removes a value at the given index from the given array field in your form. - */ - remove(field: string, index: number): void; - - /** - * Removes all the values from the given array field in your form. - */ - removeAll(field: string): void; - - /** - * Shifts a value out of the beginning of the given array in your form. - */ - shift(field: string): void; - - /** - * Performs an Array.splice operation on the given array in your form. - */ - splice(field: string, index: number, removeNum: number, value: FieldValue): void; - - /** - * Swaps two values at the given indexes of the given array field in your form. - */ - swap(field: string, indexA: number, indexB: number): void; - - /** - * Unshifts the given value into the beginning of the given array field in your form. - */ - unshift(field: string, value: FieldValue): void; - } - - /** - * A function that may be called to initiate asynchronous validation if - * asynchronous validation is enabled. - */ + array: InjectedArrayProps; asyncValidate: () => void; - - /** - * This value will be either: - * - false - No asynchronous validation is currently happening - * - true - Asynchronous validation is currently running in preparation to submit a form - * - a string - The name of the field that just blurred to trigger asynchronous validation - */ asyncValidating: string | boolean; - - /** - * Sets the value and marks the field as autofilled in the Redux Store. This is useful when a field - * needs to be set programmatically, but in a way that lets the user know (via a styling change using - * the autofilled prop in Field) that it has been autofilled for them programmatically. - */ - autofill(field: string, value: FieldValue): void; - - /** - * Marks a field as blurred in the Redux store. - */ - blur(field: string, value: FieldValue): void; - - /** - * Changes the value of a field in the Redux store. - */ - change(field: string, value: FieldValue): void; - - /** - * Clear async error of a field in the Redux store. - */ + autofill(field: string, value: any): void; + blur(field: string, value: any): void; + change(field: string, value: any): void; clearAsyncError(field: string): void; - - /** - * Destroys the form state in the Redux store. By default, this will be - * called for you in componentWillUnmount(). - */ destroy(): void; - - /** - * true if the form data has changed from its initialized values. Opposite - * of pristine. - */ dirty: boolean; - - /** - * A generic error for the entire form given by the _error key in the - * result from the synchronous validation function, the asynchronous - * validation, or the rejected promise from onSubmit. - */ error: string; - - /** - * The form name that you gave to the reduxForm() decorator or the prop you - * passed in to your decorated form component. - */ form: string; - - /** - * A function meant to be passed to or to - * - - - - ); + ) } -// Decorate with reduxForm(). It will read the initialValues prop provided by connect() -const DecoratedInitializeFromStateFormFunction = reduxForm({ - form: 'initializeFromState' // a unique identifier for this form -})(InitializeFromStateFormFunction) +type TestProps = {} & InjectedFormProps; +const Test = reduxForm({ + form : "test" +})( + class Test extends Component { -// You have to connect() to any reducers that you wish to connect to yourself -const ConnectedDecoratedInitializeFromStateFormFunction = connect( - state => ({ - initialValues: state.account.data // pull initial values from account reducer - }), -)(DecoratedInitializeFromStateFormFunction); + handleSubmitForm = (values: Partial, dispatch: Dispatch, props: TestProps) => {}; -// React ComponentClass instead of StatelessComponent + handleSubmitFormAny = (event: any) => {}; -class InitializeFromStateFormClass extends React.Component> { - render() { - return InitializeFromStateFormFunction(this.props); + render() { + const { handleSubmit } = this.props; + + return ( +

+
+ + + + + + + + + + + + + + + + null } + /> + + null } + foo="bar" + /> + + + + + + +
+ ) + } } -} - -// Decorate with reduxForm(). It will read the initialValues prop provided by connect() -const DecoratedInitializeFromStateFormClass = reduxForm({ - form: 'initializeFromState' // a unique identifier for this form -})(InitializeFromStateFormClass); - -// You have to connect() to any reducers that you wish to connect to yourself -const mapStateToProps = (state: any) => ({ - initialValues: { firstName: state.account.data.firstName } // pull initial values from account reducer -} as {initialValues?: Partial}); -const ConnectedDecoratedInitializeFromStateFormClass = connect(mapStateToProps)(DecoratedInitializeFromStateFormClass); - -class ImmutableCustomField extends Component { - render() { - const F = ImmutableField as new () => GenericField; - return ; - } -} - -@immutableReduxForm({ - form: 'myForm' -}) -class MyImmutableForm extends Component { - render() { - return ( -
- - -
- ); - } -} +); reducer({}, { - type: 'ACTION' + type: "ACTION" }); reducer.plugin({ - myform: (state: any, action: FormAction) => { - if (action.type === actionTypes.CHANGE && action.meta.form === 'securitySettings') { + myForm: (state: any, action: FormAction) => { + if (action.type === actionTypes.CHANGE && action.meta.form === "securitySettings") { return { ...state, values: { diff --git a/types/redux-form/tsconfig.json b/types/redux-form/tsconfig.json index 625f4b9492..eea8fb4b64 100644 --- a/types/redux-form/tsconfig.json +++ b/types/redux-form/tsconfig.json @@ -22,6 +22,19 @@ "files": [ "index.d.ts", "redux-form-tests.tsx", - "immutable/index.d.ts" + "immutable/index.d.ts", + "lib/actions.d.ts", + "lib/actionTypes.d.ts", + "lib/Field.d.ts", + "lib/Fields.d.ts", + "lib/FieldArray.d.ts", + "lib/Form.d.ts", + "lib/FormSection.d.ts", + "lib/formValues.d.ts", + "lib/formValueSelector.d.ts", + "lib/reducer.d.ts", + "lib/reduxForm.d.ts", + "lib/selectors.d.ts", + "lib/SubmissionError.d.ts" ] } diff --git a/types/redux-form/v4/redux-form-tests.tsx b/types/redux-form/v4/redux-form-tests.tsx index 2c962460fa..424c87c609 100644 --- a/types/redux-form/v4/redux-form-tests.tsx +++ b/types/redux-form/v4/redux-form-tests.tsx @@ -1,6 +1,6 @@ import * as React from 'react'; -import {Component, PropTypes} from 'react'; +import { Component, PropTypes } from 'react'; import {createStore, combineReducers} from 'redux'; import {reduxForm, reducer as reduxFormReducer, ReduxFormProps} from 'redux-form'; diff --git a/types/redux-form/v6/index.d.ts b/types/redux-form/v6/index.d.ts new file mode 100644 index 0000000000..8a51117530 --- /dev/null +++ b/types/redux-form/v6/index.d.ts @@ -0,0 +1,46 @@ +// Type definitions for redux-form 6.6 +// Project: https://github.com/erikras/redux-form +// Definitions by: Carson Full , Daniel Lytkin , Karol Janyst , Luka Zakrajsek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { + ComponentClass, + StatelessComponent, + ReactElement +} from "react"; + +export type FieldValue = any; + +export type FieldType = "Field" | "FieldArray"; + +export interface DataShape { + [fieldName: string]: FieldValue +} + +export type FormErrors = { + [P in keyof FormData]?: ReactElement | string | { _error?: string }; +}; + +export type FormWarnings = { + [P in keyof FormData]?: ReactElement | string | { _warning?: string }; +}; + +/** + * A component class or stateless function component. + * Workaround for: ComponentClass

| SFC

which does + * not resolve due to a bug in TypeScript. + * https://github.com/Microsoft/TypeScript/pull/8674 + */ +export type ComponentConstructor

= ComponentClass

| StatelessComponent

; + +export * from "./lib/reduxForm"; +export * from "./lib/Field"; +export * from "./lib/Fields"; +export * from "./lib/FieldArray"; +export * from "./lib/Form"; +export * from "./lib/FormSection"; +export * from "./lib/actions"; +export * from "./lib/actionTypes"; +export * from "./lib/reducer"; +export * from "./lib/selectors"; diff --git a/types/redux-form/v6/lib/Field.d.ts b/types/redux-form/v6/lib/Field.d.ts new file mode 100644 index 0000000000..ecef15b4c7 --- /dev/null +++ b/types/redux-form/v6/lib/Field.d.ts @@ -0,0 +1,333 @@ +import { + Component, + ReactElement, + ChangeEvent, + DragEvent, + FocusEvent +} from "react"; +import { Dispatch } from "redux"; +import { ComponentConstructor, DataShape, FieldValue } from "../index"; + +/** + * These are the props to give to `Field`. + * Any others will be passed through to your component. + */ +interface BaseFieldProps { + /** + * A string path, in dot-and-bracket notation, corresponding to a value + * in the form values. It may be as simple as 'firstName' or as complicated + * as contact.billing.address[2].phones[1].areaCode. + * + * Required but made optional so interface can be used on decorated components. + */ + name?: string; + + /** + * A Component, stateless function, or string corresponding to a default + * JSX element. + * + * Required but made optional so interface can be used on decorated components. + */ + component?: ComponentConstructor | "input" | "select" | "textarea", + + /** + * Formats the value from the Redux store to be displayed in the field input. + * Common use cases are to format Numbers into currencies or Dates into a + * localized date format. + */ + format?: Formatter | null; + + /** + * A function to convert whatever value the user has entered into the value that you + * want stored in the Redux store for the field. + * + * For instance, if you want the value to be in all uppercase, you would pass + * value => value.toUpperCase() + */ + normalize?: Normalizer; + + /** + * Don't use. + */ + props?: any; + + /** + * Parses the value given from the field input component to the type that you want + * stored in the Redux store. Common use cases are to parse currencies into Numbers into + * currencies or localized date formats into Dates. + */ + parse?: Parser; + + /** + * Allows you to to provide a field-level validation rule. The function will be given the + * current value of the field and all the other form values. If the field is valid, it + * should return `undefined`, if the field is invalid, it should return an error + * (usually, but not necessarily, a `String`). + */ + validate?: Validator | Validator[]; + + /** + * Allows you to to provide a field-level warning rule. The function will be given the + * current value of the field and all the other form values. If the field needs a warning, + * it should return the warning (usually, but not necessarily, a `String`). If the field + * does not need a warning, it should return `undefined`. + */ + warn?: Validator | Validator[]; + + /** + * If true, the rendered component will be available with the + * getRenderedComponent() method. Defaults to false. Cannot be used if your + * component is a stateless function component. + */ + withRef?: boolean; +} + +/** + * @param value The value entered by the user. + * @param previousValue The previous value for the field. + * @param allValues All the values in the entire form with the new value. + * This will be an Immutable Map if you are using Immutable JS. + * @param previousAllValues All the values in the entire form before the current change. + * This will be an Immutable Map if you are using Immutable JS. + */ +export type Normalizer = (value: FieldValue, previousValue?: FieldValue, allValues?: any, previousAllValues?: any) => FieldValue; + +export type Formatter = (value: FieldValue, name: string) => FieldValue; + +export type Parser = (value: FieldValue, name: string) => FieldValue; + +export type Validator = (value: FieldValue, allValues?: any, props?: any) => any; + +/** + * Declare Field as this interface to specify the generic. + */ +export interface GenericField extends Component { + /** + * true if the current value is different from the initialized value, + * false otherwise. + */ + dirty: boolean; + + /** + * The name prop that you passed in. + */ + name: string; + + /** + * true if the current value is the same as the initialized value, + * false otherwise. + */ + pristine: boolean; + + /** + * The current value of the field. + */ + value: FieldValue; + + /** + * Returns the instance of the rendered component. For this to work, you must + * provide a withRef prop, and your component must not be a stateless function + * component. + */ + getRenderedComponent(): Component & FieldCustomProps>; +} + +/** + * The Field Instance API. + */ +export class Field extends Component implements GenericField { + /** + * true if the current value is different from the initialized value, + * false otherwise. + */ + dirty: boolean; + + /** + * The name prop that you passed in. + */ + name: string; + + /** + * true if the current value is the same as the initialized value, + * false otherwise. + */ + pristine: boolean; + + /** + * The current value of the field. + */ + value: FieldValue; + + /** + * Returns the instance of the rendered component. For this to work, you must + * provide a withRef prop, and your component must not be a stateless function + * component. + */ + getRenderedComponent(): Component; +} + +/** + * These are props that `Field` will pass to your wrapped component (not including custom props). + */ +interface WrappedFieldProps { + /** + * An object containing all the props that you will normally want to pass to + * your input component. + */ + input?: WrappedFieldInputProps; + + /** + * An object containing all the metadata props. + */ + meta: WrappedFieldMetaProps; +} + +/** + * These props are meant to be destructured into your component. + */ +interface EventOrValueHandler { + (event: Event): void; + (value: FieldValue, newValue: FieldValue, previousValue: FieldValue): void; +} + +interface WrappedFieldInputProps { + /** + * An alias for value only when value is a boolean. Provided for + * convenience of destructuring the whole field object into the props of a + * form element. + */ + checked?: boolean; + + /** + * The name prop passed in. + */ + name: string; + + /** + * A function to call when the form field loses focus. + */ + onBlur: EventOrValueHandler>; + + /** + * A function to call when the form field is changed. + */ + onChange: EventOrValueHandler>; + + /** + * A function to call when the form field receives a 'dragStart' event. + * Saves the field value in the event for giving the field it is dropped + * into. + */ + onDragStart: EventOrValueHandler>; + + /** + * A function to call when the form field receives a drop event. + */ + onDrop: EventOrValueHandler>; + + /** + * A function to call when the form field receives focus. + */ + onFocus: EventOrValueHandler>; + + /** + * The value of this form field. It will be a boolean for checkboxes, and + * a string for all other input types. If there is no value in the Redux + * state for this field, it will default to ''. This is to + * ensure that the input is controlled. + */ + value: FieldValue; +} + +/** + * These props are metadata about the state of this field that redux-form is tracking for you. + */ +interface WrappedFieldMetaProps { + + /** + * true if this field currently has focus. It will only work if you are + * passing onFocus to your input element. + */ + active?: boolean; + + /** + * true if this field has been set with the AUTOFILL action and has not since been changed + * with a CHANGE action. This is useful to render the field in a way that the user can tell + * that the value was autofilled for them. + */ + autofilled: boolean; + + /** + * true if the form is currently running asynchronous validation because this + * field was blurred. + */ + asyncValidating: boolean; + + /** + * true if the field value has changed from its initialized value. + * Opposite of pristine. + */ + dirty: boolean; + + /** + * The Redux dispatch function. + */ + dispatch: Dispatch; + + /** + * The error for this field if its value is not passing validation. Both + * synchronous, asynchronous, and submit validation errors will be reported here. + */ + error?: any; + + /** + * The name of the form. Could be useful if you want to manually dispatch actions. + */ + form?: string; + + /** + * true if the field value fails validation (has a validation error). + * Opposite of valid. + */ + invalid: boolean; + + /** + * true if the field value is the same as its initialized value. Opposite + * of dirty. + */ + pristine: boolean; + + /** + * true if the field is currently being submitted + */ + submitting?: boolean; + + /** + * true if the form had onSubmit called and failed to submit for any reason. + * A subsequent successful submit will set it back to false. + */ + submitFailed?: boolean; + + /** + * true if the field has been touched. By default this will be set when + * the field is blurred. + */ + touched: boolean; + + /** + * true if the field value passes validation (has no validation errors). + * Opposite of invalid. + */ + valid: boolean; + + /** + * true if this field has ever had focus. It will only work if you are + * passing onFocus to your input element. + */ + visited?: boolean; + + /** + * The warning for this field if its value is not passing warning validation. + */ + warning?: any; +} diff --git a/types/redux-form/v6/lib/FieldArray.d.ts b/types/redux-form/v6/lib/FieldArray.d.ts new file mode 100644 index 0000000000..9629eecb27 --- /dev/null +++ b/types/redux-form/v6/lib/FieldArray.d.ts @@ -0,0 +1,217 @@ +import { Component } from "react"; +import { ComponentConstructor, Validator } from "../index"; + +/** + * These are the props to give to `FieldArray`. + * Any others will be passed through to your component. + */ +interface BaseFieldArrayProps { + /** + * A string path, in dot-and-bracket notation, corresponding to a value + * in the form values. It may be as simple as 'firstName' or as complicated + * as contact.billing.address[2].phones[1].areaCode. + * + * Required but made optional so interface can be used on decorated components. + */ + name?: string; + + /** + * A Component or stateless function to render the field array. + * + * Required but made optional so interface can be used on decorated components. + */ + component?: ComponentConstructor, + + /** + * Allows you to to provide a field-level validation rule. The function will be given the + * current value of the field and all the other form values. If the field is valid, it + * should return `undefined`, if the field is invalid, it should return an error + * (usually, but not necessarily, a `String`). + */ + validate?: Validator | Validator[]; + + /** + * Allows you to to provide a field-level warning rule. The function will be given the + * current value of the field and all the other form values. If the field needs a warning, + * it should return the warning (usually, but not necessarily, a `String`). If the field + * does not need a warning, it should return `undefined`. + */ + warn?: Validator | Validator[]; + + /** + * If true, the rendered component will be available with the + * getRenderedComponent() method. Defaults to false. Cannot be used if your + * component is a stateless function component. + */ + withRef?: boolean; + + props?: any; +} + +/** + * Declare FieldArray as this interface to specify the generics. + */ +export interface GenericFieldArray extends Component { + + /** + * The name prop that you passed in. + */ + name: string; + + /** + * true if this field passes validation, false otherwise. + */ + valid: boolean; + + /** + * Returns the instance of the rendered component. For this to work, you must + * provide a withRef prop, and your component must not be a stateless function + * component. + */ + getRenderedComponent(): Component & FieldCustomProps>; +} + +/** + * The FieldArray Instance API. + */ +export class FieldArray extends Component implements GenericFieldArray { + + /** + * The name prop that you passed in. + */ + name: string; + + /** + * true if this field passes validation, false otherwise. + */ + valid: boolean; + + /** + * Returns the instance of the rendered component. For this to work, you must + * provide a withRef prop, and your component must not be a stateless function + * component. + */ + getRenderedComponent(): Component; +} + +/** + * These are props that `FieldArray` will pass to your wrapped component. + */ +interface WrappedFieldArrayProps { + fields: FieldsProps; + meta: FieldArrayMetaProps; +} + +interface FieldsProps { + /** + * A method to iterate over each value of the array. + */ + forEach(callback: (name: string, index: number, fields: FieldsProps) => void): void; + + /** + * A method to get a single value from the array value. + */ + get(index: number): T; + + /** + * A method to get all the values in the array. + */ + getAll(): T[]; + + /** + * A function to insert a new value into the array at any arbitrary index. + */ + insert(index: number, value: T): void; + + /** + * The current length of the array. + */ + length: number; + + /** + * A method to iterate over each value of the array. Returns an array of the + * results of each call to the callback. + */ + map(callback: (name: string, index: number, fields: FieldsProps) => any): any; + + /** + * Removes an item from the end of the array. Returns the item removed. + */ + pop(): T; + + /** + * Adds a value to the end of the array. + */ + push(value: T): void; + + /** + * Removes an item from the array at an arbitrary index. + */ + remove(index: number): void; + + /** + * Removes an item from beginning of the array. Returns the item removed. + */ + shift(): T; + + /** + * Swaps two items in the array at the given indexes. + */ + swap(indexA: number, indexB: number): void; + + /** + * Adds an item to the beginning of the array. + */ + unshift(value: T): void; +} + +interface FieldArrayMetaProps { + /** + * true if the any of the fields in the field array have changed from their + * initialized value. Opposite of pristine. + */ + dirty: boolean; + + /** + * The error for this field array if its value is not passing validation. Both + * synchronous, asynchronous, and submit validation errors will be reported here. + * Array-specific errors should be returned from the validation function as an + * _error key on the array. + */ + error?: string; + + /** + * Name of your form provided to `reduxForm()` as the `form` config property. + */ + form: string; + + /** + * true if the field array value fails validation (has a validation error). + * Opposite of valid. + */ + invalid: boolean; + + /** + * true if the all of the fields in the field array are the same as their + * initialized value. Opposite of dirty. + */ + pristine: boolean; + + /** + * true if any of the fields have been touched. + */ + touched: boolean; + + /** + * true if the field value passes validation (has no validation errors). + * Opposite of invalid. + */ + valid: boolean; + + /** + * The warning for this field array if its values are not passing warning validation. + * Array-specific errors should be returned from the validation function as an + * `_warning` key on the array. + */ + warning?: string; +} diff --git a/types/redux-form/v6/lib/Fields.d.ts b/types/redux-form/v6/lib/Fields.d.ts new file mode 100644 index 0000000000..b2c210ba8c --- /dev/null +++ b/types/redux-form/v6/lib/Fields.d.ts @@ -0,0 +1,116 @@ +import { Component } from "react"; +import { ComponentConstructor, Formatter, Parser, FieldValue, WrappedFieldProps } from "../index"; + +/** + * These are the props to give to `Field`. + * Any others will be passed through to your component. + */ +interface BaseFieldsProps { + /** + * An array of strings (or the pseudo-array fields provided by FieldArray), + * in dot-and-bracket notation, corresponding to form values. + * They may be as simple as 'firstName' or as complicated as + * 'contact.billing.address[2].phones[1].areaCode'. + */ + names: string[]; + + /** + * A Component or stateless function that will be given all the props necessary + * to render the field inputs. + */ + component?: ComponentConstructor; + + /** + * Formats the value from the Redux store to be displayed in the field input. + * Common use cases are to format Numbers into currencies or Dates into a localized date format. + * + * format is called with the field value and name as arguments and should return the new formatted + * value to be displayed in the field input. + * + * To respect React 15 input behavior there is defaultFormat = value => value == null ? '' : value + * internally used. To disable that you can pass null as format prop. + */ + format?: Formatter | null; + + /** + * Don't use. + */ + props?: any; + + /** + * Parses the value given from the field input component to the type that you want stored in the Redux store. + * Common use cases are to parse currencies into Numbers into currencies or localized date formats into Dates. + * + * parse is called with the field value and name as arguments and should return the new parsed value to be + * stored in the Redux store. + */ + parse?: Parser; + + /** + * If true, the rendered component will be available with the getRenderedComponent() method. + * Defaults to false. Cannot be used if your component is a stateless function component. + */ + withRef?: boolean; +} + +/** + * Declare Fields as this interface to specify the generics. + */ +export interface GenericFields extends Component { + /** + * true if the current value of any of the fields is different from the initialized value, false otherwise. + */ + dirty: boolean; + + /** + * The names prop that you passed in. + */ + names: string[]; + + /** + * true if the all of the current values are the same as the initialized values, false otherwise. + */ + pristine: boolean; + + /** + * The current values of the fields. If they are nested, the values will duplicate the structure. + * For example, if your names are [ 'name.first', 'name.last', 'email' ], the values will be + * { name: { first: 'John', last: 'Smith' }, email: 'john@email.com' } + */ + values: { [name: string]: FieldValue }; + + getRenderedComponent(): Component; +} + +/** + * The Fields Instance API. + */ +export class Fields extends Component implements GenericFields { + /** + * true if the current value of any of the fields is different from the initialized value, false otherwise. + */ + dirty: boolean; + + /** + * The names prop that you passed in. + */ + names: string[]; + + /** + * true if the all of the current values are the same as the initialized values, false otherwise. + */ + pristine: boolean; + + /** + * The current values of the fields. If they are nested, the values will duplicate the structure. + * For example, if your names are [ 'name.first', 'name.last', 'email' ], the values will be + * { name: { first: 'John', last: 'Smith' }, email: 'john@email.com' } + */ + values: { [name: string]: FieldValue }; + + getRenderedComponent(): Component; +} + +interface WrappedFieldsProps { + [name: string]: WrappedFieldsProps & WrappedFieldProps +} diff --git a/types/redux-form/v6/lib/Form.d.ts b/types/redux-form/v6/lib/Form.d.ts new file mode 100644 index 0000000000..9339348393 --- /dev/null +++ b/types/redux-form/v6/lib/Form.d.ts @@ -0,0 +1,22 @@ +import { Component, HTMLProps, FormEvent } from "react"; +import { Dispatch } from "redux"; +import { SubmitHandler, FormProps, FormErrors } from "../index" + +interface FormSubmitHandler { + (values: any, dispatch?: Dispatch, props?: FormProps & { [prop: string]: any }): void | FormErrors | Promise; + //(e: FormEvent): void; +} + +export interface FormComponentProps extends HTMLProps { + /** + * The function to call when form submission is triggered. + */ + onSubmit: FormSubmitHandler; +} + +/** + * The Form component is a simple wrapper for the React

component that + * allows the surrounding redux-form-decorated component to trigger its + * onSubmit function. + */ +export class Form extends Component {} diff --git a/types/redux-form/v6/lib/FormSection.d.ts b/types/redux-form/v6/lib/FormSection.d.ts new file mode 100644 index 0000000000..9be46ebf80 --- /dev/null +++ b/types/redux-form/v6/lib/FormSection.d.ts @@ -0,0 +1,15 @@ +import { Component } from "react"; + +interface FormSectionProps { + /** + * The name all child fields should be prefixed with. + */ + name: string; +} + +/** + * The FormSection component makes it easy to split forms into smaller components that are resuable across + * multiple forms. It does this by prefixing the name of Field, Fields and FieldArray children, at any depth, + * with the value specified in the name prop. + */ +export class FormSection extends Component {} diff --git a/types/redux-form/v6/lib/actionTypes.d.ts b/types/redux-form/v6/lib/actionTypes.d.ts new file mode 100644 index 0000000000..ce1ba5d208 --- /dev/null +++ b/types/redux-form/v6/lib/actionTypes.d.ts @@ -0,0 +1,37 @@ +export interface ActionTypes { + ARRAY_INSERT: string; + ARRAY_MOVE: string; + ARRAY_POP: string; + ARRAY_PUSH: string; + ARRAY_REMOVE: string; + ARRAY_REMOVE_ALL: string; + ARRAY_SHIFT: string; + ARRAY_SPLICE: string; + ARRAY_UNSHIFT: string; + ARRAY_SWAP: string; + AUTOFILL: string; + BLUR: string; + CHANGE: string; + CLEAR_SUBMIT: string; + CLEAR_SUBMIT_ERRORS: string; + CLEAR_ASYNC_ERROR: string; + DESTROY: string; + FOCUS: string; + INITIALIZE: string; + REGISTER_FIELD: string; + RESET: string; + SET_SUBMIT_FAILED: string; + SET_SUBMIT_SUCCEEDED: string; + START_ASYNC_VALIDATION: string; + START_SUBMIT: string; + STOP_ASYNC_VALIDATION: string; + STOP_SUBMIT: string; + SUBMIT: string; + TOUCH: string; + UNREGISTER_FIELD: string; + UNTOUCH: string; + UPDATE_SYNC_ERRORS: string; + UPDATE_SYNC_WARNINGS: string; +} + +export const actionTypes: ActionTypes; diff --git a/types/redux-form/v6/lib/actions.d.ts b/types/redux-form/v6/lib/actions.d.ts new file mode 100644 index 0000000000..b126549f68 --- /dev/null +++ b/types/redux-form/v6/lib/actions.d.ts @@ -0,0 +1,160 @@ +import { Action } from "redux"; +import { FormErrors, FormWarnings, FieldType } from "../index"; + +export interface FormAction extends Action { + meta: { + form: string; + }; +} + +/** + * Inserts an item into a field array at the specified index + */ +export function arrayInsert(form: string, field: string, index: number, value: any): FormAction; + +/** + * Moves an item from one index in the array to another. In effect, it performs a remove and an + * insert, so the item already at the `to` position will be bumped to a higher index, not overwritten. + */ +export function arrayMove(form: string, field: string, from: number, to: number): FormAction; + +/** + * Removes an item from the end of a field array + */ +export function arrayPop(form: string, field: string): FormAction; + +/** + * Appends an item to the end of a field array + */ +export function arrayPush(form: string, field: string, value: any): FormAction; + +/** + * Removes an item at the specified index from a field array + */ +export function arrayRemove(form: string, field: string, index: number): FormAction; + +/** + * Removes all items from a field array + */ +export function arrayRemoveAll(form: string, field: string): FormAction; + +/** + * Removes an item from the beginning of a field array + */ +export function arrayShift(form: string, field: string): FormAction; + +/** + * ADVANCED USAGE - Inserts and/or removes items from a field array. Works similarly to Array.splice. + */ +export function arraySplice(form: string, field: string, index: number, removeNum: number, value: any): FormAction; + +/** + * Swaps two items at the specified indexes in a field array + */ +export function arraySwap(form: string, field: string, indexA: number, indexB: number): FormAction; + +/** + * Inserts an item at the beginning of a field array + */ +export function arrayUnshift(form: string, field: string, value: any): FormAction; + +/** + * Saves the value to the field and sets its `autofilled` property to `true`. + */ +export function autofill(form: string, field: string, value: any): FormAction; + +/** + * Saves the value to the field + */ +export function blur(form: string, field: string, value: any): FormAction; + +/** + * Saves the value to the field + */ +export function change(form: string, field: string, value: any): FormAction; + +/** + * Destroys the form, removing all it's state + */ +export function destroy(...form: string[]): FormAction; + +/** + * Marks the given field as active and visited + */ +export function focus(form: string, field: string): FormAction; + +/** + * Sets the initial values in the form with which future data values will be compared to calculate dirty and pristine. + * The data parameter may contain deep nested array and object values that match the shape of your form fields. + * If the keepDirty parameter is true, the values of the currently dirty fields will be retained to avoid overwriting + * user edits. + */ +interface InitializeOptions { + keepDirty : boolean; + keepSubmitSucceeded: boolean; +} + +export function initialize(form: string, data: any, keepDirty?: boolean | InitializeOptions, options?: InitializeOptions): FormAction; + +/** + * Registers a field with the form. + */ +export function registerField(form: string, name: string, type: FieldType): FormAction; + +/** + * Resets the values in the form back to the values past in with the most recent initialize action. + */ +export function reset(form: string): FormAction; + +/** + * Flips the asyncValidating flag true + */ +export function startAsyncValidation(form: string): FormAction; + +/** + * Flips the asyncValidating flag false and populates asyncError for each field. + */ +export function stopAsyncValidation(form: string, errors?: any): FormAction; + +export function setSubmitFailed(form: string, ...fields: string[]): FormAction; + +export function setSubmitSucceeded(form: string, ...fields: string[]): FormAction; + +/** + * Flips the submitting flag true. + */ +export function startSubmit(form: string): FormAction; + +/** + * Flips the submitting flag false and populates submitError for each field. + */ +export function stopSubmit(form: string, errors?: any): FormAction; + +/** + * Flips the asyncValidating flag false and populates asyncError for each field. + */ +export function stopAsyncValidation(form: string, errors?: any): FormAction; + +/** + * Triggers a submission of the specified form. + */ +export function submit(form: string): FormAction; + +/** + * Marks all the fields passed in as touched. + */ +export function touch(form: string, ...fields: string[]): FormAction; + +/** + * Unregisters a field with the form. + */ +export function unregisterField(form: string, name: string): FormAction; + +/** + * Resets the 'touched' flag for all the fields passed in. + */ +export function untouch(form: string, ...fields: string[]): FormAction; + +export function updateSyncErrors(from: string, syncErrors: FormErrors, error: any): FormAction; + +export function updateSyncWarnings(form: string, syncWarnings: FormWarnings, warning: any): FormAction; diff --git a/types/redux-form/v6/lib/reducer.d.ts b/types/redux-form/v6/lib/reducer.d.ts new file mode 100644 index 0000000000..f1dc6315bf --- /dev/null +++ b/types/redux-form/v6/lib/reducer.d.ts @@ -0,0 +1,49 @@ +import { Action, Reducer } from "redux"; +import { FieldType } from "../index"; + +export interface FormReducer extends Reducer { + /** + * Returns a form reducer that will also pass each action through + * additional reducers specified. The parameter should be an object mapping + * from formName to a (state, action) => nextState reducer. The state + * passed to each reducer will only be the slice that pertains to that + * form. + */ + plugin(reducers: FormReducerMapObject): Reducer; +} + +export const reducer: FormReducer; + +export interface FormReducerMapObject { + [formName: string]: Reducer; +} + +/** + * Store state + */ + +export interface FormStateMap { + [formName: string]: FormState; +} + +export interface FormState { + registeredFields: RegisteredFieldState[]; + fields?: {[name: string]: FieldState}; + values?: { [fieldName: string]: string }; + active?: string; + anyTouched?: boolean; + submitting?: boolean; + submitErrors?: { [fieldName: string]: string }; + submitFailed?: boolean; +} + +export interface RegisteredFieldState { + name: string; + type: FieldType; +} + +export interface FieldState { + active?: boolean; + touched?: boolean; + visited?: boolean; +} diff --git a/types/redux-form/v6/lib/reduxForm.d.ts b/types/redux-form/v6/lib/reduxForm.d.ts new file mode 100644 index 0000000000..f1eac8d928 --- /dev/null +++ b/types/redux-form/v6/lib/reduxForm.d.ts @@ -0,0 +1,571 @@ +import { + Component, + ComponentClass, + ReactElement, + SyntheticEvent, + ReactEventHandler, + StatelessComponent +} from "react"; +import { Dispatch } from "redux"; +import { DataShape, FieldValue, FormErrors, FormWarnings, RegisteredFieldState, ComponentConstructor } from "../index"; + +export function reduxForm( + config: Config +): FormDecorator; + +export function reduxForm( + config: Config +): FormDecorator; + +export function reduxForm( + config: Config +): FormDecorator; + +/** + * This is not entirely correct but Typescript expect input and output for decorators to be the same type. + * Because of that, React HoCs can't be fully defined. https://www.typescriptlang.org/docs/handbook/decorators.html + */ +export interface FormDecorator { + >>(component: T): T; +} + +export interface Config { + /** + * the name of your form and the key to where your form's state will be + * mounted under the redux-form reducer + */ + form?: string; + + /** + * field names for which onBlur should trigger a call to the asyncValidate + * function. Defaults to []. + * + * See Asynchronous Blur Validation Example for more details. + */ + asyncBlurFields?: string[]; + + /** + * a function that takes all the form values, the dispatch function, and + * the props given to your component, and returns a Promise that will + * resolve if the validation is passed, or will reject with an object of + * validation errors in the form { field1: , field2: }. + * + * See Asynchronous Blur Validation Example for more details. + */ + asyncValidate?(values: FormData, dispatch: Dispatch, props: P, blurredField: string): Promise; + + /** + * Whether or not to automatically destroy your form's state in the Redux + * store when your component is unmounted. Defaults to true. + */ + destroyOnUnmount?: boolean; + + /** + * Reinitialize the form every time the initialValues prop changes. + * Defaults to false. + */ + enableReinitialize?: boolean; + + /** + * Whether or not to force unregistration of fields -- use in conjunction + * with destroyOnUnmount. Useful for wizard-type forms where you want to destroy + * fields as they unmount, but not the form's state. Defaults to false, as forms + * are normally unregistered on unmount. + */ + forceUnregisterOnUnmount?: boolean; + + /** + * A function that takes the entire Redux state and returns the state slice + * which corresponds to where the redux-form reducer was mounted. This + * functionality is rarely needed, and defaults to assuming that the reducer + * is mounted under the "form" key. + */ + getFormState?(state: S): any; + + /** + * When set to true and enableReinitialize is also set, the form will retain the value of dirty fields when + * reinitializing. When this option is not set (the default), reinitializing the form replaces all field values. + * This option is useful in situations where the form has live updates or continues to be editable after + * form submission; it prevents reinitialization from overwriting user changes. Defaults to false. + */ + keepDirtyOnReinitialize?: boolean; + + /** + * The values with which to initialize your form in componentWillMount(). + * Particularly useful when Editing Multiple Records, but can also be used + * with single-record forms. The values should be in the form + * { field1: 'value1', field2: 'value2' }. + */ + initialValues?: Partial; + + /** + * A callback function that will be called with all the form values any time + * any of the form values change. + */ + onChange?: (values: any) => void; + + /** + * The function to call with the form data when the handleSubmit() is fired + * from within the form component. If you do not specify it as a prop here, + * you must pass it as a parameter to handleSubmit() inside your form + * component. + */ + onSubmit?: SubmitHandler; + + /** + * A callback function that will be called when a submission fails for whatever reason. + * + * @param errors The errors that caused the submission to fail. + * @param dispatch The Redux `dispatch` function. + * @param submitError The error object that caused the submission to fail. If `errors` is set this will be most + * likely a `SubmissionError`, otherwise it can be any error or null. + * @param props The props passed into your decorated component. + */ + onSubmitFail?(errors: FormErrors, dispatch: Dispatch, submitError: any, props: P): void; + + /** + * A callback function that will be called when a submission succeeds. + * + * @param result Any result that onSubmit has returned + * @param dispatch The Redux dispatch function + * @param props The props passed into your decorated component + */ + onSubmitSuccess?(result: any, dispatch: Dispatch, props: P): void; + + /** + * If specified, all the props normally passed into your decorated + * component directly will be passed under the key specified. Useful if + * using other decorator libraries on the same component to avoid prop + * namespace collisions. + */ + propNamespace?: string; + + /** + * If true, implements `shouldComponentUpdate` and shallowly compares _only_ + * the Redux-connected props that are needed to manage the form state. This + * prevents unnecessary updates, but assumes the component is a "pure" + * component and does not rely on any input or state other than its props and + * the selected Redux store's state. Defaults to true. + */ + pure?: boolean; + + /** + * An optional function you may provide to have full control over when sync validation happens. + */ + shouldValidate?(params: ValidateCallback): boolean; + + /** + * An optional function you may provide to have full control over when async + * validation happens. + */ + shouldAsyncValidate?(params: AsyncValidateCallback): boolean; + + /** + * marks fields as touched when the blur action is fired. Defaults to true. + */ + touchOnBlur?: boolean; + + /** + * marks fields as touched when the change action is fired. Defaults to + * false. + */ + touchOnChange?: boolean; + + /** + * Do not remove submit errors when the change action is fired. Defaults to false. + */ + persistentSubmitErrors?: boolean; + + /** + * a synchronous validation function that takes the form values and props + * passed into your component. If validation passes, it should return {}. + * If validation fails, it should return the validation errors in the form + * { field1: , field2: }. + * Defaults to (values, props) => ({}). + */ + validate?(values: FormData, props: FormProps & P): FormErrors; + + /** + * A synchronous warning function that takes the form values and props passed into your component. + * Warnings work the same as validations, but do not mark a form as invalid. If the warning check passes, + * it should return {}. If the check fails, it should return the warnings in the form + * { field1: , field2: }. Defaults to (values, props) => ({}). + */ + warn?(values: FormData, props: FormProps & P): FormWarnings; +} + +/** + * If your onSubmit function returns a promise, the submitting property will be set to true + * until the promise has been resolved or rejected. If it is rejected with a redux-form + * SubmissionError containing errors in the form { field1: 'error', field2: 'error' } then + * the submission errors will be added to each field (to the error prop) just like async + * validation errors are. If there is an error that is not specific to any field, but applicable + * to the entire form, you may pass that as if it were the error for a field called _error, + * and it will be given as the error prop. + */ +export interface SubmitHandler { + (values: FormData, dispatch: Dispatch, props: FormProps & P): void | FormErrors | Promise; +} + +interface ValidateCallback { + /** + * The values. + */ + values: FormData; + + /** + * The next props. + */ + nextProps: any; + + /** + * The current props. + */ + props: any; + + /** + * true if the form is being initially rendered. + */ + initialRender: boolean; + + /** + * The structure object being used internally for values. You may wish to use 'deepEqual' from the structure. + */ + structure: any; +} + +interface AsyncValidateCallback { + /** + * Any existing asynchronous validation errors + */ + asyncErrors?: FormErrors; + + /** + * true if the form has ever been initialized with initial values + */ + initialized: boolean; + + /** + * The reason to possibly run async validation. It will either be: 'blur' or + * 'submit', depending on whether an async blur field had triggered the async + * validation or if submitting the form has triggered it, respectively. + */ + trigger: "blur" | "submit"; + + /** + * The name of the field that has triggered the async validation. May be undefined. + */ + blurredField?: string; + + /** + * true if the form is pristine, false if it is dirty + */ + pristine: boolean; + + /** + * true if synchronous validation is passing, false if it is failing. + */ + syncValidationPasses: boolean; +} + +/** + * A throwable error that is used to return submit validation errors from onSubmit. + * The purpose being to distinguish promise rejection because of validation errors + * from promise rejection because of AJAX I/O problems or other server errors. + */ +export class SubmissionError extends Error { + errors: FormErrors; + + constructor(errors?: FormErrors); +} + +/** + * The following are methods or properties that you can access on an instance + * of your decorated form component (outermost component named "ReduxForm"). + */ +export interface FormComponent extends ComponentClass

{ + /** + * true if the form data has changed from its initialized values. Opposite + * of pristine. + */ + dirty: boolean; + + /** + * true if the form has validation errors. Opposite of valid. + */ + invalid: boolean; + + /** + * true if the form data is the same as its initialized values. Opposite + * of dirty. + */ + pristine: boolean; + + /** + * An array of objects with fields `name` and `type` for each field + * representing all the fields in the form. Mainly useful for testing. + */ + registeredFields: RegisteredFieldState[]; + + /** + * Resets all the values in the form to the initialized state, making it + * pristine again. + */ + reset(): void; + + /** + * Submits the form. Returns a promise that will be resolved when the form + * is submitted successfully, or rejected if the submission fails. + */ + submit(): Promise; + + /** + * true if the form passes validation (has no validation errors). Opposite + * of invalid. + */ + valid: boolean; + + /** + * The current values of all the fields in the form. + */ + values: FormData; + + /** + * A reference to the instance of the component you decorated with reduxForm(). + * Mainly useful for testing. + */ + wrappedInstance: ReactElement

> +} + +/** + * These are the props that will be passed to your form component. + * Your form component's props can extend this interface if you want + * to use strict checks. + */ +export interface StrictFormProps { + /** + * true if any of the fields have been marked as touched, false otherwise. + */ + anyTouched: boolean; + + /** + * A set of pre-bound action creators for you to operate on array fields in your form. + */ + array: { + /** + * Inserts a value into the given array field in your form. + */ + insert(field: string, index: number, value: FieldValue): void; + + /** + * Moves a value at the given from index to the given to index in + * the given array field in your form. + */ + move(field: string, from: number, to: number): void; + + /** + * Pops a value off of the end of a given array field in your form. + */ + pop(field: string): void; + + /** + * Pushes the given value onto the end of the given array field in your form. + */ + push(field: string, value: FieldValue): void; + + /** + * Removes a value at the given index from the given array field in your form. + */ + remove(field: string, index: number): void; + + /** + * Removes all the values from the given array field in your form. + */ + removeAll(field: string): void; + + /** + * Shifts a value out of the beginning of the given array in your form. + */ + shift(field: string): void; + + /** + * Performs an Array.splice operation on the given array in your form. + */ + splice(field: string, index: number, removeNum: number, value: FieldValue): void; + + /** + * Swaps two values at the given indexes of the given array field in your form. + */ + swap(field: string, indexA: number, indexB: number): void; + + /** + * Unshifts the given value into the beginning of the given array field in your form. + */ + unshift(field: string, value: FieldValue): void; + } + + /** + * A function that may be called to initiate asynchronous validation if + * asynchronous validation is enabled. + */ + asyncValidate: () => void; + + /** + * This value will be either: + * - false - No asynchronous validation is currently happening + * - true - Asynchronous validation is currently running in preparation to submit a form + * - a string - The name of the field that just blurred to trigger asynchronous validation + */ + asyncValidating: string | boolean; + + /** + * Sets the value and marks the field as autofilled in the Redux Store. This is useful when a field + * needs to be set programmatically, but in a way that lets the user know (via a styling change using + * the autofilled prop in Field) that it has been autofilled for them programmatically. + */ + autofill(field: string, value: FieldValue): void; + + /** + * Marks a field as blurred in the Redux store. + */ + blur(field: string, value: FieldValue): void; + + /** + * Changes the value of a field in the Redux store. + */ + change(field: string, value: FieldValue): void; + + /** + * Clear async error of a field in the Redux store. + */ + clearAsyncError(field: string): void; + + /** + * Destroys the form state in the Redux store. By default, this will be + * called for you in componentWillUnmount(). + */ + destroy(): void; + + /** + * true if the form data has changed from its initialized values. Opposite + * of pristine. + */ + dirty: boolean; + + /** + * A generic error for the entire form given by the _error key in the + * result from the synchronous validation function, the asynchronous + * validation, or the rejected promise from onSubmit. + */ + error: string; + + /** + * The form name that you gave to the reduxForm() decorator or the prop you + * passed in to your decorated form component. + */ + form: string; + + /** + * A function meant to be passed to or to + * + + + + ); +} + +// Decorate with reduxForm(). It will read the initialValues prop provided by connect() +const DecoratedInitializeFromStateFormFunction = reduxForm({ + form: 'initializeFromState' // a unique identifier for this form +})(InitializeFromStateFormFunction) + +// You have to connect() to any reducers that you wish to connect to yourself +const ConnectedDecoratedInitializeFromStateFormFunction = connect( + state => ({ + initialValues: state.account.data // pull initial values from account reducer + }), +)(DecoratedInitializeFromStateFormFunction); + +// React ComponentClass instead of StatelessComponent + +class InitializeFromStateFormClass extends React.Component> { + render() { + return InitializeFromStateFormFunction(this.props); + } +} + +// Decorate with reduxForm(). It will read the initialValues prop provided by connect() +const DecoratedInitializeFromStateFormClass = reduxForm({ + form: 'initializeFromState' // a unique identifier for this form +})(InitializeFromStateFormClass); + +// You have to connect() to any reducers that you wish to connect to yourself +const mapStateToProps = (state: any) => ({ + initialValues: { firstName: state.account.data.firstName } // pull initial values from account reducer +} as {initialValues?: Partial}); +const ConnectedDecoratedInitializeFromStateFormClass = connect(mapStateToProps)(DecoratedInitializeFromStateFormClass); + +reducer({}, { + type: 'ACTION' +}); + +reducer.plugin({ + myform: (state: any, action: FormAction) => { + if (action.type === actionTypes.CHANGE && action.meta.form === 'securitySettings') { + return { + ...state, + values: { + ...state.values, + downloadLinkAutoPassword: true, + }, + }; + } else { + return state; + } + } +}); diff --git a/types/redux-form/v6/tsconfig.json b/types/redux-form/v6/tsconfig.json new file mode 100644 index 0000000000..1903e7055b --- /dev/null +++ b/types/redux-form/v6/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "experimentalDecorators": true, + "noImplicitAny": true, + "noImplicitReturns": true, + "noImplicitThis": true, + "strictNullChecks": true, + "jsx": "react", + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "redux-form": ["redux-form/v6"], + "redux-form/*": ["redux-form/v6/*"] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "redux-form-tests.tsx" + ] +} diff --git a/types/redux-logger/redux-logger-tests.ts b/types/redux-logger/redux-logger-tests.ts index db0131b95e..3ede2b8806 100644 --- a/types/redux-logger/redux-logger-tests.ts +++ b/types/redux-logger/redux-logger-tests.ts @@ -1,5 +1,5 @@ -import {createLogger} from 'redux-logger'; +import { createLogger } from 'redux-logger'; import logger from 'redux-logger'; import { applyMiddleware, createStore } from 'redux'; diff --git a/types/redux-promise/redux-promise-tests.ts b/types/redux-promise/redux-promise-tests.ts index 39f3c9fe84..1305cd6833 100644 --- a/types/redux-promise/redux-promise-tests.ts +++ b/types/redux-promise/redux-promise-tests.ts @@ -1,4 +1,4 @@ -import {createAction} from 'redux-actions'; +import { createAction } from 'redux-actions'; import { createStore, applyMiddleware, PromiseAction } from 'redux'; import promise = require('redux-promise'); diff --git a/types/restangular/index.d.ts b/types/restangular/index.d.ts index 5d871cdd67..c32f913549 100644 --- a/types/restangular/index.d.ts +++ b/types/restangular/index.d.ts @@ -7,7 +7,7 @@ /// // Support AMD require (copying angular.d.ts approach) -// allows for import {IRequestConfig} from 'restangular' ES6 approach +// allows for import { IRequestConfig } from 'restangular' ES6 approach import * as angular from 'angular'; export = restangular; export as namespace Restangular; diff --git a/types/restify-plugins/index.d.ts b/types/restify-plugins/index.d.ts index d461358bdc..c0d8114d92 100644 --- a/types/restify-plugins/index.d.ts +++ b/types/restify-plugins/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Костя Третяк // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {RequestHandler, Server, Request, Response, Route} from 'restify'; +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: diff --git a/types/rheostat/rheostat-tests.tsx b/types/rheostat/rheostat-tests.tsx index 1116861943..263e287f6f 100644 --- a/types/rheostat/rheostat-tests.tsx +++ b/types/rheostat/rheostat-tests.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import Rheostat, {Orientation, Algorithm, PublicState} from 'rheostat'; +import Rheostat, { Orientation, Algorithm, PublicState } from 'rheostat'; type Element = React.ReactElement; diff --git a/types/riot/index.d.ts b/types/riot/index.d.ts index 3c76a0b1d0..079132db72 100644 --- a/types/riot/index.d.ts +++ b/types/riot/index.d.ts @@ -1,426 +1,727 @@ -// Type definitions for riot v2.6.0 +// Type definitions for riot 3.6 // Project: https://github.com/riot/riot // Definitions by: Boriss Nazarovs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -declare namespace riot { +/** + * Current version number as a string + */ +export const version: string; + +/** + * Riot settings + */ +export interface Settings { /** - * Current version number as string + * Setting used to customize the start and end tokens of the expression + * @default { } */ - const version: string; + brackets: string; + /** + * If set to false, riot will not create lighter tag instances for anonymous tags + * @default true + */ + skipAnonymousTags: boolean; + /** + * If set to false, DOM event handlers will not trigger update events + * @default true + */ + autoUpdate: boolean; + /** + * `riot.renderAsync` timeout in ms + * @default 1000 + */ + asyncRenderTimeout: number; +} + +export const settings: Settings; + +export interface TemplateError extends Error { + riotData: { + _riot_id: number; + tagName: string; + }; +} + +/** + * Riot template engine + */ +export interface Tmpl { + (expression: string, data?: any): any; + + version: string; /** - * Riot settings + * Utility hook function to catch all the errors swallowed by the riot template engine */ - interface Settings { - /** - * Setting used to customize the start and end tokens of the expression - */ - brackets: string; - } + errorHandler(error: TemplateError): void; +} - const settings: Settings; +/** + * Object that is used to inject and manage the css of every tag instance + */ +export interface StyleManager { + styleNode: HTMLStyleElement; - interface TemplateError extends Error { - riotData: { - tagName: string; - } - } + /** + * Save a tag style to be later injected into DOM + * @param {string} css - css string + * @param {string} name - if it's passed the css will be mapped to a tagname + */ + add(css: string, name?: string): void; - interface Util { - tmpl: { - errorHandler(error: TemplateError): void; - } - } + /** + * Inject all previously saved tag styles into DOM + */ + inject(): void; +} - const util: Util; +export interface DOMUtil { + /** + * Select multiple nodes in the DOM + * @param selector - DOM selector + * @param ctx - DOM node where the targets of our search will is located + * @returns DOM nodes found + */ + $$(selector: string, ctx?: Element): Element[]; + + /** + * Select a single node in the DOM + * @param selector - unique dom selector + * @param ctx - DOM node where the target of search will is located + * @returns DOM node found + */ + $(selector: string, ctx?: Element): Element | null; + + /** + * Create a document fragment + * @returns Document fragment + */ + createFrag(): DocumentFragment; + + /** + * Create a document text node + * @returns Text node + */ + createDOMPlaceholder(): Text; + + /** + * Check if a DOM node is an svg element + * @param element - node to check + * @returns { boolean } True if element is an svg element + */ + isSvg(element: Element): element is SVGElement; + + /** + * Create a generic DOM node + * @param name - name of the DOM node + * @returns Created element + */ + mkEl(name: string): Element; + + /** + * Set the inner html of any DOM node SVGs included + * @param container - DOM node where html should be injected + * @param html - html to inject + */ + setInnerHTML(container: Element, html: string): void; + + /** + * Toggle the visibility of a DOM node + * @param element - DOM node to update visibility for + * @param show - If true element is shown + */ + toggleVisibility(element: Element, show?: boolean): void; + + /** + * Remove any DOM attribute from a node + * @param element - DOM node to update + * @param name - name of the attribute + */ + remAttr(element: Element, name: string): void; + + /** + * Get the value of any DOM attribute on a node + * @param element - DOM node + * @param name - name of the attribute + * @returns Attribute value + */ + getAttr(element: Element, name: string): string | null; + + /** + * Set any DOM attribute + * @param element - DOM node we want to update + * @param name - name of the property we want to set + * @param value - value of the property we want to set + */ + setAttr(element: Element, name: string, value: string): void; + + /** + * Convert a style object to a string + * @param style - style object to parse + * @returns Resulting css string + */ + styleObjectToString(style: any): string; + + /** + * Insert tag safely + * @param root - children container + * @param curr - node to insert + * @param next - node that should precede inserted node + */ + safeInsert(root: Node, curr: Node, next: Node): void; + + /** + * Run callback function for each attribute in html string + * @param html - html string we want to parse + * @param fn - callback function to apply on found attributes + */ + walkAttrs(html: string, fn: (attrName: string, attrValue: string) => void): void; + + /** + * Walk down recursively through all child nodes starting with provided dom node + * @param node - starting node where we will start the recursion + * @param fn - callback to transform the child node just found + * @param context - fn can optionally return an object, which is passed to children + */ + walkNodes(node: Node, fn: (node: Node, context: any) => any, context: any): void; +} + +export interface CheckUtil { + /** + * Check if provided value is name of boolean attribute + * @param value - name to check + * @returns True if value is name of boolean attribute + */ + isBoolAttr(value: string): boolean; + + /** + * Check if provided value is a function + * @param value - reference to check + * @returns True if provided value is a function + */ + isFunction(value: any): boolean; + + /** + * Check if provided value is an object (null excluded) + * @param value - reference to check + * @returns True if provided value is an object + */ + isObject(value: any): boolean; + + /** + * Check if provided value is undefined + * @param value - reference to check + * @returns True if provided value is undefined + */ + isUndefined(value: any): boolean; + + /** + * Check if provided value is a string + * @param value - reference to check + * @returns True if provided value is a string + */ + isString(value: any): value is string; + + /** + * Check if provided value is empty. Different from falsy, because 0 or false are not considered to be blank + * @param value - value to check + * @returns True if provided value is undefined, null or empty string + */ + isBlank(value: any): boolean; + + /** + * Check if provided value is an array + * @param value - reference to check + * @returns True if provided value is an array + */ + isArray(value: any): boolean; + + /** + * Check whether object's property could be overridden + * @param obj - source object + * @param key - object property + * @returns True if value for specified key can be overridden + */ + isWritable(obj: any, key: string): boolean; + + /** + * Check if provided string is a reserved name for Riot tag instances + * @param value - name to check + * @returns True if provided string is a reserved name + */ + isReservedName(value: string): boolean; +} + +export interface MiscUtil { + /** + * Specialized function for looping over array-like collections + * @param list - collection of items + * @param fn - callback applied to each item + */ + each(list: any, fn: (item: any, index: number) => void): void; + + /** + * Check whether an array contains an item + * @param arr - target array + * @param item - item to test + * @returns True if array contains item + */ + contains(arr: any[], item: any): boolean; + + /** + * Convert a string containing dashes to camel case + * @param str - input string + * @returns my-string -> myString + */ + toCamel(str: string): string; + + /** + * Check if string starts with specified value + * @param str - source string + * @param value - test string + * @returns True if string starts with provided value + */ + startsWith(str: string, value: string): boolean; + + /** + * Helper function to set an immutable property + * @param el - object where the new property will be set + * @param key - object key where the new property will be stored + * @param value - value of the new property + * @param options - set the property overriding the default options + * @returns The initial object + */ + defineProperty(el: any, key: string, value: any, options: any): any; + + /** + * Extend any object with other properties + * @param args - objects to merge + * @returns The resulting extended object + */ + extend(...args: any[]): any; +} + +export interface TagsUtil { + /** + * Detect the tag implementation by a DOM node + * @param element - DOM node we need to parse to get its tag implementation + * @returns Object containing the implementation of a custom tag (template and boot function) + */ + getTag(element: Element): any; + + /** + * Inherit properties from a target tag instance + * @param target - tag where we will inherit properties + * @param propsInSyncWithParent - array of properties to sync with the target + */ + inheritFrom(this: TagInstance, target: TagInstance, propsInSyncWithParent: string[]): void; + + /** + * Move the position of a custom tag in its parent tag + * @param tagName - key where the tag was stored + * @param newPos - index where the new tag will be stored + */ + moveChildTag(this: TagInstance, tagName: string, newPos: number): void; + + /** + * Create a new child tag including it correctly into its parent + * @param child - child tag implementation + * @param opts - tag options containing the DOM node where the tag will be mounted + * @param innerHTML - inner html of the child node + * @param parent - instance of the parent tag including the child custom tag + * @returns Instance of the new child tag just created + */ + initChildTag(child: any, opts: any, innerHTML: string, parent: TagInstance): TagInstance; + + /** + * Loop backward all the parents tree to detect the first custom parent tag + * @param tag - a tag instance + * @returns Instance of the first custom parent tag found + */ + getImmediateCustomParentTag(tag: TagInstance): TagInstance; + + /** + * Trigger the unmount method on all the expressions + * @param expressions - DOM expressions + */ + unmountAll(expressions: any[]): void; + + /** + * Get the tag name of any DOM node + * @param dom - DOM node we want to parse + * @param skipDataIs - hack to ignore the data-is attribute when attaching to parent + * @returns Name to identify this dom node in riot + */ + getTagName(dom: Element, skipDataIs: boolean): string; + + /** + * With this function we avoid that the internal Tag methods get overridden + * @param data - options we want to use to extend the tag instance + * @returns Clean object without containing the riot internal reserved words + */ + cleanUpData(data: any): any; + + /** + * Set the property of an object for a given key. If something already + * exists there, then it becomes an array containing both the old and new value. + * @param obj - object on which to set the property + * @param key - property name + * @param value - the value of the property to be set + * @param ensureArray - ensure that the property remains an array + * @param index - add the new item in a certain array position + */ + arrayishAdd(obj: any, key: string, value: any, ensureArray?: boolean, index?: number): void; + + /** + * Removes an item from an object at a given key. If the key points to an array, + * then the item is just removed from the array. + * @param obj - object on which to remove the property + * @param key - property name + * @param value - the value of the property to be removed + * @param ensureArray - ensure that the property remains an array + */ + arrayishRemove(obj: any, key: string, value: any, ensureArray?: boolean): void; + + /** + * Mount a tag creating new Tag instance + * @param root - dom node where the tag will be mounted + * @param tagName - name of the riot tag we want to mount + * @param opts - options to pass to the Tag instance + * @param ctx - optional context that will be used to extend an existing class ( used in riot.Tag ) + * @returns Created tag instance + */ + mountTo(root: Element, tagName: string, opts?: TagOpts, ctx?: any): TagInstance; + + /** + * Makes a tag virtual and replaces a reference in the dom + * @param tag - tag to make virtual + * @param ref - dom reference location + */ + makeReplaceVirtual(tag: TagInstance, ref: Node): void; + + /** + * Adds the elements for a virtual tag + * @param src - the node that will do the inserting or appending + * @param target - only if inserting, insert before this tag's first child + */ + makeVirtual(this: TagInstance, src: Node, target?: TagInstance): void; + + /** + * Move virtual tag and all child nodes + * @param src - the node that will do the inserting + * @param target - insert before this tag's first child + */ + moveVirtual(this: TagInstance, src: Node, target: TagInstance): void; + + /** + * Get selectors for tags + * @param tags - tag names to select + * @returns Selector + */ + selectTags(tags: string[]): string; +} + +export interface Util { + /** + * Reference to the internal riot template engine + */ + tmpl: Tmpl; /** * Internal riot tags cache */ - const vdom: Tag[]; - - interface Observable { - /** - * Register callback for specified events. - * Callback is executed each time event is triggered - * @param events Space separated list of events or wildcard '*' that matches all events - * @param callback Callback function - */ - on?(events: string, callback: Function): Observable; - - /** - * Register callback for specified events. - * Callback is executed at most once. - * @param events Space separated list of events. - * @param callback Callback function - */ - one?(events: string, callback: Function): Observable; - - /** - * Remove all registered callbacks for specified events - * @param events Space separated list of events or wildcard '*' that matches all events - */ - off?(events: string): Observable; - - /** - * Remove specified callback for specified events - * @param events Space separated list of events or wildcard '*' that matches all events - * @param callback Callback function to remove - */ - off?(events: string, callback: Function): Observable; - - /** - * Execute all callback functions registered for specified list of events - * @param events Space separated list of events - * @param args Arguments provided to callbacks - */ - trigger?(events: string, ...args: any[]): Observable; - } + vdom: TagInstance[]; /** - * Riot Router + * Object used to append and create custom tags css */ - interface Route { - /** - * Register callback that is executed when the URL changes - * @param callback Callback function - */ - (callback: (...args: any[]) => void): void; - - /** - * Register callback that is executed when the URL changes and new URL matches specified filter - * @param filter URL filter - * @param callback Callback function - */ - (filter: string, callback: (...any: string[]) => void): void; - - /** - * Change the browser URL and notify all the listeners registered with `Route(callback)` - * @param to New URL - * @param title Document title for new URL - * @param shouldReplace Should new url replace the current history - */ - (to: string, title?: string, shouldReplace?: boolean): void; - - /** - * Return a new routing context - */ - create(): Route; - - /** - * Start listening for url changes - * @param autoExec Should router exec routing on the current url - */ - start(autoExec?: boolean): void; - - /** - * Stop all the routings. - * Removes the listeners and clears the callbacks. - */ - stop(): void; - - /** - * Study the current browser path “in place” and emit routing without waiting for it to change. - */ - exec(): void; - - /** - * @deprecated - */ - exec(callback: Function): void; - - /** - * Extract query from the url - */ - query(): { [key: string]: string }; - - /** - * Change the base path - * @param base Base path - */ - base(base: string): void; - - /** - * Change the default parsers to the custom ones. - * @param parser Replacement parser for default parser - * @param secondParser Replacement parser for handling url filters - */ - parser(parser: (path: string) => any[], secondParser?: (path: string, filter: string) => any[]): void; - } + styleManager: StyleManager; /** - * Adds Observer support for the given object or - * if the argument is empty a new observable instance is created and returned. - * @param el Object to become observable + * Series of utility functions to query and update DOM nodes */ - function observable(el?: any): Observable; - - const route: Route; + dom: DOMUtil; /** - * Mount custom tags with specified tag name. Returns an array of mounted tag instances. - * @param selector Tag selector. - * It can be tag name, css selector or special '*' selector that matches all tags on the page. - * @param opts Optional object passed for the tags to consume. + * Series of helper functions needed for type checking */ - function mount(selector: string, opts?: any): Tag[]; + check: CheckUtil; /** - * Mount a custom tag on DOM nodes matching provided selector. Returns an array of mounted tag instances. - * @param selector CSS selector - * @param tagName Custom tag name - * @param opts Optional object passed for the tag to consume. + * Generic helper functions */ - function mount(selector: string, tagName: string, opts?: any): Tag[]; + misc: MiscUtil; /** - * Mount a custom tag on a given DOM node. Returns an array of mounted tag instances. - * @param domNode DOM node - * @param tagName Tag name - * @param opts Optional object passed for the tag to consume. + * Methods for managing all the riot tags instances */ - function mount(domNode: Node, tagName: string, opts?: any): Tag[]; - - /** - * Render a tag to html. This method is only available on server-side. - * @param tagName Custom tag name - * @param opts Optional object passed for the tag to consume. - */ - function render(tagName: string, opts?: any): string; - - /** - * Update all the mounted tags and their expressions on the page. - * Returns an array of tag instances that are mounted on the page. - */ - function update(): Tag[]; - - /** - * Register a global mixin and automatically add it to all tag instances. - * @param mixinObject Mixin object - */ - function mixin(mixinObject: TagMixin): void; - - /** - * Register a shared mixin, globally available to be used in any tag using `TagInstance.mixin(mixinName)` - * @param mixinName Name of the mixin - * @param mixinObject Mixin object - * @param isGlobal Is global mixin? - */ - function mixin(mixinName: string, mixinObject: TagMixin, isGlobal?: boolean): void; - - /** - * Create a new custom tag “manually” without the compiler. Returns name of the tag. - * @param tagName The tag name - * @param html The layout with expressions - * @param css The style of the tag - * @param attrs String of attributes for the tag - * @param constructor The initialization function being called before - * the tag expressions are calculated and before the tag is mounted - */ - function tag(tagName: string, html: string, css?: string, attrs?: string, constructor?: (opts: any) => void): string; - - - interface TagImplementation { - /** - * Tag template - */ - tmpl: string; - /** - * The callback function called on the mount event - * @param opts Tag options object - */ - fn?(opts: any): void; - /** - * Root tag html attributes as object (key => value) - */ - attrs?: { - [key: string]: any; - } - } - - interface TagConfiguration { - /** - * DOM node where you will mount the tag template - */ - root: Node; - /** - * Tag options - */ - opts?: any; - /** - * Is it used in as loop tag - */ - isLoop?: boolean; - /** - * Is already registered using `riot.tag` - */ - hasImpl?: boolean; - /** - * Loop item in the loop assigned to this instance - */ - item?: any; - } - - interface TagInterface extends Observable { - /** - * options object - */ - opts?: any; - /** - * the parent tag if any - */ - parent?: Tag; - /** - * root DOM node - */ - root?: Node; - /** - * nested custom tags - */ - tags?: { - [key: string]: Tag | Tag[]; - }; - - /** - * Updates all the expressions on the current tag instance as well as on all the children. - * @param data Context data - */ - update?(data?: any): void; - - /** - * Extend tag with functionality available on shared mixin registered with `riot.mixin(mixinName, mixinObject)` - * @param mixinName Name of shared mixin - */ - mixin?(mixinName: string): void; - - /** - * Extend tag functionality with functionality available on provided mixin object. - * @param mixinObject Mixin object - */ - mixin?(mixinObject: TagMixin): void; - - /** - * Mount the tag - */ - mount?(): void; - - /** - * Detach the tag and its children from the page. - * @param keepTheParent If `true` unmounting tag doesn't remove the parent tag - */ - unmount?(keepTheParent?: boolean): void; - } - - - class Tag implements TagInterface { - /** - * Tag constructor - * @param impl Tag implementation - * @param conf Tag configuration - * @param innerHTML HTML that can be used replacing a nested `yield` tag in its template - */ - constructor(impl: TagImplementation, conf: TagConfiguration, innerHTML?: string); - - /** - * options object - */ - opts: any; - /** - * the parent tag if any - */ - parent: Tag; - /** - * root DOM node - */ - root: Node; - /** - * nested custom tags - */ - tags: { - [key: string]: Tag | Tag[]; - }; - - /** - * Updates all the expressions on the current tag instance as well as on all the children. - * @param data Context data - */ - update(data?: any): void; - - /** - * Extend tag with functionality available on shared mixin registered with `riot.mixin(mixinName, mixinObject)` - * @param mixinName Name of shared mixin - */ - mixin(mixinName: string): void; - - /** - * Extend tag functionality with functionality available on provided mixin object. - * @param mixinObject Mixin object - */ - mixin(mixinObject: TagMixin): void; - - /** - * Mount the tag - */ - mount(): void; - - /** - * Detach the tag and its children from the page. - * @param keepTheParent If `true` unmounting tag doesn't remove the parent tag - */ - unmount(keepTheParent?: boolean): void; - - // Observable methods - on(events: string, callback: Function): this; - one(events: string, callback: Function): this; - off(events: string): this; - off(events: string, callback: Function): this; - trigger(events: string, ...args: any[]): this; - } - - /** - * Mixin object for extending tag functionality. - * When it gets mixed in it has access to all tag properties. - * It should not override any built in tag properties - */ - interface TagMixin extends TagInterface { - /** - * Special method which can initialize - * the mixin when it's loaded to the tag and is not - * accessible from the tag its mixed in - */ - init?(): void; - } - - /** - * Compile all tags defined with