diff --git a/README.md b/README.md index b826bf5ad5..7e543c937a 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ or just look for any ".d.ts" files in the package and manually include them with These can be used by TypeScript 1.0. * [Typings](https://github.com/typings/typings) -* ~~[NuGet](http://nuget.org/Tpackages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off) +* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off) * Manually download from the `master` branch of this repository You may need to add manual [references](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html). diff --git a/notNeededPackages.json b/notNeededPackages.json index c5173ffc24..306865851b 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -186,6 +186,12 @@ "sourceRepoURL": "https://github.com/loopline-systems/electron-builder", "asOfVersion": "2.8.0" }, + { + "libraryName": "error-stack-parser", + "typingsPackageName": "error-stack-parser", + "sourceRepoURL": "https://github.com/stacktracejs/error-stack-parser", + "asOfVersion": "2.0.0" + }, { "libraryName": "eventemitter2", "typingsPackageName": "eventemitter2", diff --git a/types/ace/index.d.ts b/types/ace/index.d.ts index 456727756c..822c394a32 100644 --- a/types/ace/index.d.ts +++ b/types/ace/index.d.ts @@ -345,18 +345,47 @@ declare namespace AceAjax { insert(position: Position, text: string): any; /** - * Inserts the elements in `lines` into the document, starting at the row index given by `row`. This method also triggers the `'change'` event. - * @param row The index of the row to insert at - * @param lines An array of strings - **/ + * @deprecated Use the insertFullLines method instead. + */ insertLines(row: number, lines: string[]): any; /** - * Inserts a new line into the document at the current row's `position`. This method also triggers the `'change'` event. - * @param position The position to insert at - **/ + * Inserts the elements in `lines` into the document as full lines (does not merge with existing line), starting at the row index given by `row`. This method also triggers the `"change"` event. + * @param {Number} row The index of the row to insert at + * @param {Array} lines An array of strings + * @returns {Object} Contains the final row and column, like this: + * ``` + * {row: endRow, column: 0} + * ``` + * If `lines` is empty, this function returns an object containing the current row, and column, like this: + * ``` + * {row: row, column: 0} + * ``` + * + **/ + insertFullLines(row: number, lines: string[]): any; + + /** + * @deprecated Use insertMergedLines(position, ['', '']) instead. + */ insertNewLine(position: Position): any; + /** + * Inserts the elements in `lines` into the document, starting at the position index given by `row`. This method also triggers the `"change"` event. + * @param {Number} row The index of the row to insert at + * @param {Array} lines An array of strings + * @returns {Object} Contains the final row and column, like this: + * ``` + * {row: endRow, column: 0} + * ``` + * If `lines` is empty, this function returns an object containing the current row, and column, like this: + * ``` + * {row: row, column: 0} + * ``` + * + **/ + insertMergedLines(row: number, lines: string[]): any; + /** * Inserts `text` into the `position` at the current row. This method also triggers the `'change'` event. * @param position The position to insert at @@ -379,12 +408,19 @@ declare namespace AceAjax { removeInLine(row: number, startColumn: number, endColumn: number): any; /** - * Removes a range of full lines. This method also triggers the `'change'` event. - * @param firstRow The first row to be removed - * @param lastRow The last row to be removed - **/ + * @deprecated Use the removeFullLines method instead. + */ removeLines(firstRow: number, lastRow: number): string[]; + /** + * Removes a range of full lines. This method also triggers the `"change"` event. + * @param {Number} firstRow The first row to be removed + * @param {Number} lastRow The last row to be removed + * @returns {[String]} Returns all the removed lines. + * + **/ + removeFullLines(firstRow: number, lastRow: number): string[]; + /** * Removes the new line between `row` and the row immediately following it. This method also triggers the `'change'` event. * @param row The row to check @@ -474,9 +510,9 @@ declare namespace AceAjax { removeFold(arg: any): void; expandFold(arg: any): void; - + foldAll(startRow?: number, endRow?: number, depth?: number): void - + unfold(arg1: any, arg2: boolean): void; screenToDocumentColumn(row: number, column: number): void; @@ -2659,9 +2695,9 @@ declare namespace AceAjax { characterWidth: number; lineHeight: number; - + setScrollMargin(top:number, bottom:number, left: number, right: number): void; - + screenToTextCoordinates(left: number, top: number): void; /** diff --git a/types/actions-on-google/actions-sdk-app.d.ts b/types/actions-on-google/actions-sdk-app.d.ts index 8de0de0cfb..09a4fbe0ad 100644 --- a/types/actions-on-google/actions-sdk-app.d.ts +++ b/types/actions-on-google/actions-sdk-app.d.ts @@ -35,6 +35,7 @@ export class ActionsSdkApp extends AssistantApp { constructor(options: ActionsSdkAppOptions); /** + * @deprecated * Validates whether request is from Assistant through signature verification. * Uses Google-Auth-Library to verify authorization token against given * Google Cloud Project ID. Auth token is given in request header with key, @@ -58,6 +59,30 @@ export class ActionsSdkApp extends AssistantApp { */ isRequestFromAssistant(projectId: string): Promise; + /** + * Validates whether request is from Google through signature verification. + * Uses Google-Auth-Library to verify authorization token against given + * Google Cloud Project ID. Auth token is given in request header with key, + * "Authorization". + * + * @example + * const app = new ActionsSdkApp({request, response}); + * app.isRequestFromGoogle('nodejs-cloud-test-project-1234') + * .then(() => { + * app.ask('Hey there, thanks for stopping by!'); + * }) + * .catch(err => { + * response.status(400).send(); + * }); + * + * @param projectId Google Cloud Project ID for the Assistant app. + * @return Promise resolving with google-auth-library LoginTicket + * if request is from a valid source, otherwise rejects with the error reason + * for an invalid token. + * @actionssdk + */ + isRequestFromGoogle(projectId: string): Promise; + /** * Gets the request Conversation API version. * diff --git a/types/actions-on-google/assistant-app.d.ts b/types/actions-on-google/assistant-app.d.ts index d33f447a2e..caed5cf6cb 100644 --- a/types/actions-on-google/assistant-app.d.ts +++ b/types/actions-on-google/assistant-app.d.ts @@ -10,58 +10,36 @@ import { ActionPaymentTransactionConfig, Cart, GooglePaymentTransactionConfig, L * @dialogflow */ export enum StandardIntents { - /** - * App fires MAIN intent for queries like [talk to $app]. - */ + /** App fires MAIN intent for queries like [talk to $app]. */ MAIN, - /** - * App fires TEXT intent when action issues ask intent. - */ + /** App fires TEXT intent when action issues ask intent. */ TEXT, - /** - * App fires PERMISSION intent when action invokes askForPermission. - */ + /** App fires PERMISSION intent when action invokes askForPermission. */ PERMISSION, - /** - * App fires OPTION intent when user chooses from options provided. - */ + /** App fires OPTION intent when user chooses from options provided. */ OPTION, - /** - * App fires TRANSACTION_REQUIREMENTS_CHECK intent when action sets up transaction. - */ + /** App fires TRANSACTION_REQUIREMENTS_CHECK intent when action sets up transaction. */ TRANSACTION_REQUIREMENTS_CHECK, - /** - * App fires DELIVERY_ADDRESS intent when action asks for delivery address. - */ + /** App fires DELIVERY_ADDRESS intent when action asks for delivery address. */ DELIVERY_ADDRESS, - /** - * App fires TRANSACTION_DECISION intent when action asks for transaction decision. - */ + /** App fires TRANSACTION_DECISION intent when action asks for transaction decision. */ TRANSACTION_DECISION, - /** - * App fires CONFIRMATION intent when requesting affirmation from user. - */ + /** App fires CONFIRMATION intent when requesting affirmation from user. */ CONFIRMATION, - /** - * App fires DATETIME intent when requesting date/time from user. - */ + /** App fires DATETIME intent when requesting date/time from user. */ DATETIME, - /** - * App fires SIGN_IN intent when requesting sign-in from user. - */ + /** App fires SIGN_IN intent when requesting sign-in from user. */ SIGN_IN, - /** - * App fires NO_INPUT intent when user doesn't provide input. - */ + /** App fires NO_INPUT intent when user doesn't provide input. */ NO_INPUT, - /** - * App fires CANCEL intent when user exits app mid-dialog. - */ + /** App fires CANCEL intent when user exits app mid-dialog. */ CANCEL, - /** - * App fires NEW_SURFACE intent when requesting handoff to a new surface from user. - */ + /** App fires NEW_SURFACE intent when requesting handoff to a new surface from user. */ NEW_SURFACE, + /** App fires REGISTER_UPDATE intent when requesting the user to register for proactive updates. */ + REGISTER_UPDATE, + /** App receives CONFIGURE_UPDATES intent to indicate a custom REGISTER_UPDATE intent should be sent. */ + CONFIGURE_UPDATES } /** @@ -85,6 +63,10 @@ export enum SupportedPermissions { * {@link https://developers.google.com/actions/reference/conversation#Location|Location object}. */ DEVICE_COARSE_LOCATION, + /** + * Confirmation to receive proactive content at any time from the app. + */ + UPDATE } /** @@ -137,6 +119,8 @@ export enum BuiltInArgNames { * New surface value argument. */ NEW_SURFACE, + /** Update registration value argument. */ + REGISTER_UPDATE } /** @@ -144,8 +128,17 @@ export enum BuiltInArgNames { * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. * @actionssdk * @dialogflow + * @deprecated Use {@link ConversationTypes} instead. */ -export enum ConversationStages { +export type ConversationStages = ConversationTypes; + +/** + * List of possible conversation types, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. + * @actionssdk + * @dialogflow + */ +export enum ConversationTypes { /** * Unspecified conversation state. */ @@ -224,6 +217,13 @@ export enum SignInStatus { ERROR } +/** + * Possible update trigger time context frequencies. + */ +export enum TimeContextFrequency { + DAILY +} + /** * User provided date/time info. */ @@ -277,6 +277,17 @@ export interface User { userName: UserName; /** Unique Oauth2 token. Only available with account linking. */ accessToken: string; + /** + * Timestamp for the last access from the user. + * Retrieve using app.getLastSeen() to get a Date object or null if never seen. + */ + lastSeen: string; + /** + * A string persistent across sessions. + * Retrieved and set using app.userStorage which allows you to store it like an JSON object + * which is abstracted for convenience by the client library. + */ + userStorage: string; } /** @@ -295,6 +306,17 @@ export interface Capability { name: string; } +/** + * Intent Argument. For incoming intents, the argument value can be retrieved + * using {@link AssistantApp#getArgument}. + */ +export interface IntentArgument { + /** Name of the argument. */ + name: string; + /** Text value of the argument. */ + textValue: string; +} + /** * The Actions on Google client library AssistantApp base class. * @@ -313,6 +335,20 @@ export class AssistantApp { */ data: object; + /** + * The data persistent across sessions in JSON format. + * It exists in the same context as getUser().userId + * + * @example + * // Actions SDK + * const app = new ActionsSdkApp({request: request, response: response}); + * app.userStorage.someProperty = 'someValue'; + * // Dialogflow + * const app = new DialogflowApp({request: request, response: response}); + * app.userStorage.someProperty = 'someValue'; + */ + userStorage: object; + /** * List of standard intents that the app provides. * @actionssdk @@ -339,8 +375,17 @@ export class AssistantApp { * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. * @actionssdk * @dialogflow + * @deprecated Use {@link ConversationTypes} instead. */ - readonly ConversationStages: typeof ConversationStages; + readonly ConversationStages: typeof ConversationTypes; + + /** + * List of possible conversation types, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. + * @actionssdk + * @dialogflow + */ + readonly ConversationTypes: typeof ConversationTypes; /** * List of surface capabilities supported by the app. @@ -368,6 +413,11 @@ export class AssistantApp { */ readonly Transactions: typeof TransactionValues; + /** + * Possible update trigger time context frequencies. + */ + readonly TimeContextFrequency: typeof TimeContextFrequency; + // --------------------------------------------------------------------------- // Public APIs // --------------------------------------------------------------------------- @@ -477,7 +527,7 @@ export class AssistantApp { * @param permissions Array of permissions App supports, each of * which comes from AssistantApp.SupportedPermissions. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return A response is sent to Assistant to ask for the user's permission; for any * invalid input, we return null. * @actionssdk @@ -485,6 +535,58 @@ export class AssistantApp { */ askForPermissions(context: string, permissions: string[], dialogState?: object): express.Response | null; + /** + * Prompts the user for permission to send proactive updates at any time. + * + * @example + * const app = new DialogflowApp({request, response}); + * const REQUEST_PERMISSION_ACTION = 'request.permission'; + * const PERMISSION_REQUESTED = 'permission.requested'; + * const SHOW_IMAGE = 'show.image'; + * + * function requestPermission (app) { + * app.askForUpdatePermission('show.image', [ + * { + * name: 'image_to_show', + * textValue: 'image_type_1' + * } + * ]); + * } + * + * function checkPermission (app) { + * if (app.isPermissionGranted()) { + * app.tell(`Great, I'll send an update whenever I notice a change`); + * } else { + * // Response shows that user did not grant permission + * app.tell('Alright, just let me know whenever you need the weather!'); + * } + * } + * + * function showImage (app) { + * showPicture(app.getArgument('image_to_show')); + * } + * + * const actionMap = new Map(); + * actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission); + * actionMap.set(PERMISSION_REQUESTED, checkPermission); + * actionMap.set(SHOW_IMAGE, showImage); + * app.handleRequest(actionMap); + * + * @param intent If using Dialogflow, the action name of the intent + * to be triggered when the update is received. If using Actions SDK, the + * intent name to be triggered when the update is received. + * @param intentArguments The necessary arguments + * to fulfill the intent triggered on update. These can be retrieved using + * {@link AssistantApp#getArgument}. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. + * @return A response is sent to Assistant to ask for the user's permission; for any + * invalid input, we return null. + * @actionssdk + * @dialogflow + */ + askForUpdatePermission(intent: string, intentArguments: IntentArgument[], dialogState?: object): express.Response | null; + /** * Checks whether user is in transactable state. * @@ -520,7 +622,7 @@ export class AssistantApp { * options and order options. Optional if order has no payment or * delivery. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response. * @actionssdk * @dialogflow @@ -562,7 +664,7 @@ export class AssistantApp { * transactionConfig Configuration for the transaction. Includes payment * options and order options. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response * @dialogflow */ @@ -737,7 +839,7 @@ export class AssistantApp { * query for an affirmative or negative response. If undefined or null, * Google will use a generic yes/no prompt. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response. * @actionssdk * @dialogflow @@ -782,7 +884,7 @@ export class AssistantApp { * time if not provided by user. If undefined or null, Google will use a * generic prompt. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response. * @actionssdk * @dialogflow @@ -795,11 +897,6 @@ export class AssistantApp { * Retrieve the access token in subsequent intents using * app.getUser().accessToken. * - * Note: Currently this API requires enabling the app for Transactions APIs. - * To do this, fill out the App Info section of the Actions Console project - * and check the box indicating the use of Transactions under "Privacy and - * consent". - * * @example * const app = new DialogflowApp({ request, response }); * const WELCOME_INTENT = 'input.welcome'; @@ -824,7 +921,7 @@ export class AssistantApp { * app.handleRequest(actionMap); * * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response. * @actionssdk * @dialogflow @@ -872,13 +969,53 @@ export class AssistantApp { * @param capabilities The list of capabilities required in * the surface. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response. * @dialogflow * @actionssdk */ askForNewSurface(context: string, notificationTitle: string, capabilities: SurfaceCapabilities[], dialogState?: object): express.Response | null; + /** + * Requests the user to register for daily updates. + * + * @example + * const app = new DialogflowApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const SHOW_IMAGE = 'show.image'; + * + * function welcomeIntent (app) { + * app.askToRegisterDailyUpdate('show.image', [ + * { + * name: 'image_to_show', + * textValue: 'image_type_1' + * } + * ]); + * } + * + * function showImage (app) { + * showPicture(app.getArgument('image_to_show')); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(SHOW_IMAGE, showImage); + * app.handleRequest(actionMap); + * + * @param intent If using Dialogflow, the action name of the intent + * to be triggered when the update is received. If using Actions SDK, the + * intent name to be triggered when the update is received. + * @param intentArguments The necessary arguments + * to fulfill the intent triggered on update. These can be retrieved using + * {@link AssistantApp#getArgument}. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. + * @return HTTP response. + * @dialogflow + * @actionssdk + */ + askToRegisterDailyUpdate(intent: string, intentArguments: IntentArgument[], dialogState?: object): express.Response | null; + /** * Gets the {@link User} object. * The user object contains information about the user, including @@ -945,6 +1082,18 @@ export class AssistantApp { */ getUserLocale(): string; + /** + * Get the user's last seen time as a Date object. + * Not supported in V1. + * + * @example + * const app = new DialogflowApp({request, response}); + * const lastSeen = app.getLastSeen(); + * + * @return User's last seen date or null if never seen + */ + getLastSeen(): Date | null; + /** * If granted permission to device's location in previous intent, returns device's * location (see {@link AssistantApp#askForPermissions|askForPermissions}). @@ -1225,6 +1374,16 @@ export class AssistantApp { */ isFinalReprompt(): boolean; + /** + * Returns true if user accepted update registration request. Used with + * {@link AssistantApp#askToRegisterDailyUpdate} + * + * @return True if user accepted update registration request. + * @dialogflow + * @actionssdk + */ + isUpdateRegistered(): boolean; + // --------------------------------------------------------------------------- // Response Builders // --------------------------------------------------------------------------- diff --git a/types/actions-on-google/index.d.ts b/types/actions-on-google/index.d.ts index 5f7baba3b8..378604411f 100644 --- a/types/actions-on-google/index.d.ts +++ b/types/actions-on-google/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for actions-on-google 1.5 +// Type definitions for actions-on-google 1.6 // Project: https://github.com/actions-on-google/actions-on-google-nodejs // Definitions by: Joel Hegg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/actions-on-google/response-builder.d.ts b/types/actions-on-google/response-builder.d.ts index 1e11984551..5b6e3d7522 100644 --- a/types/actions-on-google/response-builder.d.ts +++ b/types/actions-on-google/response-builder.d.ts @@ -70,6 +70,24 @@ export interface OptionInfo { synonyms: string[]; } +export interface StructuredResponse { + orderUpdate: OrderUpdate; +} + +export interface RichResponseItemBasicCard { + basicCard: BasicCard; +} + +export interface RichResponseItemSimpleResponse { + simpleResponse: SimpleResponse; +} + +export interface RichResponseItemStructuredResponse { + structuredResponse: StructuredResponse; +} + +export type RichResponseItem = RichResponseItemBasicCard | RichResponseItemSimpleResponse | RichResponseItemStructuredResponse; + /** * Class for initializing and constructing Rich Responses with chainable interface. */ @@ -85,7 +103,7 @@ export class RichResponse { * Ordered list of either SimpleResponse objects or BasicCard objects. * First item must be SimpleResponse. There can be at most one card. */ - items: Array; + items: RichResponseItem[]; /** * Ordered list of text suggestions to display. Optional. diff --git a/types/actions-on-google/transactions.d.ts b/types/actions-on-google/transactions.d.ts index 8cc26165db..b4a4285fe9 100644 --- a/types/actions-on-google/transactions.d.ts +++ b/types/actions-on-google/transactions.d.ts @@ -25,8 +25,8 @@ export interface Price { * Order rejection info. */ export interface RejectionInfo { - /** One of Transaction.RejectionType. */ - type: RejectionType; + /** One of Transaction.ReasonType. */ + type: ReasonType; /** Reason for the order rejection. */ reason: string; } @@ -51,26 +51,16 @@ export interface CancellationInfo { * Order transit info. */ export interface TransitInfo { - /** UTC timestamp of the transit update. */ - updatedTime: { - /** Seconds since Unix epoch. */ - seconds: number; - /** Partial seconds since Unix epoch. */ - nanos?: number; - }; + /** UTC timestamp of the transit update as an RFC 3339 string. */ + updatedTime: string; } /** * Order fulfillment info. */ export interface FulfillmentInfo { - /** UTC timestamp of the fulfillment update. */ - deliveryTime: { - /** Seconds since Unix epoch. */ - seconds: number; - /** Partial seconds since Unix epoch. */ - nanos?: number; - }; + /** UTC timestamp of the fulfillment update as an RFC 3339 string. */ + deliveryTime: string; } /** @@ -140,7 +130,7 @@ export interface Location { */ export interface TransactionDecision { /** One of Transactions.ConfirmationDecision. */ - userDecision: ConfirmationDecision; + userDecision: TransactionUserDecision; checkResult: { /** One of Transactions.ResultType. */ resultType: ResultType; @@ -175,32 +165,61 @@ export interface TransactionDecision { export const TransactionValues: { /** List of transaction card networks available when paying with Google. */ readonly CardNetwork: typeof CardNetwork; + /** + * List of possible item types. + * @deprecated Use {@link TransactionValues.LineItemType} instead. + */ + readonly ItemType: typeof LineItemType; /** List of possible item types. */ - readonly ItemType: typeof ItemType; + readonly LineItemType: typeof LineItemType; /** List of price types. */ readonly PriceType: typeof PriceType; /** List of possible item types. */ readonly PaymentType: typeof PaymentType; /** List of customer information properties that can be requested. */ readonly CustomerInfoProperties: typeof CustomerInfoProperties; + /** + * List of possible order confirmation user decisions + * @deprecated Use {@link TransactionValues.TransactionUserDecision} instead. + */ + readonly ConfirmationDecision: typeof TransactionUserDecision; /** List of possible order confirmation user decisions */ - readonly ConfirmationDecision: typeof ConfirmationDecision; + readonly TransactionUserDecision: typeof TransactionUserDecision; /** List of possible order states. */ readonly OrderState: typeof OrderState; + /** + * List of possible actions to take on the order. + * @deprecated Use {@link TransactionValues.ActionType} instead. + */ + readonly OrderAction: typeof ActionType; /** List of possible actions to take on the order. */ - readonly OrderAction: typeof OrderAction; + readonly ActionType: typeof ActionType; + /** + * List of possible types of order rejection. + * @deprecated Use {@link TransactionValues.ReasonType} instead. + */ + readonly RejectionType: typeof ReasonType; /** List of possible types of order rejection. */ - readonly RejectionType: typeof RejectionType; + readonly ReasonType: typeof ReasonType; /** List of possible order state objects. */ readonly OrderStateInfo: typeof OrderStateInfo; /** List of possible order transaction requirements check result types. */ readonly ResultType: typeof ResultType; /** List of possible user decisions to give delivery address. */ - readonly DeliveryAddressDecision: typeof DeliveryAddressDecision; + readonly DeliveryAddressDecision: typeof DeliveryAddressUserDecision; + /** List of possible user decisions to give delivery address. */ + readonly DeliveryAddressUserDecision: typeof DeliveryAddressUserDecision; + /** + * List of possible order location types. + * @deprecated Use {@link TransactionValues.OrderLocationType} instead. + */ + readonly LocationType: typeof OrderLocationType; /** List of possible order location types. */ - readonly LocationType: typeof LocationType; + readonly OrderLocationType: typeof OrderLocationType; /** List of possible order time types. */ readonly TimeType: typeof TimeType; + /** List of possible tokenization types for the payment method */ + readonly PaymentMethodTokenizationType: typeof PaymentMethodTokenizationType; }; /** @@ -235,8 +254,14 @@ export enum CardNetwork { /** * List of possible item types. + * @deprecated Use {@link TransactionValues.LineItemType} instead. */ -export enum ItemType { +export type ItemType = LineItemType; + +/** + * List of possible item types. + */ +export enum LineItemType { /** * Unspecified. */ @@ -323,13 +348,24 @@ export enum PaymentType { * List of customer information properties that can be requested. */ export enum CustomerInfoProperties { + CUSTOMER_INFO_PROPERTY_UNSPECIFIED, EMAIL } /** * List of possible order confirmation user decisions + * @deprecated Use {@link TransactionValues.TransactionUserDecision} instead. */ -export enum ConfirmationDecision { +export type ConfirmationDecision = TransactionUserDecision; + +/** + * List of possible order confirmation user decisions + */ +export enum TransactionUserDecision { + /** + * Unspecified user decision. + */ + UNKNOWN_USER_DECISION, /** * Order was approved by user. */ @@ -353,6 +389,10 @@ export enum ConfirmationDecision { * List of possible order states. */ export enum OrderState { + /** + * Order was created at the integrator's system. + */ + CREATED, /** * Order was rejected. */ @@ -381,8 +421,18 @@ export enum OrderState { /** * List of possible actions to take on the order. + * @deprecated Use {@link TransactionValues.ActionType} instead. */ -export enum OrderAction { +export type OrderAction = ActionType; + +/** + * List of possible actions to take on the order. + */ +export enum ActionType { + /** + * Unknown action. + */ + UNKNOWN, /** * View details. */ @@ -418,13 +468,23 @@ export enum OrderAction { /** * Review. */ - REVIEW + REVIEW, + /** + * Customer Service. + */ + CUSTOMER_SERVICE } /** * List of possible types of order rejection. + * @deprecated Use {@link TransactionValues.ReasonType} instead. */ -export enum RejectionType { +export type RejectionType = ReasonType; + +/** + * List of possible types of order rejection. + */ +export enum ReasonType { /** * Unknown */ @@ -494,8 +554,14 @@ export enum ResultType { /** * List of possible user decisions to give delivery address. + * @deprecated Use {@link TransactionValues.DeliveryAddressUserDecision} instead. */ -export enum DeliveryAddressDecision { +export type DeliveryAddressDecision = DeliveryAddressUserDecision; + +/** + * List of possible user decisions to give delivery address. + */ +export enum DeliveryAddressUserDecision { /** * Unknown. */ @@ -512,8 +578,14 @@ export enum DeliveryAddressDecision { /** * List of possible order location types. + * @deprecated Use {@link TransactionValues.OrderLocationType} instead. */ -export enum LocationType { +export type LocationType = OrderLocationType; + +/** + * List of possible order location types. + */ +export enum OrderLocationType { /** * Unknown. */ @@ -533,7 +605,11 @@ export enum LocationType { /** * Destination of the order. */ - DESTINATION + DESTINATION, + /** + * Pick up location of the order. + */ + PICK_UP } /** @@ -558,6 +634,20 @@ export enum TimeType { RESERVATION_SLOT } +/** + * List of possible tokenization types for the payment method + */ +export enum PaymentMethodTokenizationType { + /** + * Unspecified tokenization type. + */ + UNSPECIFIED_TOKENIZATION_TYPE, + /** + * Use external payment gateway tokenization API to tokenize selected payment method. + */ + PAYMENT_GATEWAY +} + /** * Class for initializing and constructing Order with chainable interface. */ @@ -655,11 +745,11 @@ export class Order { /** * Adds an associated location to the order. Up to 2 locations can be added. * - * @param type One of TransactionValues.LocationType. + * @param type One of TransactionValues.OrderLocationType. * @param location Location to add. * @return Returns current constructed Order. */ - addLocation(type: LocationType, location: Location): Order; + addLocation(type: OrderLocationType, location: Location): Order; /** * Sets an associated time to the order. @@ -780,9 +870,9 @@ export class LineItem { image?: Image; /** - * Type of the item. One of TransactionValues.ItemType. + * Type of the item. One of TransactionValues.LineItemType. */ - type?: ItemType; + type?: LineItemType; /** * Quantity of the item. @@ -834,10 +924,10 @@ export class LineItem { /** * Set the type of the item. * - * @param type Type of the item. One of TransactionValues.ItemType. + * @param type Type of the item. One of TransactionValues.LineItemType. * @return Returns current constructed LineItem. */ - setType(type: ItemType): LineItem; + setType(type: LineItemType): LineItem; /** * Set the quantity of the item. @@ -898,9 +988,9 @@ export class OrderUpdate { lineItemUpdates: object; /** - * UTC timestamp of the order update. + * UTC timestamp of the order update as an RFC 3339 string. */ - updateTime?: object; + updateTime?: string; /** * Actionable items presented to the user to manage the order. @@ -946,7 +1036,7 @@ export class OrderUpdate { * Set the update time of the order. * * @param seconds Seconds since Unix epoch. - * @param nanos Partial time units. + * @param nanos Partial time units. It is rounded to the nearest millisecond. * @return Returns current constructed OrderUpdate. */ setUpdateTime(seconds: number, nanos?: number): OrderUpdate; @@ -974,12 +1064,12 @@ export class OrderUpdate { /** * Adds an actionable item for the user to manage the order. * - * @param type One of TransactionValues.OrderActions. + * @param type One of TransactionValues.ActionType. * @param label Button label. * @param url URL to open when button is clicked. * @return Returns current constructed OrderUpdate. */ - addOrderManagementAction(type: OrderAction, label: string, url: string): OrderUpdate; + addOrderManagementAction(type: ActionType, label: string, url: string): OrderUpdate; /** * Adds a single price update for a particular line item in the order. diff --git a/types/aframe/aframe-tests.ts b/types/aframe/aframe-tests.ts index 439d314f4a..5af66a09d1 100644 --- a/types/aframe/aframe-tests.ts +++ b/types/aframe/aframe-tests.ts @@ -1,5 +1,4 @@ // Global - const threeCamera = new AFRAME.THREE.Camera(); AFRAME.TWEEN.Easing; @@ -42,9 +41,18 @@ entity.addEventListener('child-detached', (event) => { const Component = AFRAME.registerComponent('test', {}); // Scene - const scene = document.querySelector('a-scene'); scene.hasLoaded; // System const system = scene.systems['systemName']; + +// Register Custom Geometry +AFRAME.registerGeometry('a-test-geometry', { + schema: { + groupIndex: { default: 0 } + }, + init(data) { + this.geometry = new THREE.Geometry(); + } +}); diff --git a/types/aframe/index.d.ts b/types/aframe/index.d.ts index f1f5cd7a20..803318a754 100644 --- a/types/aframe/index.d.ts +++ b/types/aframe/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for AFRAME 0.5 +// Type definitions for AFRAME 0.7 // Project: https://aframe.io/ // Definitions by: Paul Shannon +// Roberto Ritger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -40,7 +41,7 @@ declare namespace AFrame { primitives: { [ key: string ]: Entity }; registerComponent(name: string, component: ComponentDefinition): ComponentConstructor; registerElement(name: string, element: ANode): void; - registerGeometry(name: string, geometery: THREE.Geometry): Geometry; + registerGeometry(name: string, geometry: GeometryDefinition): Geometry; registerPrimitive(name: string, primitive: PrimitiveDefinition): void; registerShader(name: string, shader: any): void; registerSystem(name: string, definition: SystemDefinition): void; @@ -101,7 +102,7 @@ declare namespace AFrame { name: string; schema: Schema; - init(): void; + init(data?: any): void; pause(): void; play(): void; remove(): void; @@ -124,7 +125,7 @@ declare namespace AFrame { multiple?: boolean; schema?: Schema; - init?(): void; + init?(data?: any): void; pause?(): void; play?(): void; remove?(): void; @@ -222,6 +223,10 @@ declare namespace AFrame { [ key: string ]: any; } + interface GeometryDefinition extends ComponentDefinition { + geometry?: THREE.Geometry; + } + interface GeometryDescriptor { Geometry: Geometry; schema: Schema; diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index 5d87946c3c..f068fc4e22 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for algoliasearch-client-js 3.24.5 +// Type definitions for algoliasearch-client-js 3.24.6 // Project: https://github.com/algolia/algoliasearch-client-js // Definitions by: Baptiste Coquelle // Haroen Viaene @@ -809,8 +809,8 @@ declare namespace algoliasearch { }: { facetName: string; facetQuery: string; - qp: AlgoliaQueryParameters; - }): Promise; + } & AlgoliaQueryParameters + ): Promise; /** * Search in an index * @param params query parameter @@ -826,8 +826,7 @@ declare namespace algoliasearch { }: { facetName: string; facetQuery: string; - qp: AlgoliaQueryParameters; - }, + } & AlgoliaQueryParameters, cb: (err: Error, res: any) => void ): void; /** diff --git a/types/amcharts/index.d.ts b/types/amcharts/index.d.ts index 85abd11f5c..0dae492a76 100644 --- a/types/amcharts/index.d.ts +++ b/types/amcharts/index.d.ts @@ -2191,27 +2191,45 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val chart.addGraph(graph); */ class AmGraph { + /** Text which screen readers will read if user rolls-over the bullet/column or sets focus using tab key (this is possible only if tabIndex property of AmGraph is set to some number). Text is added as aria-label tag. Note - not all screen readers and browsers support this. + @default "[[title]] [[category]] [[value]]" + */ + accessibleLabel: string; /** Name of the alpha field in your dataProvider. */ alphaField: string; + /** If you set this to true before chart is drawn, the animation of this graph won't be played. + @default false + */ + animationPlayed: boolean; + /** Allows customizing graphs balloons individually (only when ChartCursor is used). Note: the balloon object is not created automatically, you should create it before setting properties */ + balloon: AmBalloon; /** Value balloon color. Will use graph or data item color if not set. */ balloonColor: string; - /** If you set some function, the graph will call it and pass GraphDataItem and AmGraph object to it. This function should return a string which will be displayed in a balloon. */ + /** If you set some function, the graph will call it and pass GraphDataItem and AmGraph objects to it. This function should return a string which will be displayed in a balloon. */ balloonFunction(graphDataItem: GraphDataItem, amGraph: AmGraph): string; - /** Balloon text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] [[value]] */ + /** Balloon text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] or any other field name from your data provider. HTML tags can also be used. + @default [[value]] + */ balloonText: string; - /** Specifies if the line graph should be placed behind column graphs */ + /** Specifies if the line graph should be placed behind column graphs + @default false + */ behindColumns: boolean; - /** Type of the bullets. Possible values are: "none", "round", "square", "triangleUp", "triangleDown", "bubble", "custom". none */ + /** Type of the bullets. Possible values are: "none", "round", "square", "triangleUp", "triangleDown", "triangleLeft", "triangleRight", "bubble", "diamond", "xError", "yError" and "custom". + @default "none" + */ bullet: string; /** Opacity of bullets. Value range is 0 - 1. @default 1 */ bulletAlpha: number; + /** bulletAxis value is used when you are building error chart. Error chart is a regular serial or XY chart with bullet type set to "xError" or "yError". The graph should know which axis should be used to determine the size of this bullet - that's when bulletAxis should be set. Besides that, you should also set graph.errorField. You can also use other bullet types with this feature too. For example, if you set bulletAxis for XY chart, the size of a bullet will change as you zoom the chart. */ + bulletAxis: ValueAxis; /** Bullet border opacity. - @default 1 + @default 0 */ bulletBorderAlpha: number; - /** Bullet border color. Will use lineColor if not set. */ + /** Bullet border color. Will use lineColor if not set. */ bulletBorderColor: string; /** Bullet border thickness. @default 2 @@ -2221,7 +2239,11 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val bulletColor: string; /** Name of the bullet field in your dataProvider. */ bulletField: string; - /** Bullet offset. Distance from the actual data point to the bullet. Can be used to place custom bullets above the columns. */ + /** Useful for touch devices - if you set it to 20 or so, the bullets of a graph will have invisible circle around the actual bullet (bullets should still be enabled), which will be easier to touch (bullets usually are smaller and hard to hit). */ + bulletHitAreaSize: number; + /** Bullet offset. Distance from the actual data point to the bullet. Can be used to place custom bullets above the columns. + @default 0 + */ bulletOffset: number; /** Bullet size. @default 8 @@ -2229,17 +2251,31 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val bulletSize: number; /** Name of the bullet size field in your dataProvider. */ bulletSizeField: string; + /** If this field is set and addClassNames is enabled, the chart will look for a class name string in data using this setting and apply additional class names to elements of the particular data points, such as bullets. */ + classNameField: string; /** Name of the close field (used by candlesticks and ohlc) in your dataProvider. */ closeField: string; + /** In case you want to place this graph's columns in front of other columns, set this to false. In case "true", the columns will be clustered next to each other. + + NOTE: clustering works only for graphs of type "column". + @default true + */ + clustered: boolean; /** Color of value labels. Will use chart's color if not set. */ color: string; /** Name of the color field in your dataProvider. */ colorField: string; - /** Specifies whether to connect data points if data is missing. The default value is true. + /** You can use this property with non-stacked column graphs and specify order of columns of each category (starting from 0). Important: this feature does not work in stacked columns scenarios as well as with graph toggling enabled in legend. */ + columnIndexField: string; + /** You can specify custom column width for each graph individually. Value range is 0 - 1 (we set relative width, not pixel width here). */ + columnWidth: number; + /** Specifies whether to connect data points if data is missing. The default value is true. This feature does not work with XY chart. @default true */ connect: boolean; - /** Corner radius of column. It can be set both in pixels or in percents. The chart's depth and angle styles must be set to 0. The default value is 0. Note, cornerRadiusTop will be applied for all corners of the column, JavaScript charts do not have a possibility to set separate corner radius for top and bottom. As we want all the property names to be the same both on JS and Flex, we didn't change this too. */ + /** Corner radius of column. It can be set both in pixels or in percents. The chart's depth and angle styles must be set to 0. The default value is 0. Note, cornerRadiusTop will be applied for all corners of the column, JavaScript charts do not have a possibility to set separate corner radius for top and bottom. As we want all the property names to be the same both on JS and Flex, we didn't change this too. + @default 0 + */ cornerRadiusTop: number; /** If bulletsEnabled of ChartCurosor is true, a bullet on each graph follows the cursor. You can set opacity of each graphs bullet. In case you want to disable these bullets for a certain graph, set opacity to 0. @default 1 @@ -2249,55 +2285,108 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val customBullet: string; /** Name of the custom bullet field in your dataProvider. */ customBulletField: string; - /** Dash length. If you set it to a value greater than 0, the graph line will be dashed. */ + /** Path to the image for legend marker. */ + customMarker: string; + /** Dash length. If you set it to a value greater than 0, the graph line (or columns border) will be dashed. + @default 0 + */ dashLength: number; + /** Name of the dash length field in your dataProvider. This property adds a possibility to change graphs’ line from solid to dashed on any data point. You can also make columns border dashed using this setting. Note, this won't work with smoothedLineGraph. */ + dashLengthField: string; + /** Used to format balloons if value axis is date-based. + @default "MMM DD, YYYY" + */ + dateFormat: string; /** Name of the description field in your dataProvider. */ descriptionField: string; - /** Opacity of fill. Plural form is used to keep the same property names as our Flex charts'. Flex charts can accept array of numbers to generate gradients. Although you can set array here, only first value of this array will be used. */ + /** Name of error value field in your data provider. */ + errorField: string; + /** Opacity of fill. Plural form is used to keep the same property names as our Flex charts'. Flex charts can accept array of numbers to generate gradients. Although you can set array here, only first value of this array will be used. + @default 0 + */ fillAlphas: number; - /** Fill color. Will use lineColor if not set. */ - fillColors: any; - /** Name of the fill colors field in your dataProvider. */ + /** Fill color. Will use lineColor if not set. You can also set array of colors here. */ + fillColors: string; + /** Name of the fill colors field in your dataProvider. This property adds a possibility to change line graphs’ fill color on any data point to create highlighted sections of the graph. Works only with AmSerialChart. */ fillColorsField: string; - /** You can set another graph here and if fillAlpha is >0, the area from this graph to fillToGraph will be filled (instead of filling the area to the X axis). */ + /** XY chart only. If you set this property to id or reference of your X or Y axis, and the fillAlphas is > 0, the area between graph and axis will be filled with color, like in this demo. */ + fillToAxis: ValueAxis; + /** You can set another graph here and if fillAlpha is >0, the area from this graph to fillToGraph will be filled (instead of filling the area to the X axis). This feature is not supported by smoothedLine graphs and Radar chart. */ fillToGraph: AmGraph; + /** Column width in pixels. If you set this property, columns will be of a fixed width and won't adjust to the available space. */ + fixedColumnWidth: number; /** Size of value labels text. Will use chart's fontSize if not set. */ - fontSize: string; - /** Orientation of the gradient fills (only for "column" graph type). Possible values are "vertical" and "horizontal". vertical */ + fontSize: number; + /** If this is set `true`, the graph will always break the line if the distance in time between two adjacent data points is bigger than `gapPeriod x minPeriod`, even if `connect` is set to `true`. + @default false + */ + forceGap: boolean; + /** Name of the gap field in your dataProvider. You can force graph to show gap at a desired data point using this feature. This feature does not work with XY chart. */ + gapField: string; + /** Using this property you can specify when graph should display gap - if the time difference between data points is bigger than duration of minPeriod * gapPeriod, and connect property of a graph is set to false, graph will display gap. + @default 1.1 + */ + gapPeriod: number; + /** Orientation of the gradient fills (only for "column" graph type). Possible values are "vertical" and "horizontal". + @default "vertical" + */ gradientOrientation: string; - /** Specifies whether the graph is hidden. Do not use this to show/hide the graph, use hideGraph(graph) and showGraph(graph) methods instead. */ + /** Specifies whether the graph is hidden. Do not use this to show/hide the graph, use hideGraph(graph) and showGraph(graph) methods instead. + @default false + */ hidden: boolean; - /** If there are more data points than hideBulletsCount, the bullets will not be shown. 0 means the bullets will always be visible. */ + /** If there are more data points than hideBulletsCount, the bullets will not be shown. 0 means the bullets will always be visible. + @default 0 + */ hideBulletsCount: number; /** Name of the high field (used by candlesticks and ohlc) in your dataProvider. */ highField: string; - - /** Unique id of a graph. It is not required to set one, unless you want to use this graph for as your scrollbar's graph and need to indicate which graph should be used.*/ - id?: string; - + /** Unique id of a graph. It is not required to set one, unless you want to use this graph for as your scrollbar's graph and need to indicate which graph should be used. */ + id: string; /** Whether to include this graph when calculating min and max value of the axis. @default true */ includeInMinMax: boolean; + /** Data label text anchor. + @default "auto" + */ + labelAnchor: string; /** Name of label color field in data provider. */ labelColorField: string; - /** Position of value label. Possible values are: "bottom", "top", "right", "left", "inside", "middle". Sometimes position is changed by the chart, depending on a graph type, rotation, etc. top */ + /** You can use it to format labels of data items in any way you want. Graph will call this function and pass reference to GraphDataItem and formatted text as attributes. This function should return string which will be displayed as label. */ + labelFunction(value: number, valueText: string, valueAxis: ValueAxis): string; + labelFunction(valueText: string, data: Date, valueAxis: ValueAxis): string; + /** Offset of data label. + @default 0 + */ + labelOffset: number; + /** Position of value label. Possible values are: "bottom", "top", "right", "left", "inside", "middle". Sometimes position is changed by the chart, depending on a graph type, rotation, etc. + @default "top" + */ labelPosition: string; + /** Rotation of a data label. + @default 0 + */ + labelRotation: number; /** Value label text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]]. */ labelText: string; /** Legend marker opacity. Will use lineAlpha if not set. Value range is 0 - 1. */ legendAlpha: number; /** Legend marker color. Will use lineColor if not set. */ legendColor: string; + /** It is called and the following attributes are passed: dataItem, formattedText, periodValues, periodPercentValues. It should return hex color code which will be used for legend marker. */ + legendColorFunction: Object; + /** The text which will be displayed in the value portion of the legend when user is not hovering above any data point. The tags should be made out of two parts - the name of a field (value / open / close / high / low) and the value of the period you want to be show - open / close / high / low / sum / average / count. For example: [[value.sum]] means that sum of all data points of value field in the selected period will be displayed. */ + legendPeriodValueText: string; /** Legend value text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] You can also use custom fields from your dataProvider. If not set, uses Legend's valueText. */ legendValueText: string; /** Opacity of the line (or column border). Value range is 0 - 1. @default 1 */ lineAlpha: number; - /** Color of the line (or column border). If you do not set any, the color from [[AmCoordinateChart */ + /** Color of the line (or column border). If you do not set any, the color from AmCoordinateChart.colors array will be used for each subsequent graph. */ lineColor: string; - /** Name of the line color field (used by columns and candlesticks only) in your dataProvider. */ + /** Name of the line color field in your dataProvider. This property adds a possibility to change graphs’ line color on any data point to create highlighted sections of the graph. Works only with AmSerialChart. */ lineColorField: string; /** Specifies thickness of the graph line (or column border). @default 1 @@ -2305,55 +2394,125 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val lineThickness: number; /** Name of the low field (used by candlesticks and ohlc) in your dataProvider. */ lowField: string; - /** Legend marker type. You can set legend marker (key) type for individual graphs. Possible values are: "square", "circle", "line", "dashedLine", "triangleUp", "triangleDown", "bubble". */ + /** Legend marker type. You can set legend marker (key) type for individual graphs. Possible values are: square, circle, diamond, triangleUp, triangleDown, triangleLeft, triangleDown, bubble, line, none. */ markerType: string; /** Specifies size of the bullet which value is the biggest (XY chart). @default 50 */ maxBulletSize: number; - /** Specifies minimum size of the bullet (XY chart). */ + /** Specifies minimum size of the bullet (XY chart). + @default 4 + */ minBulletSize: number; - /** If you use different colors for your negative values, a graph below zero line is filled with negativeColor. With this property you can define a different base value at which colors should be changed to negative colors. */ + /** It is useful if you have really lots of data points. Based on this property the graph will omit some of the lines (if the distance between points is less that minDistance, in pixels). This will not affect the bullets or indicator in anyway, so the user will not see any difference (unless you set minValue to a bigger value, let say 5), but will increase performance as less lines will be drawn. By setting value to a bigger number you can also make your lines look less jagged. + @default 1 + */ + minDistance: number; + /** If you use different colors for your negative values, a graph below zero line is filled with negativeColor. With this property you can define a different base value at which colors should be changed to negative colors. + @default 0 + */ negativeBase: number; /** Fill opacity of negative part of the graph. Will use fillAlphas if not set. */ negativeFillAlphas: number; /** Fill color of negative part of the graph. Will use fillColors if not set. */ - negativeFillColors: any; //String /Array; + negativeFillColors: string; + /** Opacity of the negative portion of the line (or column border). Value range is 0 - 1. + @default 1 + */ + negativeLineAlpha: number; /** Color of the line (or column) when the values are negative. In case the graph type is candlestick or ohlc, negativeLineColor is used when close value is less then open value. */ negativeLineColor: string; - /** Example: {precision:-1, decimalSeparator:'.', thousandsSeparator:','}. The graph uses this object's values to format the numbers. Uses chart's numberFormatter if not defined. */ - numberFormatter: Object; - /** If you set it to true, column chart will begin new stack. This allows having Clustered and Stacked column/bar chart. */ - newStack: boolean; - /** Name of the open field (used by floating columns, candlesticks and ohlc) in your dataProvider. - @default 50 + /** If you set it to true, column chart will begin new stack. This allows having Clustered and Stacked column/bar chart. + @default false */ + newStack: boolean; + /** In case you want to have a step line graph without risers, you should set this to true. + @default false + */ + noStepRisers: boolean; + /** Name of the open field (used by floating columns, candlesticks and ohlc) in your dataProvider. */ openField: string; - /**Precision of values. Will use chart's precision if not set any.*/ - precision: number; - /** Specifies where data points should be placed - on the beginning of the period (day, hour, etc) or in the middle (only when parseDates property of categoryAxis is set to true). This setting affects Serial chart only. Possible values are "start" and "middle". middle */ + /** Value of pattern should be object with url, width, height of an image, optionally it might have x, y, randomX and randomY values. For example: {"url":"../amcharts/patterns/black/pattern1.png", "width":4, "height":4}. If you want to have individual patterns for each column, define patterns in data provider and set graph.patternField property. Check amcharts/patterns folder for some patterns. You can create your own patterns and use them. Note, x, y, randomX and randomY properties won't work with IE8 and older. 3D bar/Pie charts won't work properly with patterns. */ + pattern: Object; + /** Field name in your data provider which holds pattern information. Value of pattern should be object with url, width, height of an image, optionally it might have x, y, randomX and randomY values. For example: {"url":"../amcharts/patterns/black/pattern1.png", "width":4, "height":4}. Check amcharts/patterns folder for some patterns. You can create your own patterns and use them. Note, x, y, randomX and randomY properties won't work with IE8 and older. 3D bar/Pie charts won't work properly with patterns. */ + patternField: string; + /** This property can be used by step graphs - you can set how many periods one horizontal line should span. + @default 1 + */ + periodSpan: number; + /** Specifies where data points should be placed - on the beginning of the period (day, hour, etc) or in the middle (only when parseDates property of categoryAxis is set to true). This setting affects Serial chart only. Possible values are "start", "middle" and "end" + @default "middle" + */ pointPosition: string; - /** If graph's type is column and labelText is set, graph hides labels which do not fit into the column's space. If you don't want these labels to be hidden, set this to true. */ + /** Precision of values. Will use chart's precision if not set any. */ + precision: number; + /** If this is set to true, candlesticks will be colored in a different manner - if current close is less than current open, the candlestick will be empty, otherwise - filled with color. If previous close is less than current close, the candlestick will use positive color, otherwise - negative color. + @default false + */ + proCandlesticks: boolean; + /** Gantt chart only. Contains unmodified segment object from data provider. */ + segmentData: Object; + /** If graph's type is column and labelText is set, graph hides labels which do not fit into the column's space or go outside plot area. If you don't want these labels to be hidden, set this to true. + @default false + */ showAllValueLabels: boolean; /** Specifies whether the value balloon of this graph is shown when mouse is over data item or chart's indicator is over some series. @default true */ showBalloon: boolean; - /** Specifies graphs value at which cursor is showed. This is only important for candlestick and ohlc charts, also if column chart has "open" value. Possible values are: "open", "close", "high", "low". close */ + /** Specifies graphs value at which cursor is showed. This is only important for candlestick and ohlc charts, also if column chart has "open" value. Possible values are: "open", "close", "high", "low". "top" and "bottom" values will glue the balloon to top/bottom of the plot area. + @default "close" + */ showBalloonAt: string; + /** Works with candlestick graph type, you can set it to open, close, high, low. If you set it to high, the events will be shown at the tip of the high line. + @default "close" + */ + showBulletsAt: string; + /** If you want mouse pointer to change to hand when hovering the graph, set this property to true. + @default false + */ + showHandOnHover: boolean; + /** It can only be used together with topRadius (when columns look like cylinders). If you set it to true, the cylinder will be lowered down so that the center of it's bottom circle would be right on category axis. + @default false + */ + showOnAxis: boolean; /** If the value axis of this graph has stack types like "regular" or "100%" You can exclude this graph from stacking. @default true */ stackable: boolean; + /** Step graph only. Specifies to which direction step should be drawn. + @default "right" + */ + stepDirection: string; + /** If you set it to false, the graph will not be hidden when user clicks on legend entry. + @default true + */ + switchable: boolean; + /** In case you set it to some number, the chart will set focus on bullet/column (starting from first) when user clicks tab key. When a focus is set, screen readers like NVDA Screen reader will read label which is set using accessibleLabel property of AmGraph. Note, not all browsers and readers support this. */ + tabIndex: number; /** Graph title. */ title: string; - /** Type of the graph. Possible values are: "line", "column", "step", "smoothedLine", "candlestick", "ohlc". XY and Radar charts can only display "line" type graphs. line */ + /** If you set this to 1, columns will become cylinders (must set depth3D and angle properties of a chart to >0 values in order this to be visible). you can make columns look like cones (set topRadius to 0) or even like some glasses (set to bigger than 1). We strongly recommend setting grid opacity to 0 in order this to look good. */ + topRadius: number; + /** Type of the graph. Possible values are: "line", "column", "step", "smoothedLine", "candlestick", "ohlc". XY and Radar charts can only display "line" type graphs. + @default "line" + */ type: string; /** Name of the url field in your dataProvider. */ urlField: string; /** Target to open URLs in, i.e. _blank, _top, etc. */ urlTarget: string; - /** Specifies which value axis the graph will use. Will use the first value axis if not set. */ + /** If set to true, the bullet border will take the same color as graph line. + @default false + */ + useLineColorForBulletBorder: boolean; + /** If negativeLineColor and/or negativeFillColors are set and useNegativeColorIfDown is set to true (default is false), the line, step and column graphs will use these colors for lines, bullets or columns if previous value is bigger than current value. In case you set openField for the graph, the graph will compare current value with openField value instead of comparing to previous value. Here is a demo. + @default false + */ + useNegativeColorIfDown: boolean; + /** Specifies which value axis the graph will use. Will use the first value axis if not set. You can use reference to the real ValueAxis object or set value axis id. + @default ValueAxis + */ valueAxis: ValueAxis; /** Name of the value field in your dataProvider. */ valueField: string; @@ -2361,11 +2520,15 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val @default true */ visibleInLegend: boolean; - /** XY chart only. A horizontal value axis object to attach graph to. */ + /** XY chart only. A horizontal value axis object to attach graph to. + @default ValueAxis + */ xAxis: ValueAxis; /** XY chart only. Name of the x field in your dataProvider. */ xField: string; - /** XY chart only. A vertical value axis object to attach graph to. */ + /** XY chart only. A vertical value axis object to attach graph to. + @default ValueAxis + */ yAxis: ValueAxis; /** XY chart only. Name of the y field in your dataProvider. */ yField: string; diff --git a/types/amqplib/index.d.ts b/types/amqplib/index.d.ts index 91060d23b0..2d5cb3ba99 100644 --- a/types/amqplib/index.d.ts +++ b/types/amqplib/index.d.ts @@ -63,4 +63,4 @@ export interface ConfirmChannel extends Channel { waitForConfirms(): Promise; } -export function connect(url: string, socketOptions?: any): Promise; +export function connect(url: string | Options.Connect, socketOptions?: any): Promise; diff --git a/types/amqplib/properties.d.ts b/types/amqplib/properties.d.ts index 12514d7810..af90909d8c 100644 --- a/types/amqplib/properties.d.ts +++ b/types/amqplib/properties.d.ts @@ -21,6 +21,64 @@ export namespace Replies { } export namespace Options { + interface Connect { + /** + * The to be used protocol + * + * Default value: 'amqp' + */ + protocol?: string; + /** + * Hostname used for connecting to the server. + * + * Default value: 'localhost' + */ + hostname?: string; + /** + * Port used for connecting to the server. + * + * Default value: 5672 + */ + port?: number; + /** + * Username used for authenticating against the server. + * + * Default value: 'guest' + */ + username?: string; + /** + * Password used for authenticating against the server. + * + * Default value: 'guest' + */ + password?: string; + /** + * The desired locale for error messages. RabbitMQ only ever uses en_US + * + * Default value: 'en_US' + */ + locale?: string; + /** + * The size in bytes of the maximum frame allowed over the connection. 0 means + * no limit (but since frames have a size field which is an unsigned 32 bit integer, it’s perforce 2^32 - 1). + * + * Default value: 0x1000 (4kb) - That's the allowed minimum, it will fit many purposes + */ + frameMax?: number; + /** + * The period of the connection heartbeat in seconds. + * + * Default value: 0 + */ + heartbeat?: number; + /** + * What VHost shall be used. + * + * Default value: '/' + */ + vhost?: string; + } + interface AssertQueue { exclusive?: boolean; durable?: boolean; @@ -85,4 +143,4 @@ export interface Message { content: Buffer; fields: any; properties: any; -} \ No newline at end of file +} diff --git a/types/angular-hotkeys/README.md b/types/angular-hotkeys/README.md deleted file mode 100644 index a31ed8a936..0000000000 --- a/types/angular-hotkeys/README.md +++ /dev/null @@ -1,55 +0,0 @@ -## What is it? - -This is a typescript interface to be used with [angular-hotkeys](https://github.com/chieffancypants/angular-hotkeys/). - -## What are declaration files? - -See the [TypeScript handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html). - - -## How do I get them? - -### npm - -This is the preferred method. This is only available for TypeScript 2.0+ users. For these typings: - -```sh -npm install --save-dev @types/angular-hotkeys -``` - -The types should then be automatically included by the compiler. -See more in the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html). - - -### Other methods - -These can be used by TypeScript 1.0. - -* [Typings](https://github.com/typings/typings) -* ~~[NuGet](http://nuget.org/Tpackages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off) -* Manually download from the `master` branch of this repository - -You may need to add manual [references](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html). - -## How to use - -After installing a package you can import the definition file and begin using it as so: - -```ts - -import * as hotkeys from '../../node_modules/@types/angular-hotkeys' - -class FooController { - static $inject = [ - 'hotkeys' - ]; - - constructor( - private hotkeys: ng.hotkeys.HotkeysProvider - ) { } -} - -``` - -for a detailed explanation of the behavior of angular-hotkeys please refer to [its documentation](https://github.com/chieffancypants/angular-hotkeys/) - diff --git a/types/angular-hotkeys/angular-hotkeys-tests.ts b/types/angular-hotkeys/angular-hotkeys-tests.ts index c0bd9b974d..503080e9d8 100644 --- a/types/angular-hotkeys/angular-hotkeys-tests.ts +++ b/types/angular-hotkeys/angular-hotkeys-tests.ts @@ -1,30 +1,67 @@ -var scope: ng.IScope; -var hotkeyProvider: ng.hotkeys.HotkeysProvider; -var hotkeyObj: ng.hotkeys.Hotkey; +import { HotkeysProvider, Hotkey } from 'angular-hotkeys'; +import { module } from 'angular'; -hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} ); -hotkeyProvider.add(["mod+s"], "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} ); -hotkeyProvider.add(hotkeyObj); -hotkeyProvider.bindTo(scope); -hotkeyProvider.del("mod+s"); -hotkeyProvider.del(["mod+s"]); -hotkeyProvider.get("mod+s"); -hotkeyProvider.get(["mod+s"]); -hotkeyProvider.toggleCheatSheet(); - -hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description ,hotkeyObj.callback); - -hotkeyProvider.bindTo(scope) - .add(hotkeyObj) - .add(hotkeyObj) - .add({ - combo: 'w', - description: 'blah blah', - callback: function() {} - }) - .add({ - combo: ['w', 'mod+w'], - description: 'blah blah', - callback: function() {} +module('myApp', ['cfp.hotkeys']) + .config((hotkeysProvider: HotkeysProvider) => { + hotkeysProvider.includeCheatSheet = false; + const somehotKeyObj: Hotkey = { + combo: '', + callback: () => { } + }; }); +function someInjectionService( + scope: ng.IScope, + hotkeyProvider: ng.hotkeys.HotkeysProvider, + hotkeyObj: ng.hotkeys.Hotkey +) { + hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => { }); + hotkeyProvider.add(["mod+s"], "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => { }); + hotkeyProvider.add(hotkeyObj); + hotkeyProvider.bindTo(scope); + hotkeyProvider.del("mod+s"); + hotkeyProvider.del(["mod+s"]); + hotkeyProvider.get("mod+s"); + hotkeyProvider.get(["mod+s"]); + hotkeyProvider.toggleCheatSheet(); + + hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description, hotkeyObj.callback); + + hotkeyProvider.bindTo(scope) + .add(hotkeyObj) + .add(hotkeyObj) + .add({ + combo: 'w', + description: 'blah blah', + callback: () => { } + }) + .add({ + combo: ['w', 'mod+w'], + description: 'blah blah', + callback: () => { } + }); + + hotkeyProvider.add({ + combo: 'ctrl+w', + description: 'Description goes here', + callback: (event, hotkey) => { + event.preventDefault(); + } + }); + + hotkeyProvider.add({ + combo: 'ctrl+x', + callback: (event, hotkey) => { + // + } + }); + + hotkeyProvider.add({ + combo: 'ctrl+w', + description: 'Description goes here', + allowIn: ['INPUT', 'SELECT', 'TEXTAREA'], + callback(event, hotkey) { + event.preventDefault(); + } + }); +} diff --git a/types/angular-hotkeys/index.d.ts b/types/angular-hotkeys/index.d.ts index 0f0be68d8e..360e2cefbe 100644 --- a/types/angular-hotkeys/index.d.ts +++ b/types/angular-hotkeys/index.d.ts @@ -1,12 +1,10 @@ -// Type definitions for angular-hotkeys +// Type definitions for angular-hotkeys 1.7 // Project: https://github.com/chieffancypants/angular-hotkeys -// Definitions by: Jason Zhao , Stefan Steinhart +// Definitions by: Jason Zhao +// Stefan Steinhart +// Cyril Gandon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -//readme written by David Valentine - - -/// import * as ng from 'angular'; @@ -15,46 +13,123 @@ export type HotkeysProviderChained = ng.hotkeys.HotkeysProviderChained; export type Hotkey = ng.hotkeys.Hotkey; declare module 'angular' { - export namespace hotkeys { - + namespace hotkeys { interface HotkeysProvider { - template: string; - templateTitle: string; + /** + * Configurable setting to disable the cheatsheet entirely. + * @default true + */ includeCheatSheet: boolean; + /** + * Configurable setting to disable ngRoute hooks. + */ + useNgRoute: boolean; + /** + * Configurable setting for the cheat sheet title + * @default 'Keyboard Shortcuts' + */ + templateTitle: string; + /** + * Configurable settings for the cheat sheet header in HTML. + * This overrides the normal title if specified. + * @default null + */ + templateHeader: string | null; + /** + * Configurable settings for the cheat sheet footer in HTML. + * @default null + */ + templateFooter: string | null; + /** + * Cheat sheet template in the event you want to totally customize it. + */ + template: string; + /** + * Configurable setting for the cheat sheet hotkey. + * @default '?' + */ cheatSheetHotkey: string; + /** + * Configurable setting for the cheat sheet description. + * @default 'Show / hide this help menu' + */ cheatSheetDescription: string; - add(combo: string | string[], callback: (event: Event, hotkey?: Hotkey) => void, action?: string, allowIn?: Array, persistent?: boolean): ng.hotkeys.Hotkey; + /** + * Creates a new Hotkey and creates the Mousetrap binding. + */ + add(combo: string | string[], description?: string, callback?: (event: Event, hotkey: Hotkey) => void, action?: string, allowIn?: string[], persistent?: boolean): Hotkey; - add(combo: string | string[], description: string, callback: (event: Event, hotkey?: Hotkey) => void, action?: string, allowIn?: Array, persistent?: boolean): ng.hotkeys.Hotkey; + /** + * Creates a new Hotkey and creates the Mousetrap binding. + */ + add(hotkeyObj: Hotkey): Hotkey; - add(hotkeyObj: ng.hotkeys.Hotkey): ng.hotkeys.Hotkey; + /** + * Binds the hotkey to a particular scope. + * Useful if the scope is destroyed, we can automatically destroy the hotkey binding. + * @param scope The scope to bind to + */ + bindTo(scope: IScope): HotkeysProviderChained; - bindTo(scope: ng.IScope): ng.hotkeys.HotkeysProviderChained; + /** + * Removes and unbinds a hotkey + * @param combo The keyboard combo (shortcut) or the HotKey object + */ + del(combo: string | string[] | Hotkey): void; - del(combo: string | string[]): void; - - del(hotkeyObj: ng.hotkeys.Hotkey): void; - - get(combo: string | string[]): ng.hotkeys.Hotkey; + /** + * Returns the Hotkey object + * @param combo The keyboard combo (shortcut) + */ + get(combo: string | string[]): Hotkey; + /** + * Toggles the help menu element's visiblity + */ toggleCheatSheet(): void; - + /** + * Purges all non-persistent hotkeys (such as those defined in routes) + * + * Without this, the same hotkey would get recreated everytime + * the route is accessed. + */ purgeHotkeys(): void; } interface HotkeysProviderChained { - add(combo: string | string[], description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): HotkeysProviderChained; + add(combo: string | string[], description: string, callback: (event: Event, hotkeys: Hotkey) => void): HotkeysProviderChained; - add(hotkeyObj: ng.hotkeys.Hotkey): HotkeysProviderChained; + add(hotkeyObj: Hotkey): HotkeysProviderChained; } interface Hotkey { + /** + * They keyboard combo (shortcut) you want to bind to. + */ combo: string | string[]; + /** + * The description for what the combo does and is only used for the Cheat Sheet. + * If it is not supplied, it will not show up, and in effect, allows you to have unlisted hotkeys. + */ description?: string; - callback: (event: Event, hotkey: ng.hotkeys.Hotkey) => void; + /** + * The function to execute when the key(s) are pressed. Passes along two arguments, event and hotkey + */ + callback(event: Event, hotkey: Hotkey): void; + /** + * The type of event to listen for, such as keypress, keydown or keyup. + * Usage of this parameter is discouraged as the underlying library will pick the most suitable option automatically. + * This should only be necessary in advanced situations. + */ action?: string; - allowIn?: Array; + /** + * An array of tag names to allow this combo in ('INPUT', 'SELECT', and/or 'TEXTAREA') + */ + allowIn?: Array<'INPUT' | 'SELECT' | 'TEXTAREA'>; + /** + * Whether the hotkey persists navigation events + */ persistent?: boolean; } } diff --git a/types/angular-hotkeys/tsconfig.json b/types/angular-hotkeys/tsconfig.json index f277241888..acb11ff247 100644 --- a/types/angular-hotkeys/tsconfig.json +++ b/types/angular-hotkeys/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +21,4 @@ "index.d.ts", "angular-hotkeys-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/angular-hotkeys/tslint.json b/types/angular-hotkeys/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/angular-hotkeys/tslint.json +++ b/types/angular-hotkeys/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/angular-material/angular-material-tests.ts b/types/angular-material/angular-material-tests.ts index d46a51d578..ac4a1386cd 100644 --- a/types/angular-material/angular-material-tests.ts +++ b/types/angular-material/angular-material-tests.ts @@ -5,6 +5,7 @@ interface TestScope extends ng.IScope { } myApp.config(( + $mdAriaProvider: ng.material.IAriaProvider, $mdThemingProvider: ng.material.IThemingProvider, $mdIconProvider: ng.material.IIconProvider, $mdProgressCircularProvider: ng.material.IProgressCircularProvider) => { @@ -52,6 +53,9 @@ myApp.config(( return c * Math.pow(2, (t / d - 1) * 10) + b; } }); + + // Globally disables all ARIA warnings. + $mdAriaProvider.disableWarnings(); }); myApp.controller('BottomSheetController', ($scope: TestScope, $mdBottomSheet: ng.material.IBottomSheetService, $q: ng.IQService) => { @@ -136,6 +140,9 @@ myApp.controller('DialogController', ($scope: TestScope, $mdDialog: ng.material. $scope['promptDialog'] = () => { $mdDialog.show($mdDialog.prompt().initialValue('Buddy')); }; + $scope['promptDialog'] = () => { + $mdDialog.show($mdDialog.prompt().required(true)); + }; $scope['prerenderedDialog'] = () => { $mdDialog.show({ template: 'Hello!', diff --git a/types/angular-material/index.d.ts b/types/angular-material/index.d.ts index 4bfadbf9b3..92f6d46751 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for angular-material 1.1 // Project: https://github.com/angular/material -// Definitions by: Blake Bigelow , Peter Hajdu , Davide Donadello , Geert Jansen +// Definitions by: Blake Bigelow , Peter Hajdu , Davide Donadello , Geert Jansen , Edward Knowles // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -11,6 +11,10 @@ export = _; declare module 'angular' { namespace material { + interface IAriaProvider { + disableWarnings(): void; + } + interface ResolveObject { [name: string]: Injectable<(...args: any[]) => PromiseLike>; } @@ -76,6 +80,7 @@ declare module 'angular' { interface IPromptDialog extends IPresetDialog { cancel(cancel: string): IPromptDialog; + required(required: boolean): IPromptDialog; // default: false placeholder(placeholder: string): IPromptDialog; initialValue(initialValue: string): IPromptDialog; } diff --git a/types/angular-sanitize/angular-sanitize-tests.ts b/types/angular-sanitize/angular-sanitize-tests.ts index b093f2bbb0..51d48db90d 100644 --- a/types/angular-sanitize/angular-sanitize-tests.ts +++ b/types/angular-sanitize/angular-sanitize-tests.ts @@ -4,5 +4,6 @@ declare var $sanitizeService: ng.sanitize.ISanitizeService; shouldBeString = $sanitizeService(shouldBeString); declare var $linky: ng.sanitize.filter.ILinky; +shouldBeString = $linky(shouldBeString); shouldBeString = $linky(shouldBeString, "target"); shouldBeString = $linky(shouldBeString, shouldBeString); diff --git a/types/angular-sanitize/index.d.ts b/types/angular-sanitize/index.d.ts index ad42ec362e..b9d16aaeb2 100644 --- a/types/angular-sanitize/index.d.ts +++ b/types/angular-sanitize/index.d.ts @@ -36,7 +36,7 @@ declare module 'angular' { * see https://docs.angularjs.org/api/ngSanitize/filter/linky */ interface ILinky { - (text: string, target: string, attributes?: { [attribute: string]: string } | ((url: string) => { [attribute: string]: string })): string; + (text: string, target?: string, attributes?: { [attribute: string]: string } | ((url: string) => { [attribute: string]: string })): string; } } diff --git a/types/ansi-regex/ansi-regex-tests.ts b/types/ansi-regex/ansi-regex-tests.ts new file mode 100644 index 0000000000..a5787902f0 --- /dev/null +++ b/types/ansi-regex/ansi-regex-tests.ts @@ -0,0 +1,13 @@ +import ansiRegex = require("ansi-regex"); + +ansiRegex(); // $ExpectType RegExp + +// From the ansi-regex README.md +ansiRegex().test('\u001B[4mcake\u001B[0m'); // $ExpectType boolean +// => true + +ansiRegex().test('cake'); // $ExpectType boolean +// => false + +'\u001B[4mcake\u001B[0m'.match(ansiRegex()); // $ExpectType RegExpMatchArray | null +// => ['\u001B[4m', '\u001B[0m'] diff --git a/types/ansi-regex/index.d.ts b/types/ansi-regex/index.d.ts new file mode 100644 index 0000000000..34890912dc --- /dev/null +++ b/types/ansi-regex/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for ansi-regex 3.0 +// Project: https://github.com/chalk/ansi-regex#readme +// Definitions by: Manish Vachharajani +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function r(): RegExp; +export = r; diff --git a/types/ansi-regex/tsconfig.json b/types/ansi-regex/tsconfig.json new file mode 100644 index 0000000000..cf1ac84a5c --- /dev/null +++ b/types/ansi-regex/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ansi-regex-tests.ts" + ] +} diff --git a/types/ansi-regex/tslint.json b/types/ansi-regex/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ansi-regex/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/applicationinsights-js/index.d.ts b/types/applicationinsights-js/index.d.ts index 17137d67dd..4214837ddf 100644 --- a/types/applicationinsights-js/index.d.ts +++ b/types/applicationinsights-js/index.d.ts @@ -777,7 +777,7 @@ declare module Microsoft.ApplicationInsights { * @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service. * @param accountId {string} - An optional string to represent the account associated with the authenticated user. */ - setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string): any; + setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string, storeInCookie?: boolean): any; /** * Clears the authenticated user id and the account id from the user context. */ diff --git a/types/atom/index.d.ts b/types/atom/index.d.ts index 0db2ab0002..2a13373b7d 100644 --- a/types/atom/index.d.ts +++ b/types/atom/index.d.ts @@ -5265,7 +5265,7 @@ export interface CursorPositionChangedEvent { newBufferPosition: Point; newScreenPosition: Point; textChanged: boolean; - Cursor: Cursor; + cursor: Cursor; } export interface DecorationPropsChangedEvent { diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index 57ca68a915..d24cb40081 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -529,8 +529,8 @@ export class ManagementClient { deleteEmailProvider(): Promise; deleteEmailProvider(cb?: (err: Error, data: any) => void): void; - updateEmailProvider(data: Data): Promise; - updateEmailProvider(data: Data, cb?: (err: Error, data: any) => void): void; + updateEmailProvider(params: {}, data: Data): Promise; + updateEmailProvider(params: {}, data: Data, cb?: (err: Error, data: any) => void): void; // Statistics diff --git a/types/autobahn/index.d.ts b/types/autobahn/index.d.ts index 7f01a53e3a..969c703478 100644 --- a/types/autobahn/index.d.ts +++ b/types/autobahn/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for AutobahnJS v0.9.7 // Project: http://autobahn.ws/js/ -// Definitions by: Elad Zelingher , Andy Hawkins , Wladimir Totino +// Definitions by: Elad Zelingher , Andy Hawkins , Wladimir Totino , Mathias Teier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -179,6 +179,7 @@ declare namespace autobahn { interface ISubscribeOptions { match?: string; + get_retained?: boolean; } interface IRegisterOptions { diff --git a/types/babel-traverse/index.d.ts b/types/babel-traverse/index.d.ts index 682550b161..df420c17bd 100644 --- a/types/babel-traverse/index.d.ts +++ b/types/babel-traverse/index.d.ts @@ -600,185 +600,185 @@ export class NodePath { addComments(type: string, comments: any[]): void; // ------------------------- isXXX ------------------------- - isArrayExpression(opts?: object): boolean; - isAssignmentExpression(opts?: object): boolean; - isBinaryExpression(opts?: object): boolean; - isDirective(opts?: object): boolean; - isDirectiveLiteral(opts?: object): boolean; - isBlockStatement(opts?: object): boolean; - isBreakStatement(opts?: object): boolean; - isCallExpression(opts?: object): boolean; - isCatchClause(opts?: object): boolean; - isConditionalExpression(opts?: object): boolean; - isContinueStatement(opts?: object): boolean; - isDebuggerStatement(opts?: object): boolean; - isDoWhileStatement(opts?: object): boolean; - isEmptyStatement(opts?: object): boolean; - isExpressionStatement(opts?: object): boolean; - isFile(opts?: object): boolean; - isForInStatement(opts?: object): boolean; - isForStatement(opts?: object): boolean; - isFunctionDeclaration(opts?: object): boolean; - isFunctionExpression(opts?: object): boolean; - isIdentifier(opts?: object): boolean; - isIfStatement(opts?: object): boolean; - isLabeledStatement(opts?: object): boolean; - isStringLiteral(opts?: object): boolean; - isNumericLiteral(opts?: object): boolean; - isNullLiteral(opts?: object): boolean; - isBooleanLiteral(opts?: object): boolean; - isRegExpLiteral(opts?: object): boolean; - isLogicalExpression(opts?: object): boolean; - isMemberExpression(opts?: object): boolean; - isNewExpression(opts?: object): boolean; - isProgram(opts?: object): boolean; - isObjectExpression(opts?: object): boolean; - isObjectMethod(opts?: object): boolean; - isObjectProperty(opts?: object): boolean; - isRestElement(opts?: object): boolean; - isReturnStatement(opts?: object): boolean; - isSequenceExpression(opts?: object): boolean; - isSwitchCase(opts?: object): boolean; - isSwitchStatement(opts?: object): boolean; - isThisExpression(opts?: object): boolean; - isThrowStatement(opts?: object): boolean; - isTryStatement(opts?: object): boolean; - isUnaryExpression(opts?: object): boolean; - isUpdateExpression(opts?: object): boolean; - isVariableDeclaration(opts?: object): boolean; - isVariableDeclarator(opts?: object): boolean; - isWhileStatement(opts?: object): boolean; - isWithStatement(opts?: object): boolean; - isAssignmentPattern(opts?: object): boolean; - isArrayPattern(opts?: object): boolean; - isArrowFunctionExpression(opts?: object): boolean; - isClassBody(opts?: object): boolean; - isClassDeclaration(opts?: object): boolean; - isClassExpression(opts?: object): boolean; - isExportAllDeclaration(opts?: object): boolean; - isExportDefaultDeclaration(opts?: object): boolean; - isExportNamedDeclaration(opts?: object): boolean; - isExportSpecifier(opts?: object): boolean; - isForOfStatement(opts?: object): boolean; - isImportDeclaration(opts?: object): boolean; - isImportDefaultSpecifier(opts?: object): boolean; - isImportNamespaceSpecifier(opts?: object): boolean; - isImportSpecifier(opts?: object): boolean; - isMetaProperty(opts?: object): boolean; - isClassMethod(opts?: object): boolean; - isObjectPattern(opts?: object): boolean; - isSpreadElement(opts?: object): boolean; - isSuper(opts?: object): boolean; - isTaggedTemplateExpression(opts?: object): boolean; - isTemplateElement(opts?: object): boolean; - isTemplateLiteral(opts?: object): boolean; - isYieldExpression(opts?: object): boolean; - isAnyTypeAnnotation(opts?: object): boolean; - isArrayTypeAnnotation(opts?: object): boolean; - isBooleanTypeAnnotation(opts?: object): boolean; - isBooleanLiteralTypeAnnotation(opts?: object): boolean; - isNullLiteralTypeAnnotation(opts?: object): boolean; - isClassImplements(opts?: object): boolean; - isClassProperty(opts?: object): boolean; - isDeclareClass(opts?: object): boolean; - isDeclareFunction(opts?: object): boolean; - isDeclareInterface(opts?: object): boolean; - isDeclareModule(opts?: object): boolean; - isDeclareTypeAlias(opts?: object): boolean; - isDeclareVariable(opts?: object): boolean; - isExistentialTypeParam(opts?: object): boolean; - isFunctionTypeAnnotation(opts?: object): boolean; - isFunctionTypeParam(opts?: object): boolean; - isGenericTypeAnnotation(opts?: object): boolean; - isInterfaceExtends(opts?: object): boolean; - isInterfaceDeclaration(opts?: object): boolean; - isIntersectionTypeAnnotation(opts?: object): boolean; - isMixedTypeAnnotation(opts?: object): boolean; - isNullableTypeAnnotation(opts?: object): boolean; - isNumericLiteralTypeAnnotation(opts?: object): boolean; - isNumberTypeAnnotation(opts?: object): boolean; - isStringLiteralTypeAnnotation(opts?: object): boolean; - isStringTypeAnnotation(opts?: object): boolean; - isThisTypeAnnotation(opts?: object): boolean; - isTupleTypeAnnotation(opts?: object): boolean; - isTypeofTypeAnnotation(opts?: object): boolean; - isTypeAlias(opts?: object): boolean; - isTypeAnnotation(opts?: object): boolean; - isTypeCastExpression(opts?: object): boolean; - isTypeParameterDeclaration(opts?: object): boolean; - isTypeParameterInstantiation(opts?: object): boolean; - isObjectTypeAnnotation(opts?: object): boolean; - isObjectTypeCallProperty(opts?: object): boolean; - isObjectTypeIndexer(opts?: object): boolean; - isObjectTypeProperty(opts?: object): boolean; - isQualifiedTypeIdentifier(opts?: object): boolean; - isUnionTypeAnnotation(opts?: object): boolean; - isVoidTypeAnnotation(opts?: object): boolean; - isJSXAttribute(opts?: object): boolean; - isJSXClosingElement(opts?: object): boolean; - isJSXElement(opts?: object): boolean; - isJSXEmptyExpression(opts?: object): boolean; - isJSXExpressionContainer(opts?: object): boolean; - isJSXIdentifier(opts?: object): boolean; - isJSXMemberExpression(opts?: object): boolean; - isJSXNamespacedName(opts?: object): boolean; - isJSXOpeningElement(opts?: object): boolean; - isJSXSpreadAttribute(opts?: object): boolean; - isJSXText(opts?: object): boolean; - isNoop(opts?: object): boolean; - isParenthesizedExpression(opts?: object): boolean; - isAwaitExpression(opts?: object): boolean; - isBindExpression(opts?: object): boolean; - isDecorator(opts?: object): boolean; - isDoExpression(opts?: object): boolean; - isExportDefaultSpecifier(opts?: object): boolean; - isExportNamespaceSpecifier(opts?: object): boolean; - isRestProperty(opts?: object): boolean; - isSpreadProperty(opts?: object): boolean; - isExpression(opts?: object): boolean; - isBinary(opts?: object): boolean; - isScopable(opts?: object): boolean; - isBlockParent(opts?: object): boolean; - isBlock(opts?: object): boolean; - isStatement(opts?: object): boolean; - isTerminatorless(opts?: object): boolean; - isCompletionStatement(opts?: object): boolean; - isConditional(opts?: object): boolean; - isLoop(opts?: object): boolean; - isWhile(opts?: object): boolean; - isExpressionWrapper(opts?: object): boolean; - isFor(opts?: object): boolean; - isForXStatement(opts?: object): boolean; - isFunction(opts?: object): boolean; - isFunctionParent(opts?: object): boolean; - isPureish(opts?: object): boolean; - isDeclaration(opts?: object): boolean; - isLVal(opts?: object): boolean; - isLiteral(opts?: object): boolean; - isImmutable(opts?: object): boolean; - isUserWhitespacable(opts?: object): boolean; - isMethod(opts?: object): boolean; - isObjectMember(opts?: object): boolean; - isProperty(opts?: object): boolean; - isUnaryLike(opts?: object): boolean; - isPattern(opts?: object): boolean; - isClass(opts?: object): boolean; - isModuleDeclaration(opts?: object): boolean; - isExportDeclaration(opts?: object): boolean; - isModuleSpecifier(opts?: object): boolean; - isFlow(opts?: object): boolean; - isFlowBaseAnnotation(opts?: object): boolean; - isFlowDeclaration(opts?: object): boolean; - isJSX(opts?: object): boolean; - isNumberLiteral(opts?: object): boolean; - isRegexLiteral(opts?: object): boolean; - isReferencedIdentifier(opts?: object): boolean; - isReferencedMemberExpression(opts?: object): boolean; - isBindingIdentifier(opts?: object): boolean; - isScope(opts?: object): boolean; + isArrayExpression(opts?: object): this is NodePath ; + isAssignmentExpression(opts?: object): this is NodePath; + isBinaryExpression(opts?: object): this is NodePath; + isDirective(opts?: object): this is NodePath; + isDirectiveLiteral(opts?: object): this is NodePath; + isBlockStatement(opts?: object): this is NodePath; + isBreakStatement(opts?: object): this is NodePath; + isCallExpression(opts?: object): this is NodePath; + isCatchClause(opts?: object): this is NodePath; + isConditionalExpression(opts?: object): this is NodePath; + isContinueStatement(opts?: object): this is NodePath; + isDebuggerStatement(opts?: object): this is NodePath; + isDoWhileStatement(opts?: object): this is NodePath; + isEmptyStatement(opts?: object): this is NodePath; + isExpressionStatement(opts?: object): this is NodePath; + isFile(opts?: object): this is NodePath; + isForInStatement(opts?: object): this is NodePath; + isForStatement(opts?: object): this is NodePath; + isFunctionDeclaration(opts?: object): this is NodePath; + isFunctionExpression(opts?: object): this is NodePath; + isIdentifier(opts?: object): this is NodePath; + isIfStatement(opts?: object): this is NodePath; + isLabeledStatement(opts?: object): this is NodePath; + isStringLiteral(opts?: object): this is NodePath; + isNumericLiteral(opts?: object): this is NodePath; + isNullLiteral(opts?: object): this is NodePath; + isBooleanLiteral(opts?: object): this is NodePath; + isRegExpLiteral(opts?: object): this is NodePath; + isLogicalExpression(opts?: object): this is NodePath; + isMemberExpression(opts?: object): this is NodePath; + isNewExpression(opts?: object): this is NodePath; + isProgram(opts?: object): this is NodePath; + isObjectExpression(opts?: object): this is NodePath; + isObjectMethod(opts?: object): this is NodePath; + isObjectProperty(opts?: object): this is NodePath; + isRestElement(opts?: object): this is NodePath; + isReturnStatement(opts?: object): this is NodePath; + isSequenceExpression(opts?: object): this is NodePath; + isSwitchCase(opts?: object): this is NodePath; + isSwitchStatement(opts?: object): this is NodePath; + isThisExpression(opts?: object): this is NodePath; + isThrowStatement(opts?: object): this is NodePath; + isTryStatement(opts?: object): this is NodePath; + isUnaryExpression(opts?: object): this is NodePath; + isUpdateExpression(opts?: object): this is NodePath; + isVariableDeclaration(opts?: object): this is NodePath; + isVariableDeclarator(opts?: object): this is NodePath; + isWhileStatement(opts?: object): this is NodePath; + isWithStatement(opts?: object): this is NodePath; + isAssignmentPattern(opts?: object): this is NodePath; + isArrayPattern(opts?: object): this is NodePath; + isArrowFunctionExpression(opts?: object): this is NodePath; + isClassBody(opts?: object): this is NodePath; + isClassDeclaration(opts?: object): this is NodePath; + isClassExpression(opts?: object): this is NodePath; + isExportAllDeclaration(opts?: object): this is NodePath; + isExportDefaultDeclaration(opts?: object): this is NodePath; + isExportNamedDeclaration(opts?: object): this is NodePath; + isExportSpecifier(opts?: object): this is NodePath; + isForOfStatement(opts?: object): this is NodePath; + isImportDeclaration(opts?: object): this is NodePath; + isImportDefaultSpecifier(opts?: object): this is NodePath; + isImportNamespaceSpecifier(opts?: object): this is NodePath; + isImportSpecifier(opts?: object): this is NodePath; + isMetaProperty(opts?: object): this is NodePath; + isClassMethod(opts?: object): this is NodePath; + isObjectPattern(opts?: object): this is NodePath; + isSpreadElement(opts?: object): this is NodePath; + isSuper(opts?: object): this is NodePath; + isTaggedTemplateExpression(opts?: object): this is NodePath; + isTemplateElement(opts?: object): this is NodePath; + isTemplateLiteral(opts?: object): this is NodePath; + isYieldExpression(opts?: object): this is NodePath; + isAnyTypeAnnotation(opts?: object): this is NodePath; + isArrayTypeAnnotation(opts?: object): this is NodePath; + isBooleanTypeAnnotation(opts?: object): this is NodePath; + isBooleanLiteralTypeAnnotation(opts?: object): this is NodePath; + isNullLiteralTypeAnnotation(opts?: object): this is NodePath; + isClassImplements(opts?: object): this is NodePath; + isClassProperty(opts?: object): this is NodePath; + isDeclareClass(opts?: object): this is NodePath; + isDeclareFunction(opts?: object): this is NodePath; + isDeclareInterface(opts?: object): this is NodePath; + isDeclareModule(opts?: object): this is NodePath; + isDeclareTypeAlias(opts?: object): this is NodePath; + isDeclareVariable(opts?: object): this is NodePath; + isExistentialTypeParam(opts?: object): this is NodePath; + isFunctionTypeAnnotation(opts?: object): this is NodePath; + isFunctionTypeParam(opts?: object): this is NodePath; + isGenericTypeAnnotation(opts?: object): this is NodePath; + isInterfaceExtends(opts?: object): this is NodePath; + isInterfaceDeclaration(opts?: object): this is NodePath; + isIntersectionTypeAnnotation(opts?: object): this is NodePath; + isMixedTypeAnnotation(opts?: object): this is NodePath; + isNullableTypeAnnotation(opts?: object): this is NodePath; + isNumericLiteralTypeAnnotation(opts?: object): this is NodePath; + isNumberTypeAnnotation(opts?: object): this is NodePath; + isStringLiteralTypeAnnotation(opts?: object): this is NodePath; + isStringTypeAnnotation(opts?: object): this is NodePath; + isThisTypeAnnotation(opts?: object): this is NodePath; + isTupleTypeAnnotation(opts?: object): this is NodePath; + isTypeofTypeAnnotation(opts?: object): this is NodePath; + isTypeAlias(opts?: object): this is NodePath; + isTypeAnnotation(opts?: object): this is NodePath; + isTypeCastExpression(opts?: object): this is NodePath; + isTypeParameterDeclaration(opts?: object): this is NodePath; + isTypeParameterInstantiation(opts?: object): this is NodePath; + isObjectTypeAnnotation(opts?: object): this is NodePath; + isObjectTypeCallProperty(opts?: object): this is NodePath; + isObjectTypeIndexer(opts?: object): this is NodePath; + isObjectTypeProperty(opts?: object): this is NodePath; + isQualifiedTypeIdentifier(opts?: object): this is NodePath; + isUnionTypeAnnotation(opts?: object): this is NodePath; + isVoidTypeAnnotation(opts?: object): this is NodePath; + isJSXAttribute(opts?: object): this is NodePath; + isJSXClosingElement(opts?: object): this is NodePath; + isJSXElement(opts?: object): this is NodePath; + isJSXEmptyExpression(opts?: object): this is NodePath; + isJSXExpressionContainer(opts?: object): this is NodePath; + isJSXIdentifier(opts?: object): this is NodePath; + isJSXMemberExpression(opts?: object): this is NodePath; + isJSXNamespacedName(opts?: object): this is NodePath; + isJSXOpeningElement(opts?: object): this is NodePath; + isJSXSpreadAttribute(opts?: object): this is NodePath; + isJSXText(opts?: object): this is NodePath; + isNoop(opts?: object): this is NodePath; + isParenthesizedExpression(opts?: object): this is NodePath; + isAwaitExpression(opts?: object): this is NodePath; + isBindExpression(opts?: object): this is NodePath; + isDecorator(opts?: object): this is NodePath; + isDoExpression(opts?: object): this is NodePath; + isExportDefaultSpecifier(opts?: object): this is NodePath; + isExportNamespaceSpecifier(opts?: object): this is NodePath; + isRestProperty(opts?: object): this is NodePath; + isSpreadProperty(opts?: object): this is NodePath; + isExpression(opts?: object): this is NodePath; + isBinary(opts?: object): this is NodePath; + isScopable(opts?: object): this is NodePath; + isBlockParent(opts?: object): this is NodePath; + isBlock(opts?: object): this is NodePath; + isStatement(opts?: object): this is NodePath; + isTerminatorless(opts?: object): this is NodePath; + isCompletionStatement(opts?: object): this is NodePath; + isConditional(opts?: object): this is NodePath; + isLoop(opts?: object): this is NodePath; + isWhile(opts?: object): this is NodePath; + isExpressionWrapper(opts?: object): this is NodePath; + isFor(opts?: object): this is NodePath; + isForXStatement(opts?: object): this is NodePath; + isFunction(opts?: object): this is NodePath; + isFunctionParent(opts?: object): this is NodePath; + isPureish(opts?: object): this is NodePath; + isDeclaration(opts?: object): this is NodePath; + isLVal(opts?: object): this is NodePath; + isLiteral(opts?: object): this is NodePath; + isImmutable(opts?: object): this is NodePath; + isUserWhitespacable(opts?: object): this is NodePath; + isMethod(opts?: object): this is NodePath; + isObjectMember(opts?: object): this is NodePath; + isProperty(opts?: object): this is NodePath; + isUnaryLike(opts?: object): this is NodePath; + isPattern(opts?: object): this is NodePath; + isClass(opts?: object): this is NodePath; + isModuleDeclaration(opts?: object): this is NodePath; + isExportDeclaration(opts?: object): this is NodePath; + isModuleSpecifier(opts?: object): this is NodePath; + isFlow(opts?: object): this is NodePath; + isFlowBaseAnnotation(opts?: object): this is NodePath; + isFlowDeclaration(opts?: object): this is NodePath; + isJSX(opts?: object): this is NodePath; + isNumberLiteral(opts?: object): this is NodePath; + isRegexLiteral(opts?: object): this is NodePath; + isReferencedIdentifier(opts?: object): this is NodePath; + isReferencedMemberExpression(opts?: object): this is NodePath; + isBindingIdentifier(opts?: object): this is NodePath; + isScope(opts?: object): this is NodePath; isReferenced(opts?: object): boolean; - isBlockScoped(opts?: object): boolean; - isVar(opts?: object): boolean; + isBlockScoped(opts?: object): this is NodePath; + isVar(opts?: object): this is NodePath; isUser(opts?: object): boolean; isGenerated(opts?: object): boolean; isPure(opts?: object): boolean; diff --git a/types/babel-types/index.d.ts b/types/babel-types/index.d.ts index 1879c81e85..a49909ed4a 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -1265,13 +1265,13 @@ 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 isReferencedIdentifier(node: object, opts?: object): node is Identifier | JSXIdentifier; +export function isReferencedMemberExpression(node: object, opts?: object): node is MemberExpression; +export function isBindingIdentifier(node: object, opts?: object): node is Identifier; +export function isScope(node: object, opts?: object): node is Scopable; 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 isBlockScoped(node: object, opts?: object): node is FunctionDeclaration | ClassDeclaration | VariableDeclaration; +export function isVar(node: object, opts?: object): node is VariableDeclaration; export function isUser(node: object, opts?: object): boolean; export function isGenerated(node: object, opts?: object): boolean; export function isPure(node: object, opts?: object): boolean; diff --git a/types/backbone/backbone-tests.ts b/types/backbone/backbone-tests.ts index 1772ec5b89..7b6fad9b56 100644 --- a/types/backbone/backbone-tests.ts +++ b/types/backbone/backbone-tests.ts @@ -159,6 +159,9 @@ function test_collection() { var book1: Book = new Book({ title: "Title 1", author: "Mike" }); books.add(book1); + // Test adding sort option to add. + books.add(new Book(), { sort: true }); + // Objects can be added to collection by casting to model type. // Compiler will check if object properties are valid for the cast. // This gives better type checking than declaring an `any` overload. @@ -190,6 +193,7 @@ function test_collection() { let modelsDict: _.Dictionary; let num: number; + models = books.slice(); models = books.slice(1); models = books.slice(1, 3); @@ -405,6 +409,12 @@ namespace v1Changes { validate: false }); } + + function test_set() { + var collection = new EmployeeCollection(); + var model = new Employee(); + collection.set([model], { add: false, remove: true, merge: false }); + } } namespace Router { @@ -415,4 +425,10 @@ namespace v1Changes { router.navigate('/employees', true); } } + + namespace Sync { + // Test for Backbone.sync override. + Backbone.sync('create', new Employee()); + Backbone.sync('read', new EmployeeCollection()); + } } diff --git a/types/backbone/index.d.ts b/types/backbone/index.d.ts index 04f3024e98..1a186d9924 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -16,6 +16,13 @@ declare namespace Backbone { interface AddOptions extends Silenceable { at?: number; merge?: boolean; + sort?: boolean; + } + + interface CollectionSetOptions extends Silenceable { + add?: boolean; + remove?: boolean; + merge?: boolean; } interface HistoryOptions extends Silenceable { @@ -243,7 +250,19 @@ declare namespace Backbone { remove(model: {}|TModel, options?: Silenceable): TModel; remove(models: ({}|TModel)[], options?: Silenceable): TModel[]; reset(models?: TModel[], options?: Silenceable): TModel[]; - set(models?: TModel[], options?: Silenceable): TModel[]; + + /** + * + * The set method performs a "smart" update of the collection with the passed list of models. + * If a model in the list isn't yet in the collection it will be added; if the model is already in the + * collection its attributes will be merged; and if the collection contains any models that aren't present + * in the list, they'll be removed. All of the appropriate "add", "remove", and "change" events are fired as + * this happens. Returns the touched models in the collection. If you'd like to customize the behavior, you can + * disable it with options: {add: false}, {remove: false}, or {merge: false}. + * @param models + * @param options + */ + set(models?: TModel[], options?: CollectionSetOptions): TModel[]; shift(options?: Silenceable): TModel; sort(options?: Silenceable): Collection; unshift(model: TModel, options?: AddOptions): TModel; @@ -259,7 +278,7 @@ declare namespace Backbone { /** * Return a shallow copy of this collection's models, using the same options as native Array#slice. */ - slice(min: number, max?: number): TModel[]; + slice(min?: number, max?: number): TModel[]; // mixins from underscore @@ -441,7 +460,7 @@ declare namespace Backbone { } // SYNC - function sync(method: string, model: Model, options?: JQueryAjaxSettings): any; + function sync(method: string, model: Model | Collection, options?: JQueryAjaxSettings): any; function ajax(options?: JQueryAjaxSettings): JQueryXHR; var emulateHTTP: boolean; var emulateJSON: boolean; diff --git a/types/baconjs/baconjs-tests.ts b/types/baconjs/baconjs-tests.ts index d39a4fd466..2755bec595 100644 --- a/types/baconjs/baconjs-tests.ts +++ b/types/baconjs/baconjs-tests.ts @@ -188,10 +188,10 @@ function CommonMethodsInEventStreamsAndProperties() { return adds.takeUntil(cancel).map(x => x.val); }; - Bacon.sequentially(2, events) + Bacon.sequentially(2, events) .groupBy(keyF, limitF) .flatMap(groupedStream => groupedStream.fold(0, (acc, x) => acc + x)) - .onValue(sum => { + .onValue((sum: number) => { console.log(sum); // returns [-1, 2, 8] in an order }); } diff --git a/types/bash-glob/bash-glob-tests.ts b/types/bash-glob/bash-glob-tests.ts new file mode 100644 index 0000000000..cf63412653 --- /dev/null +++ b/types/bash-glob/bash-glob-tests.ts @@ -0,0 +1,21 @@ +import bashGlob = require('bash-glob'); + +bashGlob('pattern', (err, files) => {}); +bashGlob(['pattern'], (err, files) => {}); +bashGlob(['pattern'], {}, (err, files) => {}); +bashGlob(['pattern'], { cwd: 'cwd' }, (err, files) => { }); + +bashGlob.on('match', (match, cwd) => {}); +bashGlob.on('files', (files, cwd) => {}); +bashGlob.on('end', (files) => {}); + +bashGlob.each('pattern', (err, files) => {}); +bashGlob.each(['pattern'], (err, files) => {}); +bashGlob.each(['pattern'], {}, (err, files) => {}); +bashGlob.each(['pattern'], { cwd: 'cwd' }, (err, files) => {}); + +// $ExpectType string[] +bashGlob.sync('pattern'); +bashGlob.sync(['pattern']); +bashGlob.sync(['pattern'], {}); +bashGlob.sync(['pattern'], { cwd: 'cwd' }); diff --git a/types/bash-glob/index.d.ts b/types/bash-glob/index.d.ts new file mode 100644 index 0000000000..29582ea9bd --- /dev/null +++ b/types/bash-glob/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for bash-glob 2.0 +// Project: https://github.com/micromatch/bash-glob +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type Patterns = string | string[]; +type Callback = (err: Error, files: string[]) => void; + +declare function bashGlob(pattern: Patterns, callback: Callback): void; +declare function bashGlob(pattern: Patterns, options: bashGlob.Options, callback: Callback): void; + +declare namespace bashGlob { + interface Options { + cwd?: string; + dot?: boolean; + dotglob?: boolean; + extglob?: boolean; + failglob?: boolean; + globstar?: boolean; + nocase?: boolean; + nocaseglob?: boolean; + nullglob?: boolean; + } + + function on(event: 'match' | 'files', callback: (files: string, cwd: string) => void): void; + function on(event: 'end', callback: (files: string) => void): void; + + function each(patterns: Patterns, callback: Callback): void; + function each(patterns: Patterns, options: Options, callback: Callback): void; + + function promise(patterns: Patterns, options?: Options): Promise; + + function sync(patterns: Patterns, options?: Options): string[]; +} + +export = bashGlob; diff --git a/types/bash-glob/tsconfig.json b/types/bash-glob/tsconfig.json new file mode 100644 index 0000000000..6a45a2d74d --- /dev/null +++ b/types/bash-glob/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bash-glob-tests.ts" + ] +} diff --git a/types/bash-glob/tslint.json b/types/bash-glob/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bash-glob/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/beats/beats-tests.ts b/types/beats/beats-tests.ts new file mode 100644 index 0000000000..00659af2e5 --- /dev/null +++ b/types/beats/beats-tests.ts @@ -0,0 +1,11 @@ +import beats = require('beats'); + +const bins: beats.Bin[] = [ + { lo: 0, hi: 512, threshold: 0, decay: 0.005 }, + { lo: 512, hi: 1024, threshold: 0, decay: 0.005 }, +]; + +const detect = beats(bins, 1); + +const frequencies = new Uint8Array(1024); +const result = detect(frequencies); diff --git a/types/beats/index.d.ts b/types/beats/index.d.ts new file mode 100644 index 0000000000..e95f008c1f --- /dev/null +++ b/types/beats/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for beats 0.0 +// Project: https://github.com/hughsk/beats/ +// Definitions by: Uri Shaked +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = beats; + +declare function beats(bins: ReadonlyArray, minSeparation?: number): (frequencies: Uint8Array | Float32Array | ReadonlyArray, dt?: number) => Float32Array; + +declare namespace beats { + interface Bin { + lo: number; + hi: number; + threshold: number; + decay: number; + } +} diff --git a/types/beats/tsconfig.json b/types/beats/tsconfig.json new file mode 100644 index 0000000000..89bd0b5995 --- /dev/null +++ b/types/beats/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "beats-tests.ts" + ] +} diff --git a/types/beats/tslint.json b/types/beats/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/beats/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/benchmark/benchmark-tests.ts b/types/benchmark/benchmark-tests.ts index 8fbe2b1d92..cb02940b37 100644 --- a/types/benchmark/benchmark-tests.ts +++ b/types/benchmark/benchmark-tests.ts @@ -229,6 +229,27 @@ suite.add({ 'onComplete': onComplete }); +// unregister a listener for an event type +suite.off('cycle', listener) as Benchmark.Suite; + +// unregister a listener for multiple event types +suite.off('start cycle', listener) as Benchmark.Suite; + +// unregister all listeners for an event type +suite.off('cycle') as Benchmark.Suite; + +// unregister all listeners for multiple event types +suite.off('start cycle complete') as Benchmark.Suite; + +// unregister all listeners for all event types +suite.off() as Benchmark.Suite; + +// register a listener for an event type +suite.on('cycle', listener) as Benchmark.Suite; + +// register a listener for multiple event types +suite.on('start cycle', listener) as Benchmark.Suite; + // basic usage suite.run(); diff --git a/types/benchmark/index.d.ts b/types/benchmark/index.d.ts index 01bb379a48..d8c72aef68 100644 --- a/types/benchmark/index.d.ts +++ b/types/benchmark/index.d.ts @@ -170,10 +170,10 @@ declare namespace Benchmark { join(separator?: string): string; listeners(type: string): Function[]; map(callback: Function): any[]; - off(type?: string, callback?: Function): Benchmark; - off(types: string[]): Benchmark; - on(type?: string, callback?: Function): Benchmark; - on(types: string[]): Benchmark; + off(type?: string, callback?: Function): Suite; + off(types: string[]): Suite; + on(type?: string, callback?: Function): Suite; + on(types: string[]): Suite; pluck(property: string): any[]; pop(): Function; push(benchmark: Benchmark): number; diff --git a/types/blessed/blessed-tests.ts b/types/blessed/blessed-tests.ts index b143703b18..c5f857146f 100644 --- a/types/blessed/blessed-tests.ts +++ b/types/blessed/blessed-tests.ts @@ -1,150 +1,138 @@ -import * as blessed from 'blessed' +import * as blessed from "blessed"; +import { readFileSync } from "fs"; let screen: blessed.Widgets.Screen = null; // https://github.com/chjj/blessed/blob/master/test/widget-autopad.js screen = blessed.screen({ - dump: __dirname + '/logs/autopad.log', + dump: __dirname + "/logs/autopad.log", smartCSR: true, autoPadding: true, warnings: true }); -var box1 = blessed.box({ +const box1 = blessed.box({ parent: screen, - top: 'center', - left: 'center', + top: "center", + left: "center", width: 20, height: 10, - border: 'line' + border: "line" }); -var box2 = blessed.box({ +const box2 = blessed.box({ parent: box1, top: 0, left: 0, width: 10, height: 5, - border: 'line' + border: "line" }); -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); screen.render(); // https://github.com/chjj/blessed/blob/master/test/widget-bigtext.js screen = blessed.screen({ - dump: __dirname + '/logs/bigtext.log', + dump: __dirname + "/logs/bigtext.log", smartCSR: true, warnings: true }); -var box = blessed.bigtext({ +const box3 = blessed.bigtext({ parent: screen, - content: 'Hello', + content: "Hello", shrink: true, - width: '80%', + width: "80%", // height: '80%', - height: 'shrink', + height: "shrink", // width: 'shrink', - border: 'line', - fch: ' ', - ch: '\u2592', + border: "line", + fch: " ", + ch: "\u2592", style: { - fg: 'red', - bg: 'blue', + fg: "red", + bg: "blue", bold: false } }); -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); screen.render(); // https://github.com/chjj/blessed/blob/master/test/widget-csr.js screen = blessed.screen({ - dump: __dirname + '/logs/csr.log', + dump: __dirname + "/logs/csr.log", smartCSR: true, warnings: true }); +const lorem = readFileSync(__dirname + "/git.diff", "utf8"); -var lorem = require('fs').readFileSync(__dirname + '/git.diff', 'utf8'); - -var cleanSides = screen.cleanSides; +const cleanSides = screen.cleanSides; function expectClean(value: any) { - screen.cleanSides = function(el: blessed.widget.Element) { - var ret = cleanSides.apply(this, arguments); + screen.cleanSides = function(el: blessed.Widgets.BlessedElement) { + const ret = cleanSides.apply(this, arguments); if (ret !== value) { - throw new Error('Failed. Expected ' - + value + ' from cleanSides. Got ' - + ret + '.'); + throw new Error(`Failed. Expected ${value} from cleanSides. Got ${ret}.`); } return ret; }; } -var btext = blessed.box({ +const btext = blessed.box({ parent: screen, - left: 'center', - top: 'center', - width: '80%', - height: '80%', + left: "center", + top: "center", + width: "80%", + height: "80%", style: { - bg: 'green' + bg: "green" }, - border: 'line', - content: 'CSR should still work.' + border: "line", + content: "CSR should still work." }); -let _oscroll = btext.scroll; -btext.scroll = function(offset, always) { +btext.scroll = (offset, always) => { expectClean(true); - return _oscroll(offset, always); }; -var text = blessed.scrollabletext({ +const text = blessed.scrollabletext({ parent: screen, content: lorem, - border: 'line', - left: 'center', - top: 'center', + border: "line", + left: "center", + top: "center", draggable: true, - width: '50%', - height: '50%', + width: "50%", + height: "50%", mouse: true, keys: true, vi: true }); -_oscroll = text.scroll; text.scroll = function(offset, always) { - var el = this; - var value = true; + const el = this; + let value = true; if (el.left < 0) value = true; if (el.top < 0) value = false; if (el.left + el.width > screen.width) value = true; if (el.top + el.height > screen.height) value = false; expectClean(value); - return _oscroll(offset, always); }; text.focus(); -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); screen.render(); // https://github.com/chjj/blessed/blob/master/test/widget-dock-noborder.js screen = blessed.screen({ - dump: __dirname + '/logs/dock.log', + dump: __dirname + "/logs/dock.log", smartCSR: true, dockBorders: true, warnings: true @@ -154,85 +142,85 @@ blessed.box({ parent: screen, left: -1, top: -1, - width: '50%+1', - height: '50%+1', - border: 'line', - content: 'Foo' + width: "50%+1", + height: "50%+1", + border: "line", + content: "Foo" }); blessed.box({ parent: screen, - left: '50%-1', + left: "50%-1", top: -1, - width: '50%+3', - height: '50%+1', - content: 'Bar', - border: 'line' + width: "50%+3", + height: "50%+1", + content: "Bar", + border: "line" }); blessed.box({ parent: screen, left: -1, - top: '50%-1', - width: '50%+1', - height: '50%+3', - border: 'line', - content: 'Foo' + top: "50%-1", + width: "50%+1", + height: "50%+3", + border: "line", + content: "Foo" }); -blessed.listtable({ - parent: screen, - left: '50%-1', - top: '50%-1', - width: '50%+3', - height: '50%+3', - border: 'line', - align: 'center', - tags: true, - keys: true, - vi: true, - mouse: true, - style: { - header: { - fg: 'blue', - bold: true - }, - cell: { - fg: 'magenta', - selected: { - bg: 'blue' +blessed + .listtable({ + parent: screen, + left: "50%-1", + top: "50%-1", + width: "50%+3", + height: "50%+3", + border: "line", + align: "center", + tags: true, + keys: true, + vi: true, + mouse: true, + style: { + header: { + fg: "blue", + bold: true + }, + cell: { + fg: "magenta", + selected: { + bg: "blue" + } } - } - }, - data: [ - [ 'Animals', 'Foods', 'Times', 'Numbers' ], - [ 'Elephant', 'Apple', '1:00am', 'One' ], - [ 'Bird', 'Orange', '2:15pm', 'Two' ], - [ 'T-Rex', 'Taco', '8:45am', 'Three' ], - [ 'Mouse', 'Cheese', '9:05am', 'Four' ] - ] -}).focus(); + }, + data: [ + ["Animals", "Foods", "Times", "Numbers"], + ["Elephant", "Apple", "1:00am", "One"], + ["Bird", "Orange", "2:15pm", "Two"], + ["T-Rex", "Taco", "8:45am", "Three"], + ["Mouse", "Cheese", "9:05am", "Four"] + ] + }) + .focus(); -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); screen.render(); // https://raw.githubusercontent.com/chjj/blessed/master/example/simple-form.js -var form = blessed.form({ +const form = blessed.form({ parent: screen, keys: true, left: 0, top: 0, width: 30, height: 4, - bg: 'green', - content: 'Submit or cancel?' + bg: "green", + content: "Submit or cancel?" }); -var submit = blessed.button({ +const submit = blessed.button({ parent: form, mouse: true, keys: true, @@ -243,20 +231,20 @@ var submit = blessed.button({ left: 10, top: 2, shrink: true, - name: 'submit', - content: 'submit', + name: "submit", + content: "submit", style: { - bg: 'blue', + bg: "blue", focus: { - bg: 'red' + bg: "red" }, hover: { - bg: 'red' + bg: "red" } } }); -var cancel = blessed.button({ +const cancel = blessed.button({ parent: form, mouse: true, keys: true, @@ -267,15 +255,15 @@ var cancel = blessed.button({ left: 20, top: 2, shrink: true, - name: 'cancel', - content: 'cancel', + name: "cancel", + content: "cancel", style: { - bg: 'blue', + bg: "blue", focus: { - bg: 'red' + bg: "red" }, hover: { - bg: 'red' + bg: "red" } } }); @@ -283,314 +271,306 @@ var cancel = blessed.button({ // https://github.com/chjj/blessed/blob/master/test/widget-layout.js screen = blessed.screen({ - dump: __dirname + '/logs/layout.log', + dump: __dirname + "/logs/layout.log", smartCSR: true, autoPadding: true, warnings: true }); -var layout = blessed.layout({ +const layout = blessed.layout({ parent: screen, - top: 'center', - left: 'center', - width: '50%', - height: '50%', - border: 'line', - layout: process.argv[2] === 'grid' ? 'grid' : 'inline', + top: "center", + left: "center", + width: "50%", + height: "50%", + border: "line", + layout: process.argv[2] === "grid" ? "grid" : "inline", style: { - bg: 'red', + bg: "red", border: { - fg: 'blue' + fg: "blue" } } }); -var box1 = blessed.box({ +blessed.box({ parent: layout, - top: 'center', - left: 'center', + top: "center", + left: "center", width: 20, height: 10, - border: 'line', - content: '1' + border: "line", + content: "1" }); -var box2 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '2' + border: "line", + content: "2" }); -var box3 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '3' + border: "line", + content: "3" }); -var box4 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '4' + border: "line", + content: "4" }); -var box5 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '5' + border: "line", + content: "5" }); -var box6 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '6' + border: "line", + content: "6" }); -var box7 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '7' + border: "line", + content: "7" }); -var box8 = blessed.box({ +blessed.box({ parent: layout, - top: 'center', - left: 'center', + top: "center", + left: "center", width: 20, height: 10, - border: 'line', - content: '8' + border: "line", + content: "8" }); -var box9 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '9' + border: "line", + content: "9" }); -var box10 = blessed.box({ +blessed.box({ parent: layout, - top: 'center', - left: 'center', + top: "center", + left: "center", width: 20, height: 10, - border: 'line', - content: '10' + border: "line", + content: "10" }); -var box11 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '11' + border: "line", + content: "11" }); -var box12 = blessed.box({ +const box12 = blessed.box({ parent: layout, - top: 'center', - left: 'center', + top: "center", + left: "center", width: 20, height: 10, - border: 'line', - content: '12' + border: "line", + content: "12" }); -if (process.argv[2] !== 'grid') { - for (var i = 0; i < 10; i++) { +if (process.argv[2] !== "grid") { + for (let i = 0; i < 10; i++) { blessed.box({ parent: layout, // width: i % 2 === 0 ? 10 : 20, // height: i % 2 === 0 ? 5 : 10, width: Math.random() > 0.5 ? 10 : 20, height: Math.random() > 0.5 ? 5 : 10, - border: 'line', - content: (i + 1 + 12) + '' + border: "line", + content: String(i + 1 + 12) }); } } -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); screen.render(); // https://github.com/chjj/blessed/blob/master/test/widget-form.js screen = blessed.screen({ - dump: __dirname + '/logs/form.log', + dump: __dirname + "/logs/form.log", warnings: true }); -type FormData = { - radio1: boolean; - radio2: boolean; - text: string; - check: boolean; -}; +interface FormData { + radio1: boolean; + radio2: boolean; + text: string; + check: boolean; +} -var form2 = blessed.form({ +const form2 = blessed.form({ parent: screen, mouse: true, keys: true, vi: true, left: 0, top: 0, - width: '100%', - //height: 12, + width: "100%", style: { - bg: 'green', + bg: "green", border: { - inverse: true + inverse: true }, scrollbar: { inverse: true } }, - content: 'foobar', + content: "foobar", scrollable: true, scrollbar: { - ch: ' ' + ch: " " } - //alwaysScroll: true }); -form2.on('submit', (data) => { +form2.on("submit", data => { output.setContent(JSON.stringify(data, null, 2)); screen.render(); }); -form2.key('d', function() { +form2.key("d", () => { form2.scroll(1, true); screen.render(); }); -form2.key('u', function() { +form2.key("u", () => { form2.scroll(-1, true); screen.render(); }); -var set = blessed.radioset({ +const set = blessed.radioset({ parent: form2, left: 1, top: 1, shrink: true, - //padding: 1, - //content: 'f', style: { - bg: 'magenta' + bg: "magenta" } }); -var radio1 = blessed.radiobutton({ +const radio1 = blessed.radiobutton({ parent: set, mouse: true, keys: true, shrink: true, style: { - bg: 'magenta' + bg: "magenta" }, height: 1, left: 0, top: 0, - name: 'radio1', - content: 'radio1' + name: "radio1", + content: "radio1" }); -var radio2 = blessed.radiobutton({ +const radio2 = blessed.radiobutton({ parent: set, mouse: true, keys: true, shrink: true, style: { - bg: 'magenta' + bg: "magenta" }, height: 1, left: 15, top: 0, - name: 'radio2', - content: 'radio2' + name: "radio2", + content: "radio2" }); -var text2 = blessed.textbox({ +const text2 = blessed.textbox({ parent: form2, mouse: true, keys: true, style: { - bg: 'blue' + bg: "blue" }, height: 1, width: 20, left: 1, top: 3, - name: 'text' + name: "text" }); -text2.on('focus', function() { - text2.readInput(); -}); +text2.on("focus", () => text2.readInput()); -var check = blessed.checkbox({ +const check = blessed.checkbox({ parent: form2, mouse: true, keys: true, shrink: true, style: { - bg: 'magenta' + bg: "magenta" }, height: 1, left: 28, top: 1, - name: 'check', - content: 'check' + name: "check", + content: "check" }); -var check2 = blessed.checkbox({ +const check2 = blessed.checkbox({ parent: form2, mouse: true, keys: true, shrink: true, style: { - bg: 'magenta' + bg: "magenta" }, height: 1, left: 28, top: 14, - name: 'foooooooo2', - content: 'foooooooo2' + name: "foooooooo2", + content: "foooooooo2" }); -var submit = blessed.button({ +const submit2 = blessed.button({ parent: form2, mouse: true, keys: true, @@ -601,69 +581,67 @@ var submit = blessed.button({ }, left: 29, top: 3, - name: 'submit', - content: 'submit', + name: "submit", + content: "submit", style: { - bg: 'blue', + bg: "blue", focus: { - bg: 'red' + bg: "red" } } }); -submit.on('press', function() { - form2.submit(); -}); +submit.on("press", () => form2.submit()); -var box1 = blessed.box({ +const box5 = blessed.box({ parent: form2, left: 1, top: 10, height: 10, width: 10, - content: 'one', + content: "one", style: { - bg: 'cyan' + bg: "cyan" } }); -var box2 = blessed.box({ - parent: box1, +const box6 = blessed.box({ + parent: box5, left: 1, top: 2, height: 8, width: 9, - content: 'two', + content: "two", style: { - bg: 'magenta' + bg: "magenta" } }); -var box3 = blessed.box({ - parent: box2, +const box7 = blessed.box({ + parent: box6, left: 1, top: 2, height: 6, width: 8, - content: 'three', + content: "three", style: { - bg: 'yellow' + bg: "yellow" } }); -var box4 = blessed.box({ - parent: box3, +blessed.box({ + parent: box7, left: 1, top: 2, height: 4, width: 7, - content: 'four', + content: "four", style: { - bg: 'blue' + bg: "blue" } }); -var output = blessed.scrollabletext({ +const output = blessed.scrollabletext({ parent: form2, mouse: true, keys: true, @@ -672,26 +650,24 @@ var output = blessed.scrollabletext({ height: 5, right: 0, style: { - bg: 'red' + bg: "red" }, - content: 'foobar' + content: "foobar" }); -var bottom = blessed.line({ +const bottom = blessed.line({ parent: form2, - type: 'line', - orientation: 'horizontal', + type: "line", + orientation: "horizontal", left: 0, right: 0, top: 50, style: { - fg: 'blue' + fg: "blue" } }); -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); form2.focus(); @@ -702,70 +678,68 @@ screen.render(); // https://github.com/chjj/blessed/blob/master/test/widget-table.js screen = blessed.screen({ - dump: __dirname + '/logs/table.log', + dump: __dirname + "/logs/table.log", autoPadding: false, fullUnicode: true, warnings: true }); -var DU = '杜'; -var JUAN = '鹃'; +const DU = "杜"; +const JUAN = "鹃"; -var table = blessed.table({ - //parent: screen, - top: 'center', - left: 'center', +const table = blessed.table({ + // parent: screen, + top: "center", + left: "center", data: null, - border: 'line', - align: 'center', + border: "line", + align: "center", tags: true, - //width: '80%', - width: 'shrink', + // width: '80%', + width: "shrink", style: { border: { - fg: 'red' + fg: "red" }, header: { - fg: 'blue', + fg: "blue", bold: true }, cell: { - fg: 'magenta' + fg: "magenta" } } }); -var data1 = [ - [ 'Animals', 'Foods', 'Times' ], - [ 'Elephant', 'Apple', '1:00am' ], - [ 'Bird', 'Orange', '2:15pm' ], - [ 'T-Rex', 'Taco', '8:45am' ], - [ 'Mouse', 'Cheese', '9:05am' ] +const data1 = [ + ["Animals", "Foods", "Times"], + ["Elephant", "Apple", "1:00am"], + ["Bird", "Orange", "2:15pm"], + ["T-Rex", "Taco", "8:45am"], + ["Mouse", "Cheese", "9:05am"] ]; -data1[1][0] = '{red-fg}' + data1[1][0] + '{/red-fg}'; -data1[2][0] += ' (' + DU + JUAN + ')'; +data1[1][0] = `{red-fg} ${data1[1][0]} {/red-fg}`; +data1[2][0] += ` (${DU}${JUAN})`; -var data2 = [ - [ 'Animals', 'Foods', 'Times', 'Numbers' ], - [ 'Elephant', 'Apple', '1:00am', 'One' ], - [ 'Bird', 'Orange', '2:15pm', 'Two' ], - [ 'T-Rex', 'Taco', '8:45am', 'Three' ], - [ 'Mouse', 'Cheese', '9:05am', 'Four' ] +const data2 = [ + ["Animals", "Foods", "Times", "Numbers"], + ["Elephant", "Apple", "1:00am", "One"], + ["Bird", "Orange", "2:15pm", "Two"], + ["T-Rex", "Taco", "8:45am", "Three"], + ["Mouse", "Cheese", "9:05am", "Four"] ]; -data2[1][0] = '{red-fg}' + data2[1][0] + '{/red-fg}'; -data2[2][0] += ' (' + DU + JUAN + ')'; +data2[1][0] = `{red-fg} ${data2[1][0]} {/red-fg}`; +data2[2][0] += ` (${DU}${JUAN})`; -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); table.setData(data2); screen.append(table); screen.render(); -setTimeout(function() { +setTimeout(() => { table.setData(data1); screen.render(); }, 3000); diff --git a/types/blessed/index.d.ts b/types/blessed/index.d.ts index 553942af2f..9098648240 100644 --- a/types/blessed/index.d.ts +++ b/types/blessed/index.d.ts @@ -1,2837 +1,3033 @@ -// Type definitions for blessed 0.1.6 +// Type definitions for blessed 0.1 // Project: https://github.com/chjj/blessed -// Definitions by: bryn austin bellomy +// Definitions by: Bryn Austin Bellomy , Steve Kellock // Definitions: https://github.com/borisyankov/DefinitelyTyped +// TypeScript Version: 2.1 -/// +/// -import { EventEmitter } from 'events'; +import { EventEmitter } from "events"; import * as stream from "stream"; import * as child_process from "child_process"; -declare namespace Blessed { - export class BlessedProgram { - hideCursor: () => void; - move: any; - showCursor: any; - } +export class BlessedProgram { + hideCursor: () => void; + move: any; + showCursor: any; +} - export module Widgets { +export namespace Widgets { + namespace Types { + type TTopLeft = string | number | "center"; - export module Types { + type TPosition = string | number; - export type TTopLeft = string | number | "center"; + type TMouseAction = "mousedown" | "mouseup" | "mousemove"; - export type TPosition = string | number; - - export type TMouseAction = "mousedown" | "mouseup" | "mousemove"; - - export type TStyle = { - type?: string; - bg?: string; - fg?: string; - ch?: string; - bold?: boolean; - underline?: boolean; - blink?: boolean; - inverse?: boolean; - invisible?: boolean; - transparent?: boolean; - border?: "line" | "bg" | TBorder; - hover?: boolean; - focus?: boolean; - label?: string; - track?: {bg?: string; fg?: string;}; - scrollbar?: {bg?: string; fg?: string;}; - } - - export type TBorder = { - /** - * Type of border (line or bg). bg by default. - */ - type?: "line" | "bg"; - /** - * Character to use if bg type, default is space. - */ - ch?: string; - /** - * Border foreground and background, must be numbers (-1 for default). - */ - bg?: number; - fg?: number; - /** - * Border attributes. - */ - bold?: string; - underline?: string; - } - - export type TCursor = { - /** - * Have blessed draw a custom cursor and hide the terminal cursor (experimental). - */ - artificial: boolean; - /** - * Shape of the cursor. Can be: block, underline, or line. - */ - shape: 'block'|'underline'|'line'; - /** - * Whether the cursor blinks. - */ - blink: boolean; - /** - * Color of the color. Accepts any valid color value (null is default). - */ - color: string; - } - - export type TAlign = "left" | "center" | "right"; - - export type ListbarCommand = { - key: string; - callback: () => void; - }; - - export type TImage = { - /** - * Pixel width. - */ - width: number; - /** - * Pixel height. - */ - height: number; - /** - * Image bitmap. - * */ - bmp: any; - /** - * Image cellmap (bitmap scaled down to cell size). - */ - cellmap: any; - }; - - export type Cursor = { - /** - * Have blessed draw a custom cursor and hide the terminal cursor (experimental). - */ - artificial: boolean; - /** - * Shape of the cursor. Can be: block, underline, or line. - */ - shape: boolean; - /** - * Whether the cursor blinks. - */ - blink: boolean; - /** - * Color of the color. Accepts any valid color value (null is default). - */ - color: string; - } - } - - export module Events { - - export interface IMouseEventArg { - x: number; - y: number; - action: Types.TMouseAction; - } - - export interface IKeyEventArg { - full: string; - name: string; - shift: boolean; - ctrl: boolean; - meta: boolean; - sequence: string; - } - } - - export interface NodeChildProcessExecOptions { - cwd?: string; - stdio?: any; - customFds?: any; - env?: any; - encoding?: string; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - } - - export interface IDestroyable { - destroy(): void; - } - - export interface IOptions { - } - - export interface IHasOptions { - options: T; - } - - export interface TputsOptions extends IOptions { - terminal?: string; - extended?: boolean; - debug?: boolean; - termcap?: string; - terminfoFile?: string; - terminfoPrefix?: string; - termcapFile?: string; - } - - export class Tput implements IHasOptions { - constructor(opts: TputsOptions); - - // ** properties ** // - - /** - * Original options object. - */ - options: TputsOptions; - - debug: boolean; - padding: boolean; - extended: boolean; - printf: boolean; - termcap: string; - terminfoPrefix: string; - terminfoFile: string; - termcapFile: string; - error: Error; - terminal: string; - - setup(): void; - term(is: any): boolean; - readTerminfo(term: string): string; - parseTerminfo(data: any, file: string): { - header: { - dataSize: number; - headerSize: number; - magicNumber: boolean; - namesSize: number; - boolCount: number; - numCount: number; - strCount: number; - strTableSize: number; - extended: { - dataSize: number; - headerSize: number; - boolCount: number; - numCount: number; - strCount: number; - strTableSize: number; - lastStrTableOffset: number; - } - } - name: string; - names: string[]; - desc: string; - bools: Object; - numbers: Object; - strings: Object; - }; - } - - export interface IDestroyable { - destroy(): void; - } - - export interface INodeOptions extends IOptions { - name?: string; - screen?: Screen; - parent?: Node; - children?: Node[]; - focusable?: boolean; - } - - export abstract class Node extends EventEmitter implements IHasOptions, IDestroyable { - constructor(options: INodeOptions); - - // ** properties ** // - - focusable: boolean; - - /** - * Original options object. - */ - options: INodeOptions; - - /** - * An object for any miscellanous user data. - */ - data: {[index: string]: any;}; - /** - * An object for any miscellanous user data. - */ - _: {[index: string]: any;}; - /** - * An object for any miscellanous user data. - */ - $: {[index: string]: any;}; - /** - * Type of the node (e.g. box). - */ - type: string; - /** - * Render index (document order index) of the last render call. - */ - index: number; - /** - * Parent screen. - */ - screen: Screen; - /** - * Parent node. - */ - parent: Node; - /** - * Array of node's children. - */ - children: Node[]; - - // ** methods ** // - - /** - * Prepend a node to this node's children. - */ - prepend(node: Node): void; - /** - * Append a node to this node's children. - */ - append(node: Node): void; - /** - * Remove child node from node. - */ - remove(node: Node): void; - /** - * Insert a node to this node's children at index i. - */ - insert(node: Node, index: number): void; - /** - * Insert a node to this node's children before the reference node. - */ - insertBefore(node: Node, refNode: Node): void; - /** - * Insert a node from node after the reference node. - */ - insertAfter(node: Node, refNode: Node): void; - /** - * Remove node from its parent. - */ - detach(): void; - /** - * Remove node from its parent. - */ - free(): void; - /** - * Remove node from its parent. - */ - forDescendants(iter: Function, s: any): void; - /** - * Remove node from its parent. - */ - forAncestors(iter: Function, s: any): void; - /** - * Remove node from its parent. - */ - collectDescendants(s: any): void; - /** - * Remove node from its parent. - */ - collectAncestors(s: any): void; - /** - * Remove node from its parent. - */ - emitDescendants(): void; - /** - * Remove node from its parent. - */ - emitAncestors(): void; - /** - * Remove node from its parent. - */ - hasDescendant(target: Node): void; - /** - * Remove node from its parent. - */ - hasAncestor(target: Node): boolean; - /** - * Remove node from its parent. - */ - destroy(): void; - /** - * Emit event for element, and recursively emit same event for all descendants. - */ - emitDescendants(type: string, ...args: any[]): void; - /** - * Get user property with a potential default value. - */ - get(name: string, def: T): T; - /** - * Set user property to value. - */ - set(name: string, value: T): void; - - // ** events ** // - - on(event: string, listener: Function): this; - /** - * Received when node is added to a parent. - */ - on(event: "adopt", callback: (arg: Node) => void): this; - /** - * Received when node is removed from it's current parent. - */ - on(event: "remove", callback: (arg: Node) => void): this; - /** - * Received when node gains a new parent. - */ - on(event: "reparent", callback: (arg: Node) => void): this; - /** - * Received when node is attached to the screen directly or somewhere in its ancestry. - */ - on(event: "attach", callback: (arg: Node) => void): this; - /** - * Received when node is detached from the screen directly or somewhere in its ancestry. - */ - on(event: "detach", callback: (arg: Node) => void): this; - } - - export class NodeWithEvents extends Node { - // ** methods ** // - - /** - * Bind a keypress listener for a specific key. - */ - key(name: string | string[], listener: Function): void; - /** - * Bind a keypress listener for a specific key once. - */ - onceKey(name: string, listener: Function): void; - /** - * Remove a keypress listener for a specific key. - */ - unkey(name: string, listener: Function): void; - removeKey(name: string, listener: Function): void; - - // ** events ** // - - on(event: string, listener: Function): this; - /** - * Received on screen resize. - */ - on(event: "resize", callback: () => void): this; - /** - * Received on mouse events. - */ - on(event: "mouse", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mouseout", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mouseover", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mousedown", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mouseup", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mousewheel", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "wheeldown", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "wheelup", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mousemove", callback: (arg: Events.IMouseEventArg) => void): this; - /** - * Received on key events. - */ - on(event: "keypress", callback: (ch: string, key: Events.IKeyEventArg) => void): this; - /** - * Global events received for all elements. - */ - on(event: "element click", callback: (arg: Screen) => void): this; - on(event: "element mouseover", callback: (arg: Screen) => void): this; - on(event: "element mouseout", callback: (arg: Screen) => void): this; - on(event: "element mouseup", callback: (arg: Screen) => void): this; - /** - * Received on key event for [name]. - */ - //on(event: "key", callback: (arg: BlessedScreen) => void): this; - /** - * Received when the terminal window focuses/blurs. Requires a terminal supporting the - * focus protocol and focus needs to be passed to program.enableMouse(). - */ - on(event: "focus", callback: (arg: Screen) => void): this; - /** - * Received when the terminal window focuses/blurs. Requires a terminal supporting the - * focus protocol and focus needs to be passed to program.enableMouse(). - */ - on(event: "blur", callback: (arg: Screen) => void): this; - /** - * Received before render. - */ - on(event: "prerender", callback: () => void): this; - /** - * Received on render. - */ - on(event: "render", callback: () => void): this; - /** - * Received when blessed notices something untoward (output is not a tty, terminfo not found, etc). - */ - on(event: "warning", callback: (text: string) => void): this; - /** - * Received when the screen is destroyed (only useful when using multiple screens). - */ - on(event: "destroy", callback: () => void): this; - /** - * Received when the element is moved. - */ - on(event: "move", callback: () => void): this; - /** - * Element was clicked (slightly smarter than mouseup). - */ - on(event: "click", callback: (arg: Screen) => void): this; - /** - * Received when element is shown. - */ - on(event: "show", callback: () => void): this; - /** - * Received when element becomes hidden. - */ - on(event: "hide", callback: () => void): this; - - on(event: "set content", callback: () => void): this; - on(event: "parsed content", callback: () => void): this; - } - - export interface IScreenOptions extends INodeOptions { - /** - * The blessed Program to be associated with. Will be automatically instantiated if none is provided. - */ - program?: BlessedProgram; - /** - * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with - * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, - * however, it is more optimal for terminal rendering. - */ - smartCSR?: boolean; - /** - * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, - * but may cause flickering depending on what is on each side of the element. - */ - fastCSR?: boolean; - /** - * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work - * with terminals that don't support it, but only on lines with the default background color. As it - * stands with the current implementation, it's uncertain how much terminal performance this adds at - * the cost of overhead within node. - */ - useBCE?: boolean; - /** - * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). - */ - resizeTimeout?: number; - /** - * The width of tabs within an element's content. - */ - tabSize?: number; - /** - * Automatically position child elements with border and padding in mind (NOTE: this is a recommended - * option. It may become default in the future). - */ - autoPadding?: boolean; - - cursor?: Types.TCursor; - - /** - * Create a log file. See log method. - */ - log?: (...msg: any[]) => void; - /** - * Dump all output and input to desired file. Can be used together with log option if set as a boolean. - */ - dump?: string; - /** - * Debug mode. Enables usage of the debug method. Also creates a debug console which will display when - * pressing F12. It will display all log and debug messages. - */ - debug?: (...msg: string[]) => void; - /** - * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful - * for creating a key that will always exit no matter whether the keys are locked. - */ - ignoreLocked?: boolean; - /** - * Automatically "dock" borders with other elements instead of overlapping, depending on position - * (experimental). For example: These border-overlapped elements: - */ - dockBorders?: boolean; - /** - * Normally, dockable borders will not dock if the colors or attributes are different. This option - * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. - */ - ignoreDockContrast?: boolean; - /** - * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode - * combining characters. This allows you to display text above the basic multilingual plane. This - * is behind an option because it may affect performance slightly negatively. Without this option - * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', - * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply - * removes them from an element's content if iTerm2 is detected). - */ - fullUnicode?: boolean; - /** - * Send focus events after mouse is enabled. - */ - sendFocus?: boolean; - /** - * Display warnings (such as the output not being a TTY, similar to ncurses). - */ - warnings?: boolean; - /** - * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. - * If value is true unicode is forced. If value is false non-unicode is forced (default: null). - */ - forceUnicode?: boolean; - /** - * Input and output streams. process.stdin/process.stdout by default, however, it could be a - * net.Socket if you want to make a program that runs over telnet or something of that nature. - * */ - input?: stream.Writable; - /** - * Input and output streams. process.stdin/process.stdout by default, however, it could be a - * net.Socket if you want to make a program that runs over telnet or something of that nature. - * */ - output?: stream.Readable; - /** - * The blessed Tput object (only available if you passed tput: true to the Program constructor.) - */ - tput?: Tput; - /** - * Top of the focus history stack. - */ - focused?: BlessedElement; - /** - * Width of the screen (same as program.cols). - */ - width?: Types.TPosition; - /** - * Height of the screen (same as program.rows). - */ - height?: Types.TPosition; - /** - * Same as screen.width. - */ - cols?: number; - /** - * Same as screen.height. - */ - rows?: number; - /** - * Relative top offset, always zero. - */ - top?: Types.TTopLeft; - /** - * Relative left offset, always zero. - */ - left?: Types.TTopLeft; - /** - * Relative right offset, always zero. - */ - right?: Types.TPosition; - /** - * Relative bottom offset, always zero. - */ - bottom?: Types.TPosition; - /** - * Absolute top offset, always zero. - */ - atop?: Types.TTopLeft; - /** - * Absolute left offset, always zero. - */ - aleft?: Types.TTopLeft; - /** - * Absolute right offset, always zero. - */ - aright?: Types.TPosition; - /** - * Absolute bottom offset, always zero. - */ - abottom?: Types.TPosition; - /** - * Whether the focused element grabs all keypresses. - */ - grabKeys?: any; - /** - * Prevent keypresses from being received by any element. - */ - lockKeys?: boolean; - /** - * The currently hovered element. Only set if mouse events are bound. - */ - hover?: any; - /** - * Set or get terminal name. Set calls screen.setTerminal() internally. - */ - terminal?: string; - /** - * Set or get window title. - */ - title?: string; - } - - export class Screen extends NodeWithEvents implements IHasOptions { - constructor(opts: IScreenOptions); - - // ** properties ** // - cleanSides: any; - - /** - * Original options object. - */ - options: IScreenOptions; - - /** - * The blessed Program to be associated with. Will be automatically instantiated if none is provided. - */ - program: BlessedProgram; - /** - * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with - * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, - * however, it is more optimal for terminal rendering. - */ - smartCSR: boolean; - /** - * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, - * but may cause flickering depending on what is on each side of the element. - */ - fastCSR: boolean; - /** - * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work - * with terminals that don't support it, but only on lines with the default background color. As it - * stands with the current implementation, it's uncertain how much terminal performance this adds at - * the cost of overhead within node. - */ - useBCE: boolean; - /** - * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). - */ - resizeTimeout: number; - /** - * The width of tabs within an element's content. - */ - tabSize: number; - /** - * Automatically position child elements with border and padding in mind (NOTE: this is a recommended - * option. It may become default in the future). - */ - autoPadding: boolean; - - cursor: Types.TCursor; - - /** - * Dump all output and input to desired file. Can be used together with log option if set as a boolean. - */ - dump: string; - /** - * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful - * for creating a key that will always exit no matter whether the keys are locked. - */ - ignoreLocked: boolean; - /** - * Automatically "dock" borders with other elements instead of overlapping, depending on position - * (experimental). For example: These border-overlapped elements: - */ - dockBorders: boolean; - /** - * Normally, dockable borders will not dock if the colors or attributes are different. This option - * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. - */ - ignoreDockContrast: boolean; - /** - * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode - * combining characters. This allows you to display text above the basic multilingual plane. This - * is behind an option because it may affect performance slightly negatively. Without this option - * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', - * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply - * removes them from an element's content if iTerm2 is detected). - */ - fullUnicode: boolean; - /** - * Send focus events after mouse is enabled. - */ - sendFocus: boolean; - /** - * Display warnings (such as the output not being a TTY, similar to ncurses). - */ - warnings: boolean; - /** - * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. - * If value is true unicode is forced. If value is false non-unicode is forced (default: null). - */ - forceUnicode: boolean; - /** - * Input and output streams. process.stdin/process.stdout by default, however, it could be a - * net.Socket if you want to make a program that runs over telnet or something of that nature. - * */ - input: stream.Writable; - /** - * Input and output streams. process.stdin/process.stdout by default, however, it could be a - * net.Socket if you want to make a program that runs over telnet or something of that nature. - * */ - output: stream.Readable; - /** - * The blessed Tput object (only available if you passed tput: true to the Program constructor.) - */ - tput: Tput; - /** - * Top of the focus history stack. - */ - focused: BlessedElement; - /** - * Width of the screen (same as program.cols). - */ - width: Types.TPosition; - /** - * Height of the screen (same as program.rows). - */ - height: Types.TPosition; - /** - * Same as screen.width. - */ - cols: number; - /** - * Same as screen.height. - */ - rows: number; - /** - * Relative top offset, always zero. - */ - top: Types.TTopLeft; - /** - * Relative left offset, always zero. - */ - left: Types.TTopLeft; - /** - * Relative right offset, always zero. - */ - right: Types.TPosition; - /** - * Relative bottom offset, always zero. - */ - bottom: Types.TPosition; - /** - * Absolute top offset, always zero. - */ - atop: Types.TTopLeft; - /** - * Absolute left offset, always zero. - */ - aleft: Types.TTopLeft; - /** - * Absolute right offset, always zero. - */ - aright: Types.TPosition; - /** - * Absolute bottom offset, always zero. - */ - abottom: Types.TPosition; - /** - * Whether the focused element grabs all keypresses. - */ - grabKeys: any; - /** - * Prevent keypresses from being received by any element. - */ - lockKeys: boolean; - /** - * The currently hovered element. Only set if mouse events are bound. - */ - hover: any; - /** - * Set or get terminal name. Set calls screen.setTerminal() internally. - */ - terminal: string; - /** - * Set or get window title. - */ - title: string; - - // ** methods ** // - - /** - * Write string to the log file if one was created. - */ - log(...msg: any[]): void; - /** - * Same as the log method, but only gets called if the debug option was set. - */ - debug(...msg: string[]): void; - /** - * Allocate a new pending screen buffer and a new output screen buffer. - */ - alloc(): void; - /** - * Reallocate the screen buffers and clear the screen. - */ - realloc(): void; - /** - * Draw the screen based on the contents of the screen buffer. - */ - draw(start: number, end: number): void; - /** - * Render all child elements, writing all data to the screen buffer and drawing the screen. - */ - render(): void; - /** - * Clear any region on the screen. - */ - clearRegion(x1: number, x2: number, y1: number, y2: number): void; - /** - * Fill any region with a character of a certain attribute. - */ - fillRegion(attr: string, ch: string, x1: number, x2: number, y1: number, y2: number): void; - /** - * Focus element by offset of focusable elements. - */ - focusOffset(offset: number): any; - /** - * Focus previous element in the index. - */ - focusPrevious(): void; - /** - * Focus next element in the index. - */ - focusNext(): void; - /** - * Push element on the focus stack (equivalent to screen.focused = el). - */ - focusPush(element: BlessedElement): void; - /** - * Pop element off the focus stack. - */ - focusPop(): BlessedElement; - /** - * Save the focused element. - */ - saveFocus(): BlessedElement; - /** - * Restore the saved focused element. - */ - restoreFocus(): BlessedElement; - /** - * "Rewind" focus to the last visible and attached element. - */ - rewindFocus(): BlessedElement; - /** - * Spawn a process in the foreground, return to blessed app after exit. - */ - spawn(file: string, args: string[], options: NodeChildProcessExecOptions): child_process.ChildProcess; - /** - * Spawn a process in the foreground, return to blessed app after exit. Executes callback on error or exit. - */ - exec(file: string, args: string[], options: NodeChildProcessExecOptions, callback: Function): child_process.ChildProcess; - /** - * Read data from text editor. - */ - readEditor(options: any, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - readEditor(callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - /** - * Set effects based on two events and attributes. - */ - setEffects(el: BlessedElement, fel: BlessedElement, over: any, out: any, effects: any, temp: any): void; - /** - * Insert a line into the screen (using csr: this bypasses the output buffer). - */ - insertLine(n: number, y: number, top: number, bottom: number): void; - /** - * Delete a line from the screen (using csr: this bypasses the output buffer). - */ - deleteLine(n: number, y: number, top: number, bottom: number): void; - /** - * Insert a line at the bottom of the screen. - */ - insertBottom(top: number, bottom: number): void; - /** - * Insert a line at the top of the screen. - */ - insertTop(top: number, bottom: number): void; - /** - * Delete a line at the bottom of the screen. - */ - deleteBottom(top: number, bottom: number): void; - /** - * Delete a line at the top of the screen. - */ - deleteTop(top: number, bottom: number): void; - /** - * Enable mouse events for the screen and optionally an element (automatically called when a form of - * on('mouse') is bound). - */ - enableMouse(el: BlessedElement): void; - enableMouse(): void; - /** - * Enable keypress events for the screen and optionally an element (automatically called when a form of - * on('keypress') is bound). - */ - enableKeys(el: BlessedElement): void; - enableKeys(): void; - /** - * Enable key and mouse events. Calls bot enableMouse and enableKeys. - */ - enableInput(el: BlessedElement): void; - enableInput(): void; - /** - * Attempt to copy text to clipboard using iTerm2's proprietary sequence. Returns true if successful. - */ - copyToClipboard(text: string): void; - /** - * Attempt to change cursor shape. Will not work in all terminals (see artificial cursors for a solution - * to this). Returns true if successful. - */ - cursorShape(shape: boolean, blink: boolean): any; - /** - * Attempt to change cursor color. Returns true if successful. - */ - cursorColor(color: string): void; - /** - * Attempt to reset cursor. Returns true if successful. - */ - cursorReset(): void; - /** - * Take an SGR screenshot of the screen within the region. Returns a string containing only - * characters and SGR codes. Can be displayed by simply echoing it in a terminal. - */ - screenshot(xi: number, xl: number, yi: number, yl: number): string; - screenshot(): void; - /** - * Destroy the screen object and remove it from the global list. Also remove all global events relevant - * to the screen object. If all screen objects are destroyed, the node process is essentially reset - * to its initial state. - */ - destroy(): void; - /** - * Reset the terminal to term. Reloads terminfo. - */ - setTerminal(term: string): void; - } - - export interface Padding { - left?: number; - right?: number; - top?: number; - bottom?: number; - } - - export class PositionCoords { - xi: number; - xl: number; - yi: number; - yl: number; - } - - export interface Position { - left: number | string; - right: number | string; - top: number | string; - bottom: number | string; - } - - export interface Border { - /** - * Type of border (line or bg). bg by default. - */ - type?: "line" | "bg"; - /** - * Character to use if bg type, default is space. - */ - ch?: string; - /** - * Border foreground and background, must be numbers (-1 for default). - */ - bg?: number; - fg?: number; - /** - * Border attributes. - */ - bold?: string; - underline?: string; - } - - export interface ElementOptions extends INodeOptions { - tags?: boolean; - - fg?: string; - bg?: string; - bold?: string; - underline?: string; - - style?: any; - /** - * Border object, see below. - */ - border?: Border | "line" | "bg"; - /** - * Element's text content. - */ - content?: string; - /** - * Element is clickable. - */ - clickable?: boolean; - /** - * Element is focusable and can receive key input. - */ - input?: boolean; - keyable?: boolean; - /** - * Element is focused. - */ - focused?: BlessedElement; - /** - * Whether the element is hidden. - */ - hidden?: boolean; - /** - * A simple text label for the element. - */ - label?: string; - /** - * A floating text label for the element which appears on mouseover. - */ - hoverText?: string; - /** - * Text alignment: left, center, or right. - */ - align?: "left" | "center" | "right"; - /** - * Vertical text alignment: top, middle, or bottom. - */ - valign?: "top" | "middle" | "bottom"; - /** - * Shrink/flex/grow to content and child elements. Width/height during render. - */ - shrink?: boolean; - /** - * Amount of padding on the inside of the element. Can be a number or an object containing - * the properties: left, right, top, and bottom. - */ - padding?: number | Padding; - - top?: Types.TTopLeft; - left?: Types.TTopLeft; - right?: Types.TPosition; - bottom?: Types.TPosition; - - /** - * Width/height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). - * Percentages can also have offsets (50%+1, 50%-1). - */ - width?: number | string; - /** - * Offsets of the element relative to its parent. Can be a number, percentage (0-100%), or - * keyword (center). right and bottom do not accept keywords. Percentages can also have - * offsets (50%+1, 50%-1). - */ - height?: number | string; - /** - * Can contain the above options. - */ - position?: Position; - /** - * Whether the element is scrollable or not. - */ - scrollable?: boolean; - /** - * Background character (default is whitespace ). - */ - ch?: string; - /** - * Allow the element to be dragged with the mouse. - */ - draggable?: boolean; - /** - * Draw a translucent offset shadow behind the element. - */ - shadow?: boolean; - } - - export interface Coords { - xl: number; - xi: number; - yl: number; - yi: number; - base: number; - _contentEnd: {x: number; y: number;}; - notop: Types.TTopLeft; - noleft: Types.TTopLeft; - noright: Types.TPosition; - nobot: Types.TPosition; - } - - export interface LabelOptions { - text: string; - side: Types.TAlign; - } - - // TODO: scrollable - Note: If the scrollable option is enabled, Element inherits all methods from ScrollableBox. - export abstract class BlessedElement extends NodeWithEvents implements IHasOptions { - constructor(opts: ElementOptions); - - // ** properties ** // - - /** - * Original options object. - */ - options: ElementOptions; - /** - * Name of the element. Useful for form submission. - */ - name: string; - /** - * Border object. - */ - border: Border; - - style: any; - position: Position; - content: string; - hidden: boolean; - visible: boolean; - detached: boolean; - /** - * Border foreground and background, must be numbers (-1 for default). - */ - bg: number; - fg: number; - /** - * Border attributes. - */ - bold: string; - underline: string; - /** - * Calculated width. - */ - width: number | string; - /** - * Calculated height. - */ - height: number | string; - /** - * Calculated relative top offset.*/ - top: Types.TTopLeft; - /** - * Calculated relative left offset. - */ - left: Types.TTopLeft; - /** - * Calculated relative right offset. - */ - right: Types.TPosition; - /** - * Calculated relative bottom offset. - */ - bottom: Types.TPosition; - /** - * Calculated absolute top offset. - */ - atop: Types.TTopLeft; - /** - * Calculated absolute left offset. - */ - aleft: Types.TTopLeft; - /** - * Calculated absolute right offset. - */ - aright: Types.TPosition; - /** - * Calculated absolute bottom offset. - */ - abottom: Types.TPosition; - - /** - * Whether the element is draggable. Set to true to allow dragging. - */ - draggable: boolean; - - itop: Types.TTopLeft; - ileft: Types.TTopLeft; - iheight: Types.TPosition; - iwidth: Types.TPosition; - - /** - * Calculated relative top offset. - */ - rtop: Types.TTopLeft; - /** - * Calculated relative left offset. - */ - rleft: Types.TTopLeft; - /** - * Calculated relative right offset. - */ - rright: Types.TPosition; - /** - * Calculated relative bottom offset. - */ - rbottom: Types.TPosition; - - lpos: PositionCoords; - - // ** methods ** // - - /** - * Write content and children to the screen buffer. - */ - render(): Coords; - /** - * Hide element.*/ - hide(): void; - /** - * Show element. - */ - show(): void; - /** - * Toggle hidden/shown. - */ - toggle(): void; - /** - * Focus element. - */ - focus(): void; - /** - * Same asel.on('screen', ...) except this will automatically keep track of which listeners - * are bound to the screen object. For use with removeScreenEvent(), free(), and destroy(). - */ - onScreenEvent(type: string, handler: Function): void; - /** - * Same asel.removeListener('screen', ...) except this will automatically keep track of which - * listeners are bound to the screen object. For use with onScreenEvent(), free(), and destroy(). - */ - removeScreenEvent(type: string, handler: Function): void; - /** - * Free up the element. Automatically unbind all events that may have been bound to the screen - * object. This prevents memory leaks. For use with onScreenEvent(), removeScreenEvent(), - * and destroy(). - */ - free(): void; - /** - * Same as the detach() method, except this will automatically call free() and unbind any screen - * events to prevent memory leaks. for use with onScreenEvent(), removeScreenEvent(), and free(). - */ - destroy(): void; - /** - * Set the z-index of the element (changes rendering order). - */ - setIndex(z: number): void; - /** - * Put the element in front of its siblings.*/ - setFront(): void; - /** - * Put the element in back of its siblings. - */ - setBack(): void; - /** - * text/options - Set the label text for the top-left corner. Example options: {text:'foo',side:'left'} - */ - setLabel(arg: string | LabelOptions): void; - /** - * Remove the label completely. - */ - removeLabel(): any; - /** - * text/options - Set a hover text box to follow the cursor. Similar to the "title" DOM attribute - * in the browser. Example options: {text:'foo'} - */ - setHover(arg: string | LabelOptions): void; - /** - * Remove the hover label completely. - */ - removeHover(): void; - /** - * Enable mouse events for the element (automatically called when a form of on('mouse') is bound). - */ - enableMouse(): void; - /** - * Enable keypress events for the element (automatically called when a form of on('keypress') is bound). - */ - enableKeys(): void; - /** - * Enable key and mouse events. Calls bot enableMouse and enableKeys. - */ - enableInput(): void; - /** - * Enable dragging of the element. - */ - enableDrag(): void; - /** - * Disable dragging of the element. - */ - disableDrag(): void; - /** - * Take an SGR screenshot of the screen within the region. Returns a string containing only - * characters and SGR codes. Can be displayed by simply echoing it in a terminal. - */ - screenshot(xi: number, xl: number, yi: number, yl: number): string; - screenshot(): void; - - /* - Content Methods - - Methods for dealing with text content, line by line. Useful for writing a text editor, - irc client, etc. - - Note: All of these methods deal with pre-aligned, pre-wrapped text. If you use deleteTop() - on a box with a wrapped line at the top, it may remove 3-4 "real" lines (rows) depending - on how long the original line was. - - The lines parameter can be a string or an array of strings. The line parameter must - be a string. - */ - - /** - * Set the content. Note: When text is input, it will be stripped of all non-SGR - * escape codes, tabs will be replaced with 8 spaces, and tags will be replaced - * with SGR codes (if enabled). - */ - setContent(text: string): void; - /** - * Return content, slightly different from el.content. Assume the above formatting. - */ - getContent(): string; - /** - * Similar to setContent, but ignore tags and remove escape codes. - */ - setText(text: string): void; - /** - * Similar to getContent, but return content with tags and escape codes removed. - */ - getText(): string; - /** - * Insert a line into the box's content. - */ - insertLine(i: number, lines: string | string[]): void; - /** - * Delete a line from the box's content. - */ - deleteLine(i: number): void; - /** - * Get a line from the box's content. - */ - getLine(i: number): string; - /** - * Get a line from the box's content from the visible top. - */ - getBaseLine(i: number): string; - /** - * Set a line in the box's content. - */ - setLine(i: number, line: string | string[]): void; - /** - * Set a line in the box's content from the visible top. - */ - setBaseLine(i: number, line: string | string[]): void; - /** - * Clear a line from the box's content. - */ - clearLine(i: number): void; - /** - * Clear a line from the box's content from the visible top. - */ - clearBaseLine(i: number): void; - /** - * Insert a line at the top of the box. - */ - insertTop(lines: string | string[]): void; - /** - * Insert a line at the bottom of the box. - */ - insertBottom(lines: string | string[]): void; - /** - * Delete a line at the top of the box. - */ - deleteTop(): void; - /** - * Delete a line at the bottom of the box. - */ - deleteBottom(): void; - /** - * Unshift a line onto the top of the content. - */ - unshiftLine(lines: string | string[]): void; - /** - * Shift a line off the top of the content. - */ - shiftLine(i: number): void; - /** - * Push a line onto the bottom of the content. - */ - pushLine(lines: string | string[]): void; - /** - * Pop a line off the bottom of the content. - */ - popLine(i: number): string; - /** - * An array containing the content lines. - */ - getLines(): string[]; - /** - * An array containing the lines as they are displayed on the screen. - */ - getScreenLines(): string[]; - /** - * Get a string's displayed width, taking into account double-width, surrogate pairs, - * combining characters, tags, and SGR escape codes. - */ - strWidth(text: string): string; - - // ** events ** // - } - - export interface ScrollableBoxOptions extends ElementOptions { - /** - * A limit to the childBase. Default is Infinity. - */ - baseLimit?: number; - /** - * A option which causes the ignoring of childOffset. This in turn causes the - * childBase to change every time the element is scrolled. - */ - alwaysScroll?: boolean; - /** - * Object enabling a scrollbar. - * Style of the scrollbar track if present (takes regular style options). - */ - scrollbar?: { style?: any; track?: any; ch?: string; } - } - - export interface ScrollableTextOptions extends ScrollableBoxOptions { - /** - * Whether to enable automatic mouse support for this element. - * Use pre-defined mouse events (right-click for editor). - */ - mouse?: boolean | (() => void); - /** - * Use pre-defined keys (i or enter for insert, e for editor, C-e for editor while inserting). - */ - keys?: string | string[] | boolean; - /** - * Use vi keys with the keys option. - */ - vi?: boolean; - } - - export interface BoxOptions extends ScrollableTextOptions { - bindings?: any; - } - - /** - * DEPRECATED - Use Box with the scrollable option instead. A box with scrollable content. - */ - export class ScrollableBoxElement extends BlessedElement { - /** - * The offset of the top of the scroll content. - */ - childBase: number; - /** - * The offset of the chosen item/line. - */ - childOffset: number; - - /** - * Scroll the content by a relative offset. - */ - scroll(offset: number, always?: boolean): void; - /** - * Scroll the content to an absolute index. - */ - scrollTo(index: number): void; - /** - * Same as scrollTo. - */ - setScroll(index: number): void; - /** - * Set the current scroll index in percentage (0-100). - */ - setScrollPerc(perc: number): void; - /** - * Get the current scroll index in lines. - */ - getScroll(): number; - /** - * Get the actual height of the scrolling area. - */ - getScrollHeight(): number; - /** - * Get the current scroll index in percentage. - */ - getScrollPerc(): number; - /** - * Reset the scroll index to its initial state. - */ - resetScroll(): void; - - on(event: string, listener: Function): this; - /** - * Received when the element is scrolled. - */ - on(event: "scroll", callback: () => void): this; - } - - /** - * DEPRECATED - Use Box with the scrollable and alwaysScroll options instead. - * A scrollable text box which can display and scroll text, as well as handle - * pre-existing newlines and escape codes. - */ - export class ScrollableTextElement extends ScrollableBoxElement { - } - - /** - * A box element which draws a simple box containing content or other elements. - */ - export class BoxElement extends ScrollableTextElement implements IHasOptions { - constructor(opts: BoxOptions); - - /** - * Original options object. - */ - options: BoxOptions; - } - - export interface TextOptions extends ElementOptions { - /** - * Fill the entire line with chosen bg until parent bg ends, even if there - * is not enough text to fill the entire width. - */ - fill?: boolean; - /** - * Text alignment: left, center, or right. - */ - align?: Types.TAlign; - } - - /** - * An element similar to Box, but geared towards rendering simple text elements. - */ - export class TextElement extends BlessedElement implements IHasOptions { - constructor(opts: TextOptions); - - /** - * Original options object. - */ - options: TextOptions; - } - - /** - * A simple line which can be line or bg styled. - */ - export interface LineOptions extends BoxOptions { - /** - * Can be vertical or horizontal. - */ - orientation?: "vertical" | "horizontal"; - /** - * Treated the same as a border object. (attributes can be contained in style). - */ + interface TStyle { type?: string; bg?: string; fg?: string; ch?: string; + bold?: boolean; + underline?: boolean; + blink?: boolean; + inverse?: boolean; + invisible?: boolean; + transparent?: boolean; + border?: "line" | "bg" | TBorder; + hover?: boolean; + focus?: boolean; + label?: string; + track?: { bg?: string; fg?: string }; + scrollbar?: { bg?: string; fg?: string }; } - /** - * A simple line which can be line or bg styled. - */ - export class LineElement extends BoxElement implements IHasOptions { - constructor(opts: LineOptions); + interface TBorder { + /** + * Type of border (line or bg). bg by default. + */ + type?: "line" | "bg"; /** - * Original options object. - */ - options: LineOptions; + * Character to use if bg type, default is space. + */ + ch?: string; + + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg?: number; + fg?: number; + + /** + * Border attributes. + */ + bold?: string; + underline?: string; } - export interface BigTextOptions extends BoxOptions { + interface TCursor { /** - * bdf->json font file to use (see ttystudio for instructions on compiling BDFs to JSON). - */ - font?: string; + * Have blessed draw a custom cursor and hide the terminal cursor (experimental). + */ + artificial: boolean; + /** - * bdf->json bold font file to use (see ttystudio for instructions on compiling BDFs to JSON). - */ - fontBold?: string; + * Shape of the cursor. Can be: block, underline, or line. + */ + shape: "block" | "underline" | "line"; + /** - * foreground character. (default: ' ') - */ - fch?: string; + * Whether the cursor blinks. + */ + blink: boolean; + + /** + * Color of the color. Accepts any valid color value (null is default). + */ + color: string; } - /** - * A box which can render content drawn as 8x14 cell characters using the terminus font. - */ - export class BigTextElement extends BoxElement implements IHasOptions { - constructor(opts: BigTextOptions); + type TAlign = "left" | "center" | "right"; - /** - * Original options object. - */ - options: BigTextOptions; + interface ListbarCommand { + key: string; + callback(): void; } - export interface ListElementStyle { - selected?: any; - item?: any; + interface TImage { + /** + * Pixel width. + */ + width: number; + + /** + * Pixel height. + */ + height: number; + + /** + * Image bitmap. + */ + bmp: any; + + /** + * Image cellmap (bitmap scaled down to cell size). + */ + cellmap: any; } - export interface ListOptions extends BoxOptions { + interface Cursor { /** - * Style for a selected item. Style for an unselected item. - */ - style?: TStyle; - /** - * An array of strings which become the list's items. - */ - items?: string[]; - /** - * A function that is called when vi mode is enabled and the key / is pressed. This function accepts a - * callback function which should be called with the search string. The search string is then used to - * jump to an item that is found in items. - */ - search?: () => void; - /** - * Whether the list is interactive and can have items selected (Default: true). - */ - interactive?: boolean; - /** - * Whether to automatically override tags and invert fg of item when selected (Default: true). - */ - invertSelected?: boolean; - } - - export class ListElement extends BoxElement implements IHasOptions> { - constructor(opts: ListOptions); - - /** - * Original options object. - */ - options: ListOptions; - - /** - * Add an item based on a string. - */ - add(text: string): void; - /** - * Add an item based on a string. - */ - addItem(text: string): void; - /** - * Removes an item from the list. Child can be an element, index, or string. - */ - removeItem(child: BlessedElement): BlessedElement; - /** - * Push an item onto the list. - * */ - pushItem(child: BlessedElement): number; - /** - * Pop an item off the list. - * */ - popItem(): BlessedElement; - /** - * Unshift an item onto the list. - */ - unshiftItem(child: BlessedElement): number; - /** - * Shift an item off the list. - * */ - shiftItem(): BlessedElement; - /** - * Inserts an item to the list. Child can be an element, index, or string. - */ - insertItem(i: number, child: BlessedElement): void; - /** - * Returns the item element. Child can be an element, index, or string. - */ - getItem(child: BlessedElement): BlessedElement; - /** - * Set item to content. - */ - setItem(child: BlessedElement, content: BlessedElement | string): void; - /** - * Remove and insert items to the list. - * */ - spliceItem(i: number, n: number, ...items: BlessedElement[]): void; - /** - * Clears all items from the list. - * */ - clearItems(): void; - /** - * Sets the list items to multiple strings. - */ - setItems(items: BlessedElement[]): void; - /** - * Returns the item index from the list. Child can be an element, index, or string. - */ - getItemIndex(child: BlessedElement): number; - /** - * Select an index of an item. - * */ - select(index: number): void; - /** - * Select item based on current offset. - * */ - move(offset: number): void; - /** - * Select item above selected. - * */ - up(amount: number): void; - /** - * Select item below selected. - */ - down(amount: number): void; - /** - * Show/focus list and pick an item. The callback is executed with the result. - */ - pick(callback: () => void): void; - /** - * Find an item based on its text content. - */ - fuzzyFind(arg: string | RegExp | (() => void)): void; - - // ** events ** // + * Have blessed draw a custom cursor and hide the terminal cursor (experimental). + */ + artificial: boolean; - on(event: string, listener: Function): this; - /** - * Received when an item is selected. - */ - on(event: "select", callback: (item: BoxElement, index: number) => void): this; - /** - * List was canceled (when esc is pressed with the keys option). - */ - on(event: "cancel", callback: () => void): this; - /** - * Either a select or a cancel event was received. - */ - on(event: "action", callback: () => void): this; - - on(event: "create item", callback: () => void): this; - on(event: "add item", callback: () => void): this; - on(event: "remove item", callback: () => void): this; - on(event: "insert item", callback: () => void): this; - on(event: "set items", callback: () => void): this; - on(event: "select item", callback: (item: BlessedElement, index: number) => void): this; - } - - export interface FileManagerOptions extends ListOptions { - /** - * Current working directory. - */ - cwd?: string; - } - - export class FileManagerElement extends ListElement implements IHasOptions { - constructor(opts: FileManagerOptions); - - /** - * Original options object. - */ - options: FileManagerOptions; /** - * Current working directory. - */ - cwd: string; + * Shape of the cursor. Can be: block, underline, or line. + */ + shape: boolean; /** - * Refresh the file list (perform a readdir on cwd and update the list items). - */ - refresh(cwd:string, callback: () => void): void; - refresh(callback: () => void): void; - refresh(): void; - /** - * Pick a single file and return the path in the callback. - */ - pick(cwd:string, callback: () => void): void; - pick(callback: () => void): void; - /** - * Reset back to original cwd. - */ - reset(cwd:string, callback: () => void): void; - reset(callback: () => void): void; - reset(): void; - - // ** events ** // - - on(event: string, listener: Function): this; - /** - * Received when an item is selected. - */ - on(event: "cd", callback: (file: string, cwd: string) => void): this; - /** - * Received when an item is selected. - */ - on(event: "file", callback: (file: string) => void): this; - - on(event: "error", callback: (err: any, file: string) => void): this; - on(event: "refresh", callback: () => void): this; - } - - export interface StyleListTable extends ListElementStyle { - /** - * Header style. - */ - header?: any; - /** - * Cell style. - */ - cell?: any; - } - - export interface ListTableOptions extends ListOptions { - /** - * Array of array of strings representing rows. - */ - rows?: string[]; - data?: string[][]; - /** - * Spaces to attempt to pad on the sides of each cell. 2 by default: one space on each side - * (only useful if the width is shrunken). - */ - pad?: number; - /** - * Do not draw inner cells. - */ - noCellBorders?: boolean; - - style?: StyleListTable; - } - - export class ListTableElement extends ListElement implements IHasOptions { - constructor(opts: ListTableOptions); - - /** - * Original options object. - */ - options: ListTableOptions; - - /** - * Set rows in table. Array of arrays of strings. - * @example: - * - * table.setData([ - [ 'Animals', 'Foods' ], - [ 'Elephant', 'Apple' ], - [ 'Bird', 'Orange' ] - ]); - */ - setRows(rows: string[][]): void; - /** - * Set rows in table. Array of arrays of strings. - * @example: - * - * table.setData([ - [ 'Animals', 'Foods' ], - [ 'Elephant', 'Apple' ], - [ 'Bird', 'Orange' ] - ]); - */ - setData(rows: string[][]): void; - } - - export interface ListbarOptions extends BoxOptions { - style?: ListElementStyle; - /** - * Set buttons using an object with keys as titles of buttons, containing of objects - * containing keys of keys and callback. - */ - commands: Types.ListbarCommand[]; - items: Types.ListbarCommand[]; - /** - * Automatically bind list buttons to keys 0-9. - */ - autoCommandKeys: boolean; - } - - export class ListbarElement extends BoxElement implements IHasOptions { - constructor(opts: ListbarOptions); - - /** - * Original options object. - */ - options: ListbarOptions; - - /** - * Set commands (see commands option above). - */ - setItems(commands: Types.ListbarCommand[]): void; - /** - * Append an item to the bar. - */ - add(item: Types.ListbarCommand, callback: () => void): void; - /** - * Append an item to the bar. - */ - addItem(item: Types.ListbarCommand, callback: () => void): void; - /** - * Append an item to the bar. - */ - appendItem(item: Types.ListbarCommand, callback: () => void): void; - /** - * Select an item on the bar. - */ - select(offset: number): void; - /** - * Remove item from the bar. - */ - removeItem(child: BlessedElement): void; - /** - * Move relatively across the bar. - */ - move(offset: number): void; - /** - * Move left relatively across the bar. - */ - moveLeft(offset: number): void; - /** - * Move right relatively across the bar. - */ - moveRight(offset: number): void; - /** - * Select button and execute its callback. - */ - selectTab(index: number): void; - - // ** events ** // - - on(event: string, listener: Function): this; - - on(event: "set items", callback: () => void): this; - on(event: "remove item", callback: () => void): this; - on(event: "select tab", callback: () => void): this; - } - - export interface FormOptions extends BoxOptions { - /** - * Allow default keys (tab, vi keys, enter). - */ - keys?: any; - /** - * Allow vi keys. - */ - vi?: boolean; - } - - export class FormElement extends BoxElement implements IHasOptions { - constructor(opts: FormOptions); - - /** - * Original options object. - */ - options: FormOptions; - /** - * Last submitted data. - */ - submission: TFormData; - - /** - * Focus next form element. - */ - focusNext(): void; - /** - * Focus previous form element. - */ - focusPrevious(): void; - /** - * Submit the form. - */ - submit(): void; - /** - * Discard the form. - */ - cancel(): void; - /** - * Clear the form. - */ - reset(): void; - - // ** events ** // - - on(event: string, listener: Function): this; - /** - * Form is submitted. Receives a data object. - */ - on(event: "submit", callback: (out: TFormData) => void): this; - /** - * Form is discarded. - */ - on(event: "cancel", callback: () => void): this; - /** - * Form is cleared. - */ - on(event: "reset", callback: () => void): this; - } - - export interface InputOptions extends BoxOptions { } - - export abstract class InputElement extends BoxElement { - constructor(opts: InputOptions); - } - - /** - * A box which allows multiline text input. - */ - export interface TextareaOptions extends InputOptions { - /** - * Call readInput() when the element is focused. Automatically unfocus. - */ - inputOnFocus?: boolean; - } - - export class TextareaElement extends InputElement implements IHasOptions { - constructor(opts: TextareaOptions); - - /** - * Original options object. - */ - options: TextareaOptions; - - /** - * The input text. read-only. - */ - value: string; - - /** - * Submit the textarea (emits submit). - */ - submit(): void; - /** - * Cancel the textarea (emits cancel). - */ - cancel(): void; - /** - * Grab key events and start reading text from the keyboard. Takes a callback which receives - * the final value. - */ - readInput(callback?: (err: any, value?: string) => void): void; - /** - * Grab key events and start reading text from the keyboard. Takes a callback which receives - * the final value. - */ - input(callback: (err: any, value?: string) => void): void; - /** - * Grab key events and start reading text from the keyboard. Takes a callback which receives - * the final value. - */ - setInput(callback: (err: any, value?: string) => void): void; - /** - * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which - * receives the final value. - */ - readEditor(callback: (err: any, value?: string) => void): void; - /** - * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which - * receives the final value. - */ - editor(callback: (err: any, value?: string) => void): void; - /** - * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which - * receives the final value. - */ - setEditor(callback: (err: any, value?: string) => void): void; - /** - * The same as this.value, for now. - */ - getValue(): string; - /** - * Clear input. - */ - clearValue(): void; - /** - * Set value. - */ - setValue(text: string): void; - - // ** events ** // - - on(event: string, listener: Function): this; - - on(event: "error", callback: (err: any) => void): this; - - /** - * Value is submitted (enter). - */ - on(event: "submit", callback: (value: any) => void): this; - /** - * Value is discared (escape). - */ - on(event: "cancel", callback: (value: any) => void): this; - /** - * Either submit or cancel. - */ - on(event: "action", callback: (value: any) => void): this; - } - - export interface TextboxOptions extends TextareaOptions { - /** - * Completely hide text. - */ - secret?: boolean; - /** - * Replace text with asterisks (*). - */ - censor?: boolean; - } - - export class TextboxElement extends TextareaElement implements IHasOptions { - constructor(opts: TextboxOptions); - - /** - * Original options object. - */ - options: TextboxOptions; - - /** - * Completely hide text. - */ - secret: boolean; - /** - * Replace text with asterisks (*). - */ - censor: boolean; - } - - export interface ButtonOptions extends BoxOptions { } - - export class ButtonElement extends InputElement implements IHasOptions { - constructor(opts: ButtonOptions); - - /** - * Original options object. - */ - options: ButtonOptions; - - /** - * Press button. Emits press. - */ - press(): void; - - on(event: string, listener: Function): this; - - on(event: "press", callback: () => void): this; - } - - export interface CheckboxOptions extends BoxOptions { - /** - * whether the element is checked or not. - * */ - checked?: boolean; - /** - * enable mouse support. - * */ - mouse?: boolean; - } - - /** - * A checkbox which can be used in a form element. - * */ - export class CheckboxElement extends InputElement implements IHasOptions { - constructor(options?: CheckboxOptions); - - /** - * Original options object. - */ - options: CheckboxOptions; - - /** - * the text next to the checkbox (do not use setcontent, use `check.text = ''`). - * */ - text: string; - /** - * whether the element is checked or not. - * */ - checked: boolean; - /** - * same as `checked`. - * */ - value: boolean; - - /** - * check the element. - * */ - check(): void; - /** - * uncheck the element. - * */ - uncheck(): void; - /** - * toggle checked state. - * */ - toggle(): void; - } - - export interface RadioSetOptions extends BoxOptions { } - - /** - * An element wrapping RadioButtons. RadioButtons within this element will be mutually exclusive - * with each other. - * */ - export abstract class RadioSetElement extends BoxElement { - constructor(opts: RadioSetOptions); - } - - export interface RadioButtonOptions extends BoxOptions { } - - /** - * A radio button which can be used in a form element. - */ - export abstract class RadioButtonElement extends CheckboxElement { - constructor(opts: RadioButtonOptions); - } - - export interface PromptOptions extends BoxOptions { } - - /** - * A prompt box containing a text input, okay, and cancel buttons (automatically hidden). - */ - export class PromptElement extends BoxElement implements IHasOptions { - constructor(opts: PromptOptions); - - options: PromptOptions; - - /** - * Show the prompt and wait for the result of the textbox. Set text and initial value. - */ - input(text: string, value: string, callback: (err: any, value: string) => void): void; - setInput(text: string, value: string, callback: (err: any, value: string) => void): void; - readInput(text: string, value: string, callback: (err: any, value: string) => void): void; - } - - export interface QuestionOptions extends BoxOptions { } - - /** - * A question box containing okay and cancel buttons (automatically hidden). - */ - export class QuestionElement extends BoxElement implements IHasOptions { - constructor(opts: QuestionOptions); - - options: QuestionOptions; - - /** - * Ask a question. callback will yield the result. - */ - ask(question: string, callback: (err: any, value: string) => void): void; - } - - export interface MessageOptions extends BoxOptions { } - - /** - * A box containing a message to be displayed (automatically hidden). - */ - export class MessageElement extends BoxElement implements IHasOptions { - constructor(opts: MessageOptions); - - options: MessageOptions; - - /** - * Display a message for a time (default is 3 seconds). Set time to 0 for a perpetual message that is dismissed on keypress. - */ - log(text: string, time: number, callback: (err: any) => void): void; - log(text: string, callback: (err: any) => void): void; - display(text: string, time: number, callback: (err: any) => void): void; - display(text: string, callback: (err: any) => void): void; - - /** - * Display an error in the same way. - */ - error(text: string, time: number, callback: () => void): void; - error(text: string, callback: () => void): void; - } - - export interface LoadingOptions extends BoxOptions { } - - /** - * A box with a spinning line to denote loading (automatically hidden). - */ - export class LoadingElement extends BoxElement implements IHasOptions { - constructor(opts: LoadingOptions); - - options: LoadingOptions; - - /** - * Display the loading box with a message. Will lock keys until stop is called. - */ - load(text: string): void; - /** - * Hide loading box. Unlock keys. - */ - stop(): void; - } - - export interface ProgressBarOptions extends BoxOptions { - /** - * can be `horizontal` or `vertical`. - * */ - orientation: string; - /** - * the character to fill the bar with (default is space). - * */ - pch: string; - /** - * the amount filled (0 - 100). - * */ - filled: number; - /** - * same as `filled`. - * */ - value: number; - /** - * enable key support. - * */ - keys: boolean; - /** - * enable mouse support. - * */ - mouse: boolean; - } - - /** - * A progress bar allowing various styles. This can also be used as a form input. - */ - export class ProgressBarElement extends InputElement implements IHasOptions { - constructor(options?: ProgressBarOptions); - - options: ProgressBarOptions; - - /** - * progress the bar by a fill amount. - * */ - progress(amount:number): void; - /** - * set progress to specific amount. - * */ - setProgress(amount:number): void; - /** - * reset the bar. - * */ - reset(): void; - - on(event: string, listener: Function): this; - /** - * Bar was reset. - */ - on(event: "reset", callback: () => void): this; - /** - * Bar has completely filled. - */ - on(event: "complete", callback: () => void): this; - } - - export interface LogOptions extends ScrollableTextOptions { - /** - * amount of scrollback allowed. default: Infinity. - * */ - scrollback?: number; - /** - * scroll to bottom on input even if the user has scrolled up. default: false. - * */ - scrollOnInput?: boolean; - } - - /** - * A log permanently scrolled to the bottom. - * */ - export class Log extends ScrollableTextElement implements IHasOptions { - constructor(options?: LogOptions); - - options: LogOptions; - - /** - * amount of scrollback allowed. default: Infinity. - * */ - scrollback: number; - /** - * scroll to bottom on input even if the user has scrolled up. default: false. - * */ - scrollOnInput: boolean; - - /** - * add a log line. - * */ - log(text:string): void; - /** - * add a log line. - * */ - add(text:string): void; - } - - export interface TableOptions extends BoxOptions { - /** - * array of array of strings representing rows (same as `data`). - * */ - rows?: string[][]; - /** - * array of array of strings representing rows (same as `rows`). - * */ - data?: string[][]; - /** - * spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). - * */ - pad?: number; - /** - * do not draw inner cells. - * */ - noCellBorders?: boolean; - /** - * fill cell borders with the adjacent background color. - * */ - fillCellBorders?: boolean; - } - - /** - * A stylized table of text elements. - * */ - export class TableElement extends BoxElement implements IHasOptions { - constructor(opts: TableOptions); - - options: TableOptions; - - /** - * set rows in table. array of arrays of strings. - * */ - setData(rows: string[][]): void; - /** - * set rows in table. array of arrays of strings. - * */ - setRows(rows: string[][]): void; - } - - export interface TerminalOptions extends BoxOptions { - /** - * handler for input data. - * */ - handler?: (userInput:Buffer) => void; - /** - * name of shell. $SHELL by default. - * */ - shell?:string; - /** - * args for shell. - * */ - args?:any; - /** - * can be line, underline, and block. - * */ - cursor?: 'line'|'underline'|'block'; - - terminal?: string; - - /** - * Object for process env. - */ - env?: any; - } - - export class TerminalElement extends BoxElement implements IHasOptions { - constructor(opts: TerminalOptions); - - options: TerminalOptions; - - /** - * reference to the headless term.js terminal. - * */ - term: any; - /** - * reference to the pty.js pseudo terminal. - * */ - pty: any; - - /** - * write data to the terminal. - * */ - write(data:string): void; - - /** - * nearly identical to `element.screenshot`, however, the specified region includes the terminal's _entire_ scrollback, rather than just what is visible on the screen. - * */ - screenshot(xi?:number, xl?:number, yi?:number, yl?:number): string; - } - - export interface ImageOptions extends BoxOptions { - /** - * path to image. - * */ - file: string; - /** - * path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. - * */ - type: "ansi" | "overlay" | "w3m"; - } - - /** - * Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. X11 required: works in xterm, urxvt, and possibly other terminals. - * */ - export class ImageElement extends BoxElement implements IHasOptions { - constructor(options?: ImageOptions); - - options: ImageOptions; - } - - export interface ANSIImageOptions extends BoxOptions { - /** - * URL or path to PNG/GIF file. Can also be a buffer. - * */ - file: string; - /** - * Scale cellmap down (0-1.0) from its original pixel width/height (Default: 1.0). - * */ - scale: number; - - /** - * This differs from other element's width or height in that only one of them is needed: blessed will maintain the aspect ratio of the image as it scales down to the proper number of cells. NOTE: PNG/GIF's are always automatically shrunken to size (based on scale) if a width or height is not given. - * */ - width: number | string; - height: number | string; - - /** - * Add various "density" ASCII characters over the rendering to give the image more detail, similar to libcaca/libcucul (the library mplayer uses to display videos in the terminal). - */ - ascii: string; - - /** - * Whether to animate if the image is an APNG/animating GIF. If false, only display the first frame or IDAT (Default: true). - */ - animate: boolean; - - /** - * Set the speed of animation. Slower: 0.0-1.0. Faster: 1-1000. It cannot go faster than 1 frame per millisecond, so 1000 is the fastest. (Default: 1.0) - */ - speed: number; - - /** - * mem or cpu. If optimizing for memory, animation frames will be rendered to bitmaps as the animation plays, using less memory. Optimizing for cpu will precompile all bitmaps beforehand, which may be faster, but might also OOM the process on large images. (Default: mem). - */ - optimization: "mem" | "cpu"; - } - - /** - * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. - * */ - export class ANSIImageElement extends BoxElement implements IHasOptions { - constructor(options?:ANSIImageOptions); - - options: ANSIImageOptions; - - /** - * Image object from the png reader. - */ - img: Types.TImage; - - /** - * set the image in the box to a new path. - * */ - setImage(img: string, callback: () => void): void; - /** - * clear the current image. - * */ - clearImage(callback: () => void): void; - /** - * Play animation if it has been paused or stopped. - */ - play(): void; - /** - * Pause animation. - */ - pause(): void; - /** - * Stop animation. - */ - stop(): void; - } - - export interface OverlayImageOptions extends BoxOptions { - /** - * Path to image. - */ - file: string; - /** - * Render the file as ANSI art instead of using w3m to overlay Internally uses the ANSIImage element. See the ANSIImage element for more information/options. (Default: true). - */ - ansi: boolean; - /** - * Path to w3mimgdisplay. If a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. - */ - w3m: string; - /** - * Whether to search /usr, /bin, and /lib for w3mimgdisplay (Default: true). - */ - search: string; - } - - /** - * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. - * */ - export class OverlayImageElement extends BoxElement implements IHasOptions { - constructor(options?: OverlayImageOptions); - - options: OverlayImageOptions; - - /** - * set the image in the box to a new path. - * */ - setImage(img: string, callback: () => void): void; - /** - * clear the current image. - * */ - clearImage(callback: () => void): void; - /** - * get the size of an image file in pixels. - * */ - imageSize(img:string, callback: () => void): void; - /** - * get the size of the terminal in pixels. - * */ - termSize(callback: () => void): void; - /** - * get the pixel to cell ratio for the terminal. - * */ - getPixelRatio(callback: () => void): void; - } - - export interface VideoOptions extends BoxOptions { - /** - * Video to play. - */ - file: string; - /** - * Start time in seconds. - */ - start: number; - } - - export class VideoElement extends BoxElement implements IHasOptions { - constructor(options?: VideoOptions); - - options: VideoOptions; - - /** - * The terminal element running mplayer or mpv. - */ - tty: any; - } - - export interface LayoutOptions extends ElementOptions { - /** - * A callback which is called right before the children are iterated over to be rendered. Should return an - * iterator callback which is called on each child element: iterator(el, i). - */ - renderer?: () => void; - - /** - * Using the default renderer, it provides two layouts: inline, and grid. inline is the default and will render - * akin to inline-block. grid will create an automatic grid based on element dimensions. The grid cells' - * width and height are always determined by the largest children in the layout. - */ - layout: "inline" | "inline-block" | "grid"; - } - - export class LayoutElement extends BlessedElement implements IHasOptions { - constructor(options?: LayoutOptions); - - options: LayoutOptions; - - /** - * A callback which is called right before the children are iterated over to be rendered. Should return an - * iterator callback which is called on each child element: iterator(el, i). - */ - renderer(coords: PositionCoords): void; - /** - * Check to see if a previous child element has been rendered and is visible on screen. This is only useful - * for checking child elements that have already been attempted to be rendered! see the example below. - */ - isRendered(el: BlessedElement): boolean; - /** - * Get the last rendered and visible child element based on an index. This is useful for basing the position - * of the current child element on the position of the last child element. - */ - getLast(i: number): Element; - /** - * Get the last rendered and visible child element coords based on an index. This is useful for basing the position - * of the current child element on the position of the last child element. See the example below. - */ - getLastCoords(i: number): PositionCoords; - } + * Whether the cursor blinks. + */ + blink: boolean; - export class Program { /** - Wrap the given text in terminal formatting codes corresponding to the given attribute - name. The `attr` string can be of the form `red fg` or `52 bg` where `52` is a 0-255 - integer color number. - */ - text (text:string, attr:string): string; + * Color of the color. Accepts any valid color value (null is default). + */ + color: string; } } - export module widget { - export class Element extends Widgets.BlessedElement { } - export class Node extends Widgets.Node { } - export class Screen extends Widgets.Screen { } + namespace Events { + interface IMouseEventArg { + x: number; + y: number; + action: Types.TMouseAction; + } - export class Box extends Widgets.BoxElement { } - export class ScrollableBox extends Widgets.ScrollableBoxElement { } - export class ScrollableText extends Widgets.ScrollableTextElement { } - export class Text extends Widgets.BoxElement { } - export class Line extends Widgets.LineElement { } - export class BigText extends Widgets.BigTextElement { } - export class List extends Widgets.ListElement { } - export class FileManager extends Widgets.FileManagerElement { } - export class ListTable extends Widgets.ListTableElement { } - export class ListBar extends Widgets.ListbarElement { } - export class Form extends Widgets.FormElement { } - export class Textarea extends Widgets.TextareaElement { } - export class Button extends Widgets.ButtonElement { } - export class Checkbox extends Widgets.CheckboxElement { } - export class RadioSet extends Widgets.RadioSetElement { } - export class RadioButton extends Widgets.RadioButtonElement { } - - export class Prompt extends Widgets.PromptElement { } - export class question extends Widgets.QuestionElement { } - export class Message extends Widgets.MessageElement { } - export class Loading extends Widgets.LoadingElement { } - - export class ProgressBar extends Widgets.ProgressBarElement { } - export class Terminal extends Widgets.TerminalElement { } + interface IKeyEventArg { + full: string; + name: string; + shift: boolean; + ctrl: boolean; + meta: boolean; + sequence: string; + } } - export function screen(options?: Widgets.IScreenOptions): Widgets.Screen; + interface NodeChildProcessExecOptions { + cwd?: string; + stdio?: any; + customFds?: any; + env?: any; + encoding?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + } - export function box(options?: Widgets.BoxOptions): Widgets.BoxElement; - export function text(options?: Widgets.TextOptions): Widgets.TextElement; - export function line(options?: Widgets.LineOptions): Widgets.LineElement; - export function scrollablebox(options?: Widgets.BoxOptions): Widgets.BoxElement; - export function scrollabletext(options?: Widgets.BoxOptions): Widgets.BoxElement; - export function bigtext(options?: Widgets.BigTextOptions): Widgets.BigTextElement; - export function list(options?: Widgets.ListOptions): Widgets.ListElement; - export function filemanager(options?: Widgets.FileManagerOptions): Widgets.FileManagerElement; - export function listtable(options?: Widgets.ListTableOptions): Widgets.ListTableElement; - export function listbar(options?: Widgets.ListbarOptions): Widgets.ListbarElement; - export function form(options?: Widgets.FormOptions): Widgets.FormElement; - export function input(options?: Widgets.InputOptions): Widgets.InputElement; - export function textarea(options?: Widgets.TextareaOptions): Widgets.TextareaElement; - export function textbox(options?: Widgets.TextboxOptions): Widgets.TextboxElement; - export function button(options?: Widgets.ButtonOptions): Widgets.ButtonElement; - export function checkbox(options?: Widgets.CheckboxOptions): Widgets.CheckboxElement; - export function radioset(options?: Widgets.RadioSetOptions): Widgets.RadioSetElement; - export function radiobutton(options?: Widgets.RadioButtonOptions): Widgets.RadioButtonElement; + interface IDestroyable { + destroy(): void; + } - export function table(options?: Widgets.TableOptions): Widgets.TableElement; + interface IOptions {} - export function prompt(options?: Widgets.PromptOptions): Widgets.PromptElement; - export function question(options?: Widgets.QuestionOptions): Widgets.QuestionElement; - export function message(options?: Widgets.MessageOptions): Widgets.MessageElement; - export function loading(options?: Widgets.LoadingOptions): Widgets.LoadingElement; - export function log(options?: Widgets.LogOptions): Widgets.Log; + interface IHasOptions { + options: T; + } - export function progressbar(options?: Widgets.ProgressBarOptions): Widgets.ProgressBarElement; - export function terminal(options?: Widgets.TerminalOptions): Widgets.TerminalElement; + interface TputsOptions extends IOptions { + terminal?: string; + extended?: boolean; + debug?: boolean; + termcap?: string; + terminfoFile?: string; + terminfoPrefix?: string; + termcapFile?: string; + } - export function layout(options?: Widgets.LayoutOptions): Widgets.LayoutElement; + class Tput implements IHasOptions { + constructor(opts: TputsOptions); - export function escape(item: any): any; - export const colors: { - match: (hexColor: string) => string + /** + * Original options object. + */ + options: TputsOptions; + + debug: boolean; + padding: boolean; + extended: boolean; + printf: boolean; + termcap: string; + terminfoPrefix: string; + terminfoFile: string; + termcapFile: string; + error: Error; + terminal: string; + + setup(): void; + term(is: any): boolean; + readTerminfo(term: string): string; + parseTerminfo( + data: any, + file: string + ): { + header: { + dataSize: number; + headerSize: number; + magicNumber: boolean; + namesSize: number; + boolCount: number; + numCount: number; + strCount: number; + strTableSize: number; + extended: { + dataSize: number; + headerSize: number; + boolCount: number; + numCount: number; + strCount: number; + strTableSize: number; + lastStrTableOffset: number; + }; + }; + name: string; + names: string[]; + desc: string; + bools: any; + numbers: any; + strings: any; + }; + } + + interface IDestroyable { + destroy(): void; + } + + interface INodeOptions extends IOptions { + name?: string; + screen?: Screen; + parent?: Node; + children?: Node[]; + focusable?: boolean; + } + + type NodeEventType = + /** Received when node is added to a parent. */ + | "adopt" + /** Received when node is removed from it's current parent. */ + | "remove" + /** Received when node gains a new parent. */ + | "reparent" + /** Received when node is attached to the screen directly or somewhere in its ancestry. */ + | "attach" + /** Received when node is detached from the screen directly or somewhere in its ancestry. */ + | "detach"; + + abstract class Node extends EventEmitter implements IHasOptions, IDestroyable { + constructor(options: INodeOptions); + + focusable: boolean; + + /** + * Original options object. + */ + options: INodeOptions; + + /** + * An object for any miscellanous user data. + */ + data: { [index: string]: any }; + + /** + * An object for any miscellanous user data. + */ + _: { [index: string]: any }; + + /** + * An object for any miscellanous user data. + */ + $: { [index: string]: any }; + + /** + * Type of the node (e.g. box). + */ + type: string; + + /** + * Render index (document order index) of the last render call. + */ + index: number; + + /** + * Parent screen. + */ + screen: Screen; + + /** + * Parent node. + */ + parent: Node; + + /** + * Array of node's children. + */ + children: Node[]; + + /** + * Prepend a node to this node's children. + */ + prepend(node: Node): void; + + /** + * Append a node to this node's children. + */ + append(node: Node): void; + + /** + * Remove child node from node. + */ + remove(node: Node): void; + + /** + * Insert a node to this node's children at index i. + */ + insert(node: Node, index: number): void; + + /** + * Insert a node to this node's children before the reference node. + */ + insertBefore(node: Node, refNode: Node): void; + + /** + * Insert a node from node after the reference node. + */ + insertAfter(node: Node, refNode: Node): void; + + /** + * Remove node from its parent. + */ + detach(): void; + free(): void; + forDescendants(iter: (node: Node) => void, s: any): void; + forAncestors(iter: (node: Node) => void, s: any): void; + collectDescendants(s: any): void; + collectAncestors(s: any): void; + + /** + * Emit event for element, and recursively emit same event for all descendants. + */ + emitDescendants(type?: string, ...args: any[]): void; + emitAncestors(): void; + hasDescendant(target: Node): void; + hasAncestor(target: Node): boolean; + destroy(): void; + + /** + * Get user property with a potential default value. + */ + get(name: string, def: T): T; + + /** + * Set user property to value. + */ + set(name: string, value: any): void; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: NodeEventType, callback: (arg: Node) => void): this; + } + + type NodeScreenEventType = + /** + * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * focus protocol and focus needs to be passed to program.enableMouse(). + */ + | "focus" + /** + * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * focus protocol and focus needs to be passed to program.enableMouse(). + */ + | "blur" + /** + * Element was clicked (slightly smarter than mouseup). + */ + | "click" + | "element click" + | "element mouseover" + | "element mouseout" + | "element mouseup"; + + type NodeMouseEventType = + | "mouse" + | "mouseout" + | "mouseover" + | "mousedown" + | "mouseup" + | "mousewheel" + | "wheeldown" + | "wheelup" + | "mousemove"; + + type NodeGenericEventType = + /** Received on screen resize. */ + | "resize" + /** Received before render. */ + | "prerender" + /** Received on render. */ + | "render" + /** Received when the screen is destroyed (only useful when using multiple screens). */ + | "destroy" + /** Received when the element is moved. */ + | "move" + /** Received when element is shown. */ + | "show" + /** Received when element becomes hidden. */ + | "hide" + | "set content" + | "parsed content"; + + class NodeWithEvents extends Node { + /** + * Bind a keypress listener for a specific key. + */ + key(name: string | string[], listener: (ch: any, key: Events.IKeyEventArg) => void): void; + + /** + * Bind a keypress listener for a specific key once. + */ + onceKey(name: string, listener: (ch: any, key: Events.IKeyEventArg) => void): void; + + /** + * Remove a keypress listener for a specific key. + */ + unkey(name: string, listener: (ch: any, key: Events.IKeyEventArg) => void): void; + removeKey(name: string, listener: (ch: any, key: Events.IKeyEventArg) => void): void; + + on(event: string, listener: (ch: any, key: Events.IKeyEventArg) => void): this; + /** Received on mouse events. */ + on(event: NodeMouseEventType, callback: (arg: Events.IMouseEventArg) => void): this; + /** Received on key events. */ + on(event: "keypress", callback: (ch: string, key: Events.IKeyEventArg) => void): this; + on(event: NodeScreenEventType, callback: (arg: Screen) => void): this; + /** Received when blessed notices something untoward (output is not a tty, terminfo not found, etc). */ + on(event: "warning", callback: (text: string) => void): this; + on(event: NodeGenericEventType, callback: () => void): this; + } + + interface IScreenOptions extends INodeOptions { + /** + * The blessed Program to be associated with. Will be automatically instantiated if none is provided. + */ + program?: BlessedProgram; + + /** + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * however, it is more optimal for terminal rendering. + */ + smartCSR?: boolean; + + /** + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * but may cause flickering depending on what is on each side of the element. + */ + fastCSR?: boolean; + + /** + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at + * the cost of overhead within node. + */ + useBCE?: boolean; + + /** + * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). + */ + resizeTimeout?: number; + + /** + * The width of tabs within an element's content. + */ + tabSize?: number; + + /** + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * option. It may become default in the future). + */ + autoPadding?: boolean; + + cursor?: Types.TCursor; + + /** + * Create a log file. See log method. + */ + log?(...msg: any[]): void; + + /** + * Dump all output and input to desired file. Can be used together with log option if set as a boolean. + */ + dump?: string; + + /** + * Debug mode. Enables usage of the debug method. Also creates a debug console which will display when + * pressing F12. It will display all log and debug messages. + */ + debug?(...msg: string[]): void; + + /** + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * for creating a key that will always exit no matter whether the keys are locked. + */ + ignoreLocked?: boolean; + + /** + * Automatically "dock" borders with other elements instead of overlapping, depending on position + * (experimental). For example: These border-overlapped elements: + */ + dockBorders?: boolean; + + /** + * Normally, dockable borders will not dock if the colors or attributes are different. This option + * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. + */ + ignoreDockContrast?: boolean; + + /** + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * removes them from an element's content if iTerm2 is detected). + */ + fullUnicode?: boolean; + + /** + * Send focus events after mouse is enabled. + */ + sendFocus?: boolean; + + /** + * Display warnings (such as the output not being a TTY, similar to ncurses). + */ + warnings?: boolean; + + /** + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * If value is true unicode is forced. If value is false non-unicode is forced (default: null). + */ + forceUnicode?: boolean; + + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + */ + input?: stream.Writable; + + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + */ + output?: stream.Readable; + + /** + * The blessed Tput object (only available if you passed tput: true to the Program constructor.) + */ + tput?: Tput; + + /** + * Top of the focus history stack. + */ + focused?: BlessedElement; + + /** + * Width of the screen (same as program.cols). + */ + width?: Types.TPosition; + + /** + * Height of the screen (same as program.rows). + */ + height?: Types.TPosition; + + /** + * Same as screen.width. + */ + cols?: number; + + /** + * Same as screen.height. + */ + rows?: number; + + /** + * Relative top offset, always zero. + */ + top?: Types.TTopLeft; + + /** + * Relative left offset, always zero. + */ + left?: Types.TTopLeft; + + /** + * Relative right offset, always zero. + */ + right?: Types.TPosition; + + /** + * Relative bottom offset, always zero. + */ + bottom?: Types.TPosition; + + /** + * Absolute top offset, always zero. + */ + atop?: Types.TTopLeft; + + /** + * Absolute left offset, always zero. + */ + aleft?: Types.TTopLeft; + + /** + * Absolute right offset, always zero. + */ + aright?: Types.TPosition; + + /** + * Absolute bottom offset, always zero. + */ + abottom?: Types.TPosition; + + /** + * Whether the focused element grabs all keypresses. + */ + grabKeys?: any; + + /** + * Prevent keypresses from being received by any element. + */ + lockKeys?: boolean; + + /** + * The currently hovered element. Only set if mouse events are bound. + */ + hover?: any; + + /** + * Set or get terminal name. Set calls screen.setTerminal() internally. + */ + terminal?: string; + + /** + * Set or get window title. + */ + title?: string; + } + + class Screen extends NodeWithEvents implements IHasOptions { + constructor(opts: IScreenOptions); + + cleanSides: any; + + /** + * Original options object. + */ + options: IScreenOptions; + + /** + * The blessed Program to be associated with. Will be automatically instantiated if none is provided. + */ + program: BlessedProgram; + + /** + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * however, it is more optimal for terminal rendering. + */ + smartCSR: boolean; + + /** + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * but may cause flickering depending on what is on each side of the element. + */ + fastCSR: boolean; + + /** + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at + * the cost of overhead within node. + */ + useBCE: boolean; + + /** + * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). + */ + resizeTimeout: number; + + /** + * The width of tabs within an element's content. + */ + tabSize: number; + + /** + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * option. It may become default in the future). + */ + autoPadding: boolean; + + cursor: Types.TCursor; + + /** + * Dump all output and input to desired file. Can be used together with log option if set as a boolean. + */ + dump: string; + + /** + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * for creating a key that will always exit no matter whether the keys are locked. + */ + ignoreLocked: boolean; + + /** + * Automatically "dock" borders with other elements instead of overlapping, depending on position + * (experimental). For example: These border-overlapped elements: + */ + dockBorders: boolean; + + /** + * Normally, dockable borders will not dock if the colors or attributes are different. This option + * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. + */ + ignoreDockContrast: boolean; + + /** + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * removes them from an element's content if iTerm2 is detected). + */ + fullUnicode: boolean; + + /** + * Send focus events after mouse is enabled. + */ + sendFocus: boolean; + + /** + * Display warnings (such as the output not being a TTY, similar to ncurses). + */ + warnings: boolean; + + /** + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * If value is true unicode is forced. If value is false non-unicode is forced (default: null). + */ + forceUnicode: boolean; + + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + */ + input: stream.Writable; + + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + */ + output: stream.Readable; + + /** + * The blessed Tput object (only available if you passed tput: true to the Program constructor.) + */ + tput: Tput; + + /** + * Top of the focus history stack. + */ + focused: BlessedElement; + + /** + * Width of the screen (same as program.cols). + */ + width: Types.TPosition; + + /** + * Height of the screen (same as program.rows). + */ + height: Types.TPosition; + + /** + * Same as screen.width. + */ + cols: number; + + /** + * Same as screen.height. + */ + rows: number; + + /** + * Relative top offset, always zero. + */ + top: Types.TTopLeft; + + /** + * Relative left offset, always zero. + */ + left: Types.TTopLeft; + + /** + * Relative right offset, always zero. + */ + right: Types.TPosition; + + /** + * Relative bottom offset, always zero. + */ + bottom: Types.TPosition; + + /** + * Absolute top offset, always zero. + */ + atop: Types.TTopLeft; + + /** + * Absolute left offset, always zero. + */ + aleft: Types.TTopLeft; + + /** + * Absolute right offset, always zero. + */ + aright: Types.TPosition; + + /** + * Absolute bottom offset, always zero. + */ + abottom: Types.TPosition; + + /** + * Whether the focused element grabs all keypresses. + */ + grabKeys: any; + + /** + * Prevent keypresses from being received by any element. + */ + lockKeys: boolean; + + /** + * The currently hovered element. Only set if mouse events are bound. + */ + hover: any; + + /** + * Set or get terminal name. Set calls screen.setTerminal() internally. + */ + terminal: string; + + /** + * Set or get window title. + */ + title: string; + + /** + * Write string to the log file if one was created. + */ + log(...msg: any[]): void; + + /** + * Same as the log method, but only gets called if the debug option was set. + */ + debug(...msg: string[]): void; + + /** + * Allocate a new pending screen buffer and a new output screen buffer. + */ + alloc(): void; + + /** + * Reallocate the screen buffers and clear the screen. + */ + realloc(): void; + + /** + * Draw the screen based on the contents of the screen buffer. + */ + draw(start: number, end: number): void; + + /** + * Render all child elements, writing all data to the screen buffer and drawing the screen. + */ + render(): void; + + /** + * Clear any region on the screen. + */ + clearRegion(x1: number, x2: number, y1: number, y2: number): void; + + /** + * Fill any region with a character of a certain attribute. + */ + fillRegion(attr: string, ch: string, x1: number, x2: number, y1: number, y2: number): void; + + /** + * Focus element by offset of focusable elements. + */ + focusOffset(offset: number): any; + + /** + * Focus previous element in the index. + */ + focusPrevious(): void; + + /** + * Focus next element in the index. + */ + focusNext(): void; + + /** + * Push element on the focus stack (equivalent to screen.focused = el). + */ + focusPush(element: BlessedElement): void; + + /** + * Pop element off the focus stack. + */ + focusPop(): BlessedElement; + + /** + * Save the focused element. + */ + saveFocus(): BlessedElement; + + /** + * Restore the saved focused element. + */ + restoreFocus(): BlessedElement; + + /** + * "Rewind" focus to the last visible and attached element. + */ + rewindFocus(): BlessedElement; + + /** + * Spawn a process in the foreground, return to blessed app after exit. + */ + spawn(file: string, args: string[], options: NodeChildProcessExecOptions): child_process.ChildProcess; + + /** + * Spawn a process in the foreground, return to blessed app after exit. Executes callback on error or exit. + */ + exec( + file: string, + args: string[], + options: NodeChildProcessExecOptions, + callback: (...args: any[]) => void + ): child_process.ChildProcess; + + /** + * Read data from text editor. + */ + readEditor(options: any, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + readEditor(callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + + /** + * Set effects based on two events and attributes. + */ + setEffects(el: BlessedElement, fel: BlessedElement, over: any, out: any, effects: any, temp: any): void; + + /** + * Insert a line into the screen (using csr: this bypasses the output buffer). + */ + insertLine(n: number, y: number, top: number, bottom: number): void; + + /** + * Delete a line from the screen (using csr: this bypasses the output buffer). + */ + deleteLine(n: number, y: number, top: number, bottom: number): void; + + /** + * Insert a line at the bottom of the screen. + */ + insertBottom(top: number, bottom: number): void; + + /** + * Insert a line at the top of the screen. + */ + insertTop(top: number, bottom: number): void; + + /** + * Delete a line at the bottom of the screen. + */ + deleteBottom(top: number, bottom: number): void; + + /** + * Delete a line at the top of the screen. + */ + deleteTop(top: number, bottom: number): void; + + /** + * Enable mouse events for the screen and optionally an element (automatically called when a form of + * on('mouse') is bound). + */ + enableMouse(el?: BlessedElement): void; + + /** + * Enable keypress events for the screen and optionally an element (automatically called when a form of + * on('keypress') is bound). + */ + enableKeys(el?: BlessedElement): void; + + /** + * Enable key and mouse events. Calls bot enableMouse and enableKeys. + */ + enableInput(el?: BlessedElement): void; + + /** + * Attempt to copy text to clipboard using iTerm2's proprietary sequence. Returns true if successful. + */ + copyToClipboard(text: string): void; + + /** + * Attempt to change cursor shape. Will not work in all terminals (see artificial cursors for a solution + * to this). Returns true if successful. + */ + cursorShape(shape: boolean, blink: boolean): any; + + /** + * Attempt to change cursor color. Returns true if successful. + */ + cursorColor(color: string): void; + + /** + * Attempt to reset cursor. Returns true if successful. + */ + cursorReset(): void; + + /** + * Take an SGR screenshot of the screen within the region. Returns a string containing only + * characters and SGR codes. Can be displayed by simply echoing it in a terminal. + */ + screenshot(xi: number, xl: number, yi: number, yl: number): string; + screenshot(): void; + + /** + * Destroy the screen object and remove it from the global list. Also remove all global events relevant + * to the screen object. If all screen objects are destroyed, the node process is essentially reset + * to its initial state. + */ + destroy(): void; + + /** + * Reset the terminal to term. Reloads terminfo. + */ + setTerminal(term: string): void; + } + + interface Padding { + left?: number; + right?: number; + top?: number; + bottom?: number; + } + + class PositionCoords { + xi: number; + xl: number; + yi: number; + yl: number; + } + + interface Position { + left: number | string; + right: number | string; + top: number | string; + bottom: number | string; + } + + interface Border { + /** + * Type of border (line or bg). bg by default. + */ + type?: "line" | "bg"; + + /** + * Character to use if bg type, default is space. + */ + ch?: string; + + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg?: number; + fg?: number; + + /** + * Border attributes. + */ + bold?: string; + underline?: string; + } + + interface ElementOptions extends INodeOptions { + tags?: boolean; + + fg?: string; + bg?: string; + bold?: string; + underline?: string; + + style?: any; + + /** + * Border object, see below. + */ + border?: Border | "line" | "bg"; + + /** + * Element's text content. + */ + content?: string; + + /** + * Element is clickable. + */ + clickable?: boolean; + + /** + * Element is focusable and can receive key input. + */ + input?: boolean; + keyable?: boolean; + + /** + * Element is focused. + */ + focused?: BlessedElement; + + /** + * Whether the element is hidden. + */ + hidden?: boolean; + + /** + * A simple text label for the element. + */ + label?: string; + + /** + * A floating text label for the element which appears on mouseover. + */ + hoverText?: string; + + /** + * Text alignment: left, center, or right. + */ + align?: "left" | "center" | "right"; + + /** + * Vertical text alignment: top, middle, or bottom. + */ + valign?: "top" | "middle" | "bottom"; + + /** + * Shrink/flex/grow to content and child elements. Width/height during render. + */ + shrink?: boolean; + + /** + * Amount of padding on the inside of the element. Can be a number or an object containing + * the properties: left, right, top, and bottom. + */ + padding?: number | Padding; + + top?: Types.TTopLeft; + left?: Types.TTopLeft; + right?: Types.TPosition; + bottom?: Types.TPosition; + + /** + * Width/height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). + * Percentages can also have offsets (50%+1, 50%-1). + */ + width?: number | string; + + /** + * Offsets of the element relative to its parent. Can be a number, percentage (0-100%), or + * keyword (center). right and bottom do not accept keywords. Percentages can also have + * offsets (50%+1, 50%-1). + */ + height?: number | string; + + /** + * Can contain the above options. + */ + position?: Position; + + /** + * Whether the element is scrollable or not. + */ + scrollable?: boolean; + + /** + * Background character (default is whitespace ). + */ + ch?: string; + + /** + * Allow the element to be dragged with the mouse. + */ + draggable?: boolean; + + /** + * Draw a translucent offset shadow behind the element. + */ + shadow?: boolean; + } + + interface Coords { + xl: number; + xi: number; + yl: number; + yi: number; + base: number; + _contentEnd: { x: number; y: number }; + notop: Types.TTopLeft; + noleft: Types.TTopLeft; + noright: Types.TPosition; + nobot: Types.TPosition; + } + + interface LabelOptions { + text: string; + side: Types.TAlign; + } + + // TODO: scrollable - Note: If the scrollable option is enabled, Element inherits all methods from ScrollableBox. + abstract class BlessedElement extends NodeWithEvents implements IHasOptions { + constructor(opts: ElementOptions); + + /** + * Original options object. + */ + options: ElementOptions; + + /** + * Name of the element. Useful for form submission. + */ + name: string; + + /** + * Border object. + */ + border: Border; + + style: any; + position: Position; + content: string; + hidden: boolean; + visible: boolean; + detached: boolean; + + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg: number; + fg: number; + + /** + * Border attributes. + */ + bold: string; + underline: string; + + /** + * Calculated width. + */ + width: number | string; + + /** + * Calculated height. + */ + height: number | string; + + /** + * Calculated relative top offset. + */ + top: Types.TTopLeft; + + /** + * Calculated relative left offset. + */ + left: Types.TTopLeft; + + /** + * Calculated relative right offset. + */ + right: Types.TPosition; + + /** + * Calculated relative bottom offset. + */ + bottom: Types.TPosition; + + /** + * Calculated absolute top offset. + */ + atop: Types.TTopLeft; + + /** + * Calculated absolute left offset. + */ + aleft: Types.TTopLeft; + + /** + * Calculated absolute right offset. + */ + aright: Types.TPosition; + + /** + * Calculated absolute bottom offset. + */ + abottom: Types.TPosition; + + /** + * Whether the element is draggable. Set to true to allow dragging. + */ + draggable: boolean; + + itop: Types.TTopLeft; + ileft: Types.TTopLeft; + iheight: Types.TPosition; + iwidth: Types.TPosition; + + /** + * Calculated relative top offset. + */ + rtop: Types.TTopLeft; + + /** + * Calculated relative left offset. + */ + rleft: Types.TTopLeft; + + /** + * Calculated relative right offset. + */ + rright: Types.TPosition; + + /** + * Calculated relative bottom offset. + */ + rbottom: Types.TPosition; + + lpos: PositionCoords; + + /** + * Write content and children to the screen buffer. + */ + render(): Coords; + + /** + * Hide element. + */ + hide(): void; + + /** + * Show element. + */ + show(): void; + + /** + * Toggle hidden/shown. + */ + toggle(): void; + + /** + * Focus element. + */ + focus(): void; + + /** + * Same asel.on('screen', ...) except this will automatically keep track of which listeners + * are bound to the screen object. For use with removeScreenEvent(), free(), and destroy(). + */ + onScreenEvent(type: string, handler: (...args: any[]) => void): void; + + /** + * Same asel.removeListener('screen', ...) except this will automatically keep track of which + * listeners are bound to the screen object. For use with onScreenEvent(), free(), and destroy(). + */ + removeScreenEvent(type: string, handler: (...args: any[]) => void): void; + + /** + * Free up the element. Automatically unbind all events that may have been bound to the screen + * object. This prevents memory leaks. For use with onScreenEvent(), removeScreenEvent(), + * and destroy(). + */ + free(): void; + + /** + * Same as the detach() method, except this will automatically call free() and unbind any screen + * events to prevent memory leaks. for use with onScreenEvent(), removeScreenEvent(), and free(). + */ + destroy(): void; + + /** + * Set the z-index of the element (changes rendering order). + */ + setIndex(z: number): void; + + /** + * Put the element in front of its siblings. + */ + setFront(): void; + + /** + * Put the element in back of its siblings. + */ + setBack(): void; + + /** + * text/options - Set the label text for the top-left corner. Example options: {text:'foo',side:'left'} + */ + setLabel(arg: string | LabelOptions): void; + + /** + * Remove the label completely. + */ + removeLabel(): any; + + /** + * text/options - Set a hover text box to follow the cursor. Similar to the "title" DOM attribute + * in the browser. Example options: {text:'foo'} + */ + setHover(arg: string | LabelOptions): void; + + /** + * Remove the hover label completely. + */ + removeHover(): void; + + /** + * Enable mouse events for the element (automatically called when a form of on('mouse') is bound). + */ + enableMouse(): void; + + /** + * Enable keypress events for the element (automatically called when a form of on('keypress') is bound). + */ + enableKeys(): void; + + /** + * Enable key and mouse events. Calls bot enableMouse and enableKeys. + */ + enableInput(): void; + + /** + * Enable dragging of the element. + */ + enableDrag(): void; + + /** + * Disable dragging of the element. + */ + disableDrag(): void; + + /** + * Take an SGR screenshot of the screen within the region. Returns a string containing only + * characters and SGR codes. Can be displayed by simply echoing it in a terminal. + */ + screenshot(xi: number, xl: number, yi: number, yl: number): string; + screenshot(): void; + + /* + Content Methods + + Methods for dealing with text content, line by line. Useful for writing a text editor, + irc client, etc. + + Note: All of these methods deal with pre-aligned, pre-wrapped text. If you use deleteTop() + on a box with a wrapped line at the top, it may remove 3-4 "real" lines (rows) depending + on how long the original line was. + + The lines parameter can be a string or an array of strings. The line parameter must + be a string. + */ + + /** + * Set the content. Note: When text is input, it will be stripped of all non-SGR + * escape codes, tabs will be replaced with 8 spaces, and tags will be replaced + * with SGR codes (if enabled). + */ + setContent(text: string): void; + + /** + * Return content, slightly different from el.content. Assume the above formatting. + */ + getContent(): string; + + /** + * Similar to setContent, but ignore tags and remove escape codes. + */ + setText(text: string): void; + + /** + * Similar to getContent, but return content with tags and escape codes removed. + */ + getText(): string; + + /** + * Insert a line into the box's content. + */ + insertLine(i: number, lines: string | string[]): void; + + /** + * Delete a line from the box's content. + */ + deleteLine(i: number): void; + + /** + * Get a line from the box's content. + */ + getLine(i: number): string; + + /** + * Get a line from the box's content from the visible top. + */ + getBaseLine(i: number): string; + + /** + * Set a line in the box's content. + */ + setLine(i: number, line: string | string[]): void; + + /** + * Set a line in the box's content from the visible top. + */ + setBaseLine(i: number, line: string | string[]): void; + + /** + * Clear a line from the box's content. + */ + clearLine(i: number): void; + + /** + * Clear a line from the box's content from the visible top. + */ + clearBaseLine(i: number): void; + + /** + * Insert a line at the top of the box. + */ + insertTop(lines: string | string[]): void; + + /** + * Insert a line at the bottom of the box. + */ + insertBottom(lines: string | string[]): void; + + /** + * Delete a line at the top of the box. + */ + deleteTop(): void; + + /** + * Delete a line at the bottom of the box. + */ + deleteBottom(): void; + + /** + * Unshift a line onto the top of the content. + */ + unshiftLine(lines: string | string[]): void; + + /** + * Shift a line off the top of the content. + */ + shiftLine(i: number): void; + + /** + * Push a line onto the bottom of the content. + */ + pushLine(lines: string | string[]): void; + + /** + * Pop a line off the bottom of the content. + */ + popLine(i: number): string; + + /** + * An array containing the content lines. + */ + getLines(): string[]; + + /** + * An array containing the lines as they are displayed on the screen. + */ + getScreenLines(): string[]; + + /** + * Get a string's displayed width, taking into account double-width, surrogate pairs, + * combining characters, tags, and SGR escape codes. + */ + strWidth(text: string): string; + } + + interface ScrollableBoxOptions extends ElementOptions { + /** + * A limit to the childBase. Default is Infinity. + */ + baseLimit?: number; + + /** + * A option which causes the ignoring of childOffset. This in turn causes the + * childBase to change every time the element is scrolled. + */ + alwaysScroll?: boolean; + + /** + * Object enabling a scrollbar. + * Style of the scrollbar track if present (takes regular style options). + */ + scrollbar?: { style?: any; track?: any; ch?: string }; + } + + interface ScrollableTextOptions extends ScrollableBoxOptions { + /** + * Whether to enable automatic mouse support for this element. + * Use pre-defined mouse events (right-click for editor). + */ + mouse?: boolean | (() => void); + + /** + * Use pre-defined keys (i or enter for insert, e for editor, C-e for editor while inserting). + */ + keys?: string | string[] | boolean; + + /** + * Use vi keys with the keys option. + */ + vi?: boolean; + } + + interface BoxOptions extends ScrollableTextOptions { + bindings?: any; + } + + /** + * DEPRECATED - Use Box with the scrollable option instead. A box with scrollable content. + */ + class ScrollableBoxElement extends BlessedElement { + /** + * The offset of the top of the scroll content. + */ + childBase: number; + + /** + * The offset of the chosen item/line. + */ + childOffset: number; + + /** + * Scroll the content by a relative offset. + */ + scroll(offset: number, always?: boolean): void; + + /** + * Scroll the content to an absolute index. + */ + scrollTo(index: number): void; + + /** + * Same as scrollTo. + */ + setScroll(index: number): void; + + /** + * Set the current scroll index in percentage (0-100). + */ + setScrollPerc(perc: number): void; + + /** + * Get the current scroll index in lines. + */ + getScroll(): number; + + /** + * Get the actual height of the scrolling area. + */ + getScrollHeight(): number; + + /** + * Get the current scroll index in percentage. + */ + getScrollPerc(): number; + + /** + * Reset the scroll index to its initial state. + */ + resetScroll(): void; + + on(event: string, listener: (...args: any[]) => void): this; + + /** + * Received when the element is scrolled. + */ + on(event: "scroll", callback: () => void): this; + } + + /** + * DEPRECATED - Use Box with the scrollable and alwaysScroll options instead. + * A scrollable text box which can display and scroll text, as well as handle + * pre-existing newlines and escape codes. + */ + class ScrollableTextElement extends ScrollableBoxElement {} + + /** + * A box element which draws a simple box containing content or other elements. + */ + class BoxElement extends ScrollableTextElement implements IHasOptions { + constructor(opts: BoxOptions); + + /** + * Original options object. + */ + options: BoxOptions; + } + + interface TextOptions extends ElementOptions { + /** + * Fill the entire line with chosen bg until parent bg ends, even if there + * is not enough text to fill the entire width. + */ + fill?: boolean; + + /** + * Text alignment: left, center, or right. + */ + align?: Types.TAlign; + } + + /** + * An element similar to Box, but geared towards rendering simple text elements. + */ + class TextElement extends BlessedElement implements IHasOptions { + constructor(opts: TextOptions); + + /** + * Original options object. + */ + options: TextOptions; + } + + /** + * A simple line which can be line or bg styled. + */ + interface LineOptions extends BoxOptions { + /** + * Can be vertical or horizontal. + */ + orientation?: "vertical" | "horizontal"; + + /** + * Treated the same as a border object. (attributes can be contained in style). + */ + type?: string; + bg?: string; + fg?: string; + ch?: string; + } + + /** + * A simple line which can be line or bg styled. + */ + class LineElement extends BoxElement implements IHasOptions { + constructor(opts: LineOptions); + + /** + * Original options object. + */ + options: LineOptions; + } + + interface BigTextOptions extends BoxOptions { + /** + * bdf->json font file to use (see ttystudio for instructions on compiling BDFs to JSON). + */ + font?: string; + + /** + * bdf->json bold font file to use (see ttystudio for instructions on compiling BDFs to JSON). + */ + fontBold?: string; + + /** + * foreground character. (default: ' ') + */ + fch?: string; + } + + /** + * A box which can render content drawn as 8x14 cell characters using the terminus font. + */ + class BigTextElement extends BoxElement implements IHasOptions { + constructor(opts: BigTextOptions); + + /** + * Original options object. + */ + options: BigTextOptions; + } + + interface ListElementStyle { + selected?: any; + item?: any; + } + + interface ListOptions extends BoxOptions { + /** + * Style for a selected item. Style for an unselected item. + */ + style?: TStyle; + + /** + * An array of strings which become the list's items. + */ + items?: string[]; + + /** + * A function that is called when vi mode is enabled and the key / is pressed. This function accepts a + * callback function which should be called with the search string. The search string is then used to + * jump to an item that is found in items. + */ + search?(err: any, value?: string): void; + + /** + * Whether the list is interactive and can have items selected (Default: true). + */ + interactive?: boolean; + + /** + * Whether to automatically override tags and invert fg of item when selected (Default: true). + */ + invertSelected?: boolean; + } + + type ListElementEventType = + /** List was canceled (when esc is pressed with the keys option). */ + | "cancel" + /** Either a select or a cancel event was received. */ + | "action" + | "create item" + | "add item" + | "remove item" + | "insert item" + | "set items"; + + class ListElement extends BoxElement implements IHasOptions> { + constructor(opts: ListOptions); + + /** + * Original options object. + */ + options: ListOptions; + + /** + * Add an item based on a string. + */ + add(text: string): void; + + /** + * Add an item based on a string. + */ + addItem(text: string): void; + + /** + * Removes an item from the list. Child can be an element, index, or string. + */ + removeItem(child: BlessedElement): BlessedElement; + + /** + * Push an item onto the list. + */ + pushItem(child: BlessedElement): number; + + /** + * Pop an item off the list. + */ + popItem(): BlessedElement; + + /** + * Unshift an item onto the list. + */ + unshiftItem(child: BlessedElement): number; + + /** + * Shift an item off the list. + */ + shiftItem(): BlessedElement; + + /** + * Inserts an item to the list. Child can be an element, index, or string. + */ + insertItem(i: number, child: BlessedElement): void; + + /** + * Returns the item element. Child can be an element, index, or string. + */ + getItem(child: BlessedElement): BlessedElement; + + /** + * Set item to content. + */ + setItem(child: BlessedElement, content: BlessedElement | string): void; + + /** + * Remove and insert items to the list. + */ + spliceItem(i: number, n: number, ...items: BlessedElement[]): void; + + /** + * Clears all items from the list. + */ + clearItems(): void; + + /** + * Sets the list items to multiple strings. + */ + setItems(items: BlessedElement[]): void; + + /** + * Returns the item index from the list. Child can be an element, index, or string. + */ + getItemIndex(child: BlessedElement): number; + + /** + * Select an index of an item. + */ + select(index: number): void; + + /** + * Select item based on current offset. + */ + move(offset: number): void; + + /** + * Select item above selected. + */ + up(amount: number): void; + + /** + * Select item below selected. + */ + down(amount: number): void; + + /** + * Show/focus list and pick an item. The callback is executed with the result. + */ + pick(callback: () => void): void; + + /** + * Find an item based on its text content. + */ + fuzzyFind(arg: string | RegExp | (() => void)): void; + + on(event: string, listener: (...args: any[]) => void): this; + /** Received when an item is selected. */ + on(event: "select", callback: (item: BoxElement, index: number) => void): this; + on(event: ListElementEventType, callback: () => void): this; + on(event: "select item", callback: (item: BlessedElement, index: number) => void): this; + } + + interface FileManagerOptions extends ListOptions { + /** + * Current working directory. + */ + cwd?: string; + } + + class FileManagerElement extends ListElement implements IHasOptions { + constructor(opts: FileManagerOptions); + + /** + * Original options object. + */ + options: FileManagerOptions; + + /** + * Current working directory. + */ + cwd: string; + + /** + * Refresh the file list (perform a readdir on cwd and update the list items). + */ + refresh(cwd: string, callback: () => void): void; + refresh(callback?: () => void): void; + + /** + * Pick a single file and return the path in the callback. + */ + pick(cwd: string, callback: () => void): void; + pick(callback: () => void): void; + + /** + * Reset back to original cwd. + */ + reset(cwd: string, callback: () => void): void; + reset(callback?: () => void): void; + + on(event: string, listener: (...args: any[]) => void): this; + /** Received when an item is selected. */ + on(event: "cd", callback: (file: string, cwd: string) => void): this; + /** Received when an item is selected. */ + on(event: "file", callback: (file: string) => void): this; + on(event: "error", callback: (err: any, file: string) => void): this; + on(event: "refresh", callback: () => void): this; + } + + interface StyleListTable extends ListElementStyle { + /** + * Header style. + */ + header?: any; + + /** + * Cell style. + */ + cell?: any; + } + + interface ListTableOptions extends ListOptions { + /** + * Array of array of strings representing rows. + */ + rows?: string[]; + data?: string[][]; + + /** + * Spaces to attempt to pad on the sides of each cell. 2 by default: one space on each side + * (only useful if the width is shrunken). + */ + pad?: number; + + /** + * Do not draw inner cells. + */ + noCellBorders?: boolean; + + style?: StyleListTable; + } + + class ListTableElement extends ListElement implements IHasOptions { + constructor(opts: ListTableOptions); + + /** + * Original options object. + */ + options: ListTableOptions; + + /** + * Set rows in table. Array of arrays of strings. + * @example: + * + * table.setData([ + * [ 'Animals', 'Foods' ], + * [ 'Elephant', 'Apple' ], + * [ 'Bird', 'Orange' ] + * ]); + */ + setRows(rows: string[][]): void; + + /** + * Set rows in table. Array of arrays of strings. + * @example: + * + * table.setData([ + * [ 'Animals', 'Foods' ], + * [ 'Elephant', 'Apple' ], + * [ 'Bird', 'Orange' ] + * ]); + */ + setData(rows: string[][]): void; + } + + interface ListbarOptions extends BoxOptions { + style?: ListElementStyle; + + /** + * Set buttons using an object with keys as titles of buttons, containing of objects + * containing keys of keys and callback. + */ + commands: Types.ListbarCommand[]; + items: Types.ListbarCommand[]; + + /** + * Automatically bind list buttons to keys 0-9. + */ + autoCommandKeys: boolean; + } + + class ListbarElement extends BoxElement implements IHasOptions { + constructor(opts: ListbarOptions); + + /** + * Original options object. + */ + options: ListbarOptions; + + /** + * Set commands (see commands option above). + */ + setItems(commands: Types.ListbarCommand[]): void; + + /** + * Append an item to the bar. + */ + add(item: Types.ListbarCommand, callback: () => void): void; + + /** + * Append an item to the bar. + */ + addItem(item: Types.ListbarCommand, callback: () => void): void; + + /** + * Append an item to the bar. + */ + appendItem(item: Types.ListbarCommand, callback: () => void): void; + + /** + * Select an item on the bar. + */ + select(offset: number): void; + + /** + * Remove item from the bar. + */ + removeItem(child: BlessedElement): void; + + /** + * Move relatively across the bar. + */ + move(offset: number): void; + + /** + * Move left relatively across the bar. + */ + moveLeft(offset: number): void; + + /** + * Move right relatively across the bar. + */ + moveRight(offset: number): void; + + /** + * Select button and execute its callback. + */ + selectTab(index: number): void; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "set items" | "remove item" | "select tab", callback: () => void): this; + } + + interface FormOptions extends BoxOptions { + /** + * Allow default keys (tab, vi keys, enter). + */ + keys?: any; + + /** + * Allow vi keys. + */ + vi?: boolean; + } + + class FormElement extends BoxElement implements IHasOptions { + constructor(opts: FormOptions); + + /** + * Original options object. + */ + options: FormOptions; + + /** + * Last submitted data. + */ + submission: TFormData; + + /** + * Focus next form element. + */ + focusNext(): void; + + /** + * Focus previous form element. + */ + focusPrevious(): void; + + /** + * Submit the form. + */ + submit(): void; + + /** + * Discard the form. + */ + cancel(): void; + + /** + * Clear the form. + */ + reset(): void; + + on(event: string, listener: (...args: any[]) => void): this; + /** Form is submitted. Receives a data object. */ + on(event: "submit", callback: (out: TFormData) => void): this; + on(event: "cancel" | "reset", callback: () => void): this; + } + + interface InputOptions extends BoxOptions {} + + abstract class InputElement extends BoxElement { + constructor(opts: InputOptions); + } + + /** + * A box which allows multiline text input. + */ + interface TextareaOptions extends InputOptions { + /** + * Call readInput() when the element is focused. Automatically unfocus. + */ + inputOnFocus?: boolean; + } + + type TextareaElementEventType = + /** Value is an error. */ + | "error" + /** Value is submitted (enter). */ + | "submit" + /** Value is discared (escape). */ + | "cancel" + /** Either submit or cancel. */ + | "action"; + + class TextareaElement extends InputElement implements IHasOptions { + constructor(opts: TextareaOptions); + + /** + * Original options object. + */ + options: TextareaOptions; + + /** + * The input text. read-only. + */ + value: string; + + /** + * Submit the textarea (emits submit). + */ + submit(): void; + + /** + * Cancel the textarea (emits cancel). + */ + cancel(): void; + + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + readInput(callback?: (err: any, value?: string) => void): void; + + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + input(callback: (err: any, value?: string) => void): void; + + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + setInput(callback: (err: any, value?: string) => void): void; + + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + readEditor(callback: (err: any, value?: string) => void): void; + + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + editor(callback: (err: any, value?: string) => void): void; + + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + setEditor(callback: (err: any, value?: string) => void): void; + + /** + * The same as this.value, for now. + */ + getValue(): string; + + /** + * Clear input. + */ + clearValue(): void; + + /** + * Set value. + */ + setValue(text: string): void; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: TextareaElementEventType, callback: (err: any) => void): this; + } + + interface TextboxOptions extends TextareaOptions { + /** + * Completely hide text. + */ + secret?: boolean; + + /** + * Replace text with asterisks (*). + */ + censor?: boolean; + } + + class TextboxElement extends TextareaElement implements IHasOptions { + constructor(opts: TextboxOptions); + + /** + * Original options object. + */ + options: TextboxOptions; + + /** + * Completely hide text. + */ + secret: boolean; + + /** + * Replace text with asterisks (*). + */ + censor: boolean; + } + + interface ButtonOptions extends BoxOptions {} + + class ButtonElement extends InputElement implements IHasOptions { + constructor(opts: ButtonOptions); + + /** + * Original options object. + */ + options: ButtonOptions; + + /** + * Press button. Emits press. + */ + press(): void; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "press", callback: () => void): this; + } + + interface CheckboxOptions extends BoxOptions { + /** + * whether the element is checked or not. + */ + checked?: boolean; + + /** + * enable mouse support. + */ + mouse?: boolean; + } + + /** + * A checkbox which can be used in a form element. + */ + class CheckboxElement extends InputElement implements IHasOptions { + constructor(options?: CheckboxOptions); + + /** + * Original options object. + */ + options: CheckboxOptions; + + /** + * the text next to the checkbox (do not use setcontent, use `check.text = ''`). + */ + text: string; + + /** + * whether the element is checked or not. + */ + checked: boolean; + + /** + * same as `checked`. + */ + value: boolean; + + /** + * check the element. + */ + check(): void; + + /** + * uncheck the element. + */ + uncheck(): void; + + /** + * toggle checked state. + */ + toggle(): void; + } + + interface RadioSetOptions extends BoxOptions {} + + /** + * An element wrapping RadioButtons. RadioButtons within this element will be mutually exclusive + * with each other. + */ + abstract class RadioSetElement extends BoxElement { + constructor(opts: RadioSetOptions); + } + + interface RadioButtonOptions extends BoxOptions {} + + /** + * A radio button which can be used in a form element. + */ + abstract class RadioButtonElement extends CheckboxElement { + constructor(opts: RadioButtonOptions); + } + + interface PromptOptions extends BoxOptions {} + + /** + * A prompt box containing a text input, okay, and cancel buttons (automatically hidden). + */ + class PromptElement extends BoxElement implements IHasOptions { + constructor(opts: PromptOptions); + + options: PromptOptions; + + /** + * Show the prompt and wait for the result of the textbox. Set text and initial value. + */ + input(text: string, value: string, callback: (err: any, value: string) => void): void; + setInput(text: string, value: string, callback: (err: any, value: string) => void): void; + readInput(text: string, value: string, callback: (err: any, value: string) => void): void; + } + + interface QuestionOptions extends BoxOptions {} + + /** + * A question box containing okay and cancel buttons (automatically hidden). + */ + class QuestionElement extends BoxElement implements IHasOptions { + constructor(opts: QuestionOptions); + + options: QuestionOptions; + + /** + * Ask a question. callback will yield the result. + */ + ask(question: string, callback: (err: any, value: string) => void): void; + } + + interface MessageOptions extends BoxOptions {} + + /** + * A box containing a message to be displayed (automatically hidden). + */ + class MessageElement extends BoxElement implements IHasOptions { + constructor(opts: MessageOptions); + + options: MessageOptions; + + /** + * Display a message for a time (default is 3 seconds). Set time to 0 for a + * perpetual message that is dismissed on keypress. + */ + log(text: string, time: number, callback: (err: any) => void): void; + log(text: string, callback: (err: any) => void): void; + display(text: string, time: number, callback: (err: any) => void): void; + display(text: string, callback: (err: any) => void): void; + + /** + * Display an error in the same way. + */ + error(text: string, time: number, callback: () => void): void; + error(text: string, callback: () => void): void; + } + + interface LoadingOptions extends BoxOptions {} + + /** + * A box with a spinning line to denote loading (automatically hidden). + */ + class LoadingElement extends BoxElement implements IHasOptions { + constructor(opts: LoadingOptions); + + options: LoadingOptions; + + /** + * Display the loading box with a message. Will lock keys until stop is called. + */ + load(text: string): void; + + /** + * Hide loading box. Unlock keys. + */ + stop(): void; + } + + interface ProgressBarOptions extends BoxOptions { + /** + * can be `horizontal` or `vertical`. + */ + orientation: string; + + /** + * the character to fill the bar with (default is space). + */ + pch: string; + + /** + * the amount filled (0 - 100). + */ + filled: number; + + /** + * same as `filled`. + */ + value: number; + + /** + * enable key support. + */ + keys: boolean; + + /** + * enable mouse support. + */ + mouse: boolean; + } + + /** + * A progress bar allowing various styles. This can also be used as a form input. + */ + class ProgressBarElement extends InputElement implements IHasOptions { + constructor(options?: ProgressBarOptions); + + options: ProgressBarOptions; + + /** + * progress the bar by a fill amount. + */ + progress(amount: number): void; + + /** + * set progress to specific amount. + */ + setProgress(amount: number): void; + + /** + * reset the bar. + */ + reset(): void; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "reset" | "complete", callback: () => void): this; + } + + interface LogOptions extends ScrollableTextOptions { + /** + * amount of scrollback allowed. default: Infinity. + */ + scrollback?: number; + + /** + * scroll to bottom on input even if the user has scrolled up. default: false. + */ + scrollOnInput?: boolean; + } + + /** + * A log permanently scrolled to the bottom. + */ + class Log extends ScrollableTextElement implements IHasOptions { + constructor(options?: LogOptions); + + options: LogOptions; + + /** + * amount of scrollback allowed. default: Infinity. + */ + scrollback: number; + + /** + * scroll to bottom on input even if the user has scrolled up. default: false. + */ + scrollOnInput: boolean; + + /** + * add a log line. + */ + log(text: string): void; + + /** + * add a log line. + */ + add(text: string): void; + } + + interface TableOptions extends BoxOptions { + /** + * array of array of strings representing rows (same as `data`). + */ + rows?: string[][]; + + /** + * array of array of strings representing rows (same as `rows`). + */ + data?: string[][]; + + /** + * spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). + */ + pad?: number; + + /** + * do not draw inner cells. + */ + noCellBorders?: boolean; + + /** + * fill cell borders with the adjacent background color. + */ + fillCellBorders?: boolean; + } + + /** + * A stylized table of text elements. + */ + class TableElement extends BoxElement implements IHasOptions { + constructor(opts: TableOptions); + + options: TableOptions; + + /** + * set rows in table. array of arrays of strings. + */ + setData(rows: string[][]): void; + + /** + * set rows in table. array of arrays of strings. + */ + setRows(rows: string[][]): void; + } + + interface TerminalOptions extends BoxOptions { + /** + * handler for input data. + */ + handler?(userInput: Buffer): void; + + /** + * name of shell. $SHELL by default. + */ + shell?: string; + + /** + * args for shell. + */ + args?: any; + + /** + * can be line, underline, and block. + */ + cursor?: "line" | "underline" | "block"; + + terminal?: string; + + /** + * Object for process env. + */ + env?: any; + } + + class TerminalElement extends BoxElement implements IHasOptions { + constructor(opts: TerminalOptions); + + options: TerminalOptions; + + /** + * reference to the headless term.js terminal. + */ + term: any; + + /** + * reference to the pty.js pseudo terminal. + */ + pty: any; + + /** + * write data to the terminal. + */ + write(data: string): void; + + /** + * nearly identical to `element.screenshot`, however, the specified region includes the terminal's + * _entire_ scrollback, rather than just what is visible on the screen. + */ + screenshot(xi?: number, xl?: number, yi?: number, yl?: number): string; + } + + interface ImageOptions extends BoxOptions { + /** + * path to image. + */ + file: string; + + /** + * path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the + * entire disk for the binary. + */ + type: "ansi" | "overlay" | "w3m"; + } + + /** + * Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. + * X11 required: works in xterm, urxvt, and possibly other terminals. + */ + class ImageElement extends BoxElement implements IHasOptions { + constructor(options?: ImageOptions); + + options: ImageOptions; + } + + interface ANSIImageOptions extends BoxOptions { + /** + * URL or path to PNG/GIF file. Can also be a buffer. + */ + file: string; + + /** + * Scale cellmap down (0-1.0) from its original pixel width/height (Default: 1.0). + */ + scale: number; + + /** + * This differs from other element's width or height in that only one + * of them is needed: blessed will maintain the aspect ratio of the image + * as it scales down to the proper number of cells. NOTE: PNG/GIF's are + * always automatically shrunken to size (based on scale) if a width or + * height is not given. + */ + width: number | string; + height: number | string; + + /** + * Add various "density" ASCII characters over the rendering to give the + * image more detail, similar to libcaca/libcucul (the library mplayer uses + * to display videos in the terminal). + */ + ascii: string; + + /** + * Whether to animate if the image is an APNG/animating GIF. If false, only + * display the first frame or IDAT (Default: true). + */ + animate: boolean; + + /** + * Set the speed of animation. Slower: 0.0-1.0. Faster: 1-1000. It cannot go + * faster than 1 frame per millisecond, so 1000 is the fastest. (Default: 1.0) + */ + speed: number; + + /** + * mem or cpu. If optimizing for memory, animation frames will be rendered to + * bitmaps as the animation plays, using less memory. Optimizing for cpu will + * precompile all bitmaps beforehand, which may be faster, but might also OOM + * the process on large images. (Default: mem). + */ + optimization: "mem" | "cpu"; + } + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + */ + class ANSIImageElement extends BoxElement implements IHasOptions { + constructor(options?: ANSIImageOptions); + + options: ANSIImageOptions; + + /** + * Image object from the png reader. + */ + img: Types.TImage; + + /** + * set the image in the box to a new path. + */ + setImage(img: string, callback: () => void): void; + + /** + * clear the current image. + */ + clearImage(callback: () => void): void; + + /** + * Play animation if it has been paused or stopped. + */ + play(): void; + + /** + * Pause animation. + */ + pause(): void; + + /** + * Stop animation. + */ + stop(): void; + } + + interface OverlayImageOptions extends BoxOptions { + /** + * Path to image. + */ + file: string; + + /** + * Render the file as ANSI art instead of using w3m to overlay Internally uses the + * ANSIImage element. See the ANSIImage element for more information/options. (Default: true). + */ + ansi: boolean; + + /** + * Path to w3mimgdisplay. If a proper w3mimgdisplay path is not given, blessed will + * search the entire disk for the binary. + */ + w3m: string; + + /** + * Whether to search /usr, /bin, and /lib for w3mimgdisplay (Default: true). + */ + search: string; + } + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + */ + class OverlayImageElement extends BoxElement implements IHasOptions { + constructor(options?: OverlayImageOptions); + + options: OverlayImageOptions; + + /** + * set the image in the box to a new path. + */ + setImage(img: string, callback: () => void): void; + + /** + * clear the current image. + */ + clearImage(callback: () => void): void; + + /** + * get the size of an image file in pixels. + */ + imageSize(img: string, callback: () => void): void; + + /** + * get the size of the terminal in pixels. + */ + termSize(callback: () => void): void; + + /** + * get the pixel to cell ratio for the terminal. + */ + getPixelRatio(callback: () => void): void; + } + + interface VideoOptions extends BoxOptions { + /** + * Video to play. + */ + file: string; + + /** + * Start time in seconds. + */ + start: number; + } + + class VideoElement extends BoxElement implements IHasOptions { + constructor(options?: VideoOptions); + + options: VideoOptions; + + /** + * The terminal element running mplayer or mpv. + */ + tty: any; + } + + interface LayoutOptions extends ElementOptions { + /** + * A callback which is called right before the children are iterated over to be rendered. Should return an + * iterator callback which is called on each child element: iterator(el, i). + */ + renderer?(): void; + + /** + * Using the default renderer, it provides two layouts: inline, and grid. inline is the default and will render + * akin to inline-block. grid will create an automatic grid based on element dimensions. The grid cells' + * width and height are always determined by the largest children in the layout. + */ + layout: "inline" | "inline-block" | "grid"; + } + + class LayoutElement extends BlessedElement implements IHasOptions { + constructor(options?: LayoutOptions); + + options: LayoutOptions; + + /** + * A callback which is called right before the children are iterated over to be rendered. Should return an + * iterator callback which is called on each child element: iterator(el, i). + */ + renderer(coords: PositionCoords): void; + + /** + * Check to see if a previous child element has been rendered and is visible on screen. This is only useful + * for checking child elements that have already been attempted to be rendered! see the example below. + */ + isRendered(el: BlessedElement): boolean; + + /** + * Get the last rendered and visible child element based on an index. This is useful for basing the position + * of the current child element on the position of the last child element. + */ + getLast(i: number): BlessedElement; + + /** + * Get the last rendered and visible child element coords based on an index. This is useful for basing the position + * of the current child element on the position of the last child element. See the example below. + */ + getLastCoords(i: number): PositionCoords; + } + + class Program { + /** + * Wrap the given text in terminal formatting codes corresponding to the given attribute + * name. The `attr` string can be of the form `red fg` or `52 bg` where `52` is a 0-255 + * integer color number. + */ + text(text: string, attr: string): string; } } -export = Blessed; +export namespace widget { + class Terminal extends Widgets.TerminalElement {} +} + +export function screen(options?: Widgets.IScreenOptions): Widgets.Screen; +export function box(options?: Widgets.BoxOptions): Widgets.BoxElement; +export function text(options?: Widgets.TextOptions): Widgets.TextElement; +export function line(options?: Widgets.LineOptions): Widgets.LineElement; +export function scrollablebox(options?: Widgets.BoxOptions): Widgets.BoxElement; +export function scrollabletext(options?: Widgets.BoxOptions): Widgets.BoxElement; +export function bigtext(options?: Widgets.BigTextOptions): Widgets.BigTextElement; +export function list(options?: Widgets.ListOptions): Widgets.ListElement; +export function filemanager(options?: Widgets.FileManagerOptions): Widgets.FileManagerElement; +export function listtable(options?: Widgets.ListTableOptions): Widgets.ListTableElement; +export function listbar(options?: Widgets.ListbarOptions): Widgets.ListbarElement; +export function form(options?: Widgets.FormOptions): Widgets.FormElement; +export function input(options?: Widgets.InputOptions): Widgets.InputElement; +export function textarea(options?: Widgets.TextareaOptions): Widgets.TextareaElement; +export function textbox(options?: Widgets.TextboxOptions): Widgets.TextboxElement; +export function button(options?: Widgets.ButtonOptions): Widgets.ButtonElement; +export function checkbox(options?: Widgets.CheckboxOptions): Widgets.CheckboxElement; +export function radioset(options?: Widgets.RadioSetOptions): Widgets.RadioSetElement; +export function radiobutton(options?: Widgets.RadioButtonOptions): Widgets.RadioButtonElement; +export function table(options?: Widgets.TableOptions): Widgets.TableElement; +export function prompt(options?: Widgets.PromptOptions): Widgets.PromptElement; +export function question(options?: Widgets.QuestionOptions): Widgets.QuestionElement; +export function message(options?: Widgets.MessageOptions): Widgets.MessageElement; +export function loading(options?: Widgets.LoadingOptions): Widgets.LoadingElement; +export function log(options?: Widgets.LogOptions): Widgets.Log; +export function progressbar(options?: Widgets.ProgressBarOptions): Widgets.ProgressBarElement; +export function terminal(options?: Widgets.TerminalOptions): Widgets.TerminalElement; +export function layout(options?: Widgets.LayoutOptions): Widgets.LayoutElement; +export function escape(item: any): any; + +export const colors: { + match(hexColor: string): string; +}; diff --git a/types/bluebird-retry/bluebird-retry-tests.ts b/types/bluebird-retry/bluebird-retry-tests.ts index eb3260a007..e9beaf5562 100644 --- a/types/bluebird-retry/bluebird-retry-tests.ts +++ b/types/bluebird-retry/bluebird-retry-tests.ts @@ -1,13 +1,13 @@ import Promise = require('bluebird'); import retry = require('bluebird-retry'); -function promiseSuccess(text:string) { +function promiseSuccess(text: string) { return Promise.resolve(text); -}; +} -var count = 0; +let count = 0; function myfunc() { - console.log('myfunc called ' + (++count) + ' times'); + console.log(`myfunc called ${++count} times`); if (count < 3) { throw new Error('i fail the first two times'); } else { @@ -16,18 +16,17 @@ function myfunc() { } retry(myfunc) - .done(function(result) { console.log(result); } ); + .done(result => { console.log(result); }); - -//Options example +// Options example function logFail() { console.log(new Date().toISOString()); throw new Error('bail'); } -var options:retry.Options = { +const options: retry.Options = { max_tries: 4, interval: 500 }; -retry(logFail, options); \ No newline at end of file +retry(logFail, options); diff --git a/types/bluebird-retry/index.d.ts b/types/bluebird-retry/index.d.ts index 97d756524b..358c75936d 100644 --- a/types/bluebird-retry/index.d.ts +++ b/types/bluebird-retry/index.d.ts @@ -1,17 +1,15 @@ -// Type definitions for bluebird-retry +// Type definitions for bluebird-retry 0.11 // Project: https://github.com/jut-io/bluebird-retry // Definitions by: Pascal Vomhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -/// - import Promise = require('bluebird'); declare function retry(func: (param: T) => void, options?: retry.Options): Promise; declare namespace retry { - export interface Options { + interface Options { interval?: number; backoff?: number; max_interval?: number; @@ -22,7 +20,6 @@ declare namespace retry { context?: any; args?: any; } - } export = retry; diff --git a/types/bluebird-retry/tslint.json b/types/bluebird-retry/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/bluebird-retry/tslint.json +++ b/types/bluebird-retry/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/box2d/index.d.ts b/types/box2d/index.d.ts index 77a132592e..d17eb2c8f6 100644 --- a/types/box2d/index.d.ts +++ b/types/box2d/index.d.ts @@ -5147,7 +5147,7 @@ declare namespace Box2D.Dynamics.Joints { /** * The pulley joint is connected to two bodies and two fixed ground points. The pulley supports a ratio such that: length1 + ratio length2 <= constant Yes, the force transmitted is scaled by the ratio. The pulley also enforces a maximum length limit on both sides. This is useful to prevent one side of the pulley hitting the top. **/ - export class b2PullyJoint extends b2Joint { + export class b2PulleyJoint extends b2Joint { /** * Get the anchor point on bodyA in world coordinates. @@ -5207,7 +5207,7 @@ declare namespace Box2D.Dynamics.Joints { /** * Pulley joint definition. This requires two ground anchors, two dynamic body anchor points, max lengths for each side, and a pulley ratio. **/ - export class b2PullyJointDef extends b2JointDef { + export class b2PulleyJointDef extends b2JointDef { /** * The first ground anchor in world coordinates. This point never moves. diff --git a/types/braintree-web/index.d.ts b/types/braintree-web/index.d.ts index 46f16e072b..bc5ca0b01f 100644 --- a/types/braintree-web/index.d.ts +++ b/types/braintree-web/index.d.ts @@ -611,12 +611,14 @@ declare namespace braintree { * @property {object} details Additional account details. * @property {string} details.cardType Type of card, ex: Visa, MasterCard. * @property {string} details.lastTwo Last two digits of card number. + * @property {string} details.lastFour Last four digits of card number. * @property {string} description A human-readable description. * @property {string} type The payment method type, always `CreditCard`. */ interface HostedFieldsAccountDetails { cardType: string; lastTwo: string; + lastFour: string; } interface HostedFieldsTokenizePayload { diff --git a/types/bson/index.d.ts b/types/bson/index.d.ts index 2b6a636e89..6aeeabe3d9 100644 --- a/types/bson/index.d.ts +++ b/types/bson/index.d.ts @@ -39,6 +39,9 @@ export class Binary { constructor(buffer: Buffer, subType?: number); + /** The underlying Buffer which stores the binary data. */ + readonly buffer: Buffer; + /** The length of the binary. */ length(): number; /** Updates this binary with byte_value */ diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index abfd4ddd98..1e9e3b55bc 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -1,11 +1,14 @@ -// Type definitions for bull 3.0 +// Type definitions for bull 3.3 // Project: https://github.com/OptimalBits/bull // Definitions by: Bruno Grieder // Cameron Crothers // Marshall Cottrell +// Weeco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Redis from "ioredis"; +import * as Promise from "bluebird"; /** * This is the Queue constructor. @@ -13,407 +16,591 @@ import * as Redis from "ioredis"; * Everytime the same queue is instantiated it tries to process all the old jobs that may exist from a previous unfinished session. */ declare const Bull: { - // tslint:disable:unified-signatures - (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; - (queueName: string, url?: string): Bull.Queue; - new (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; - new (queueName: string, url?: string): Bull.Queue; - // tslint:enable:unified-signatures + // tslint:disable:unified-signatures + (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; + (queueName: string, url?: string): Bull.Queue; + new (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; + new (queueName: string, url?: string): Bull.Queue; + // tslint:enable:unified-signatures }; declare namespace Bull { - interface QueueOptions { - /** - * Options passed directly to the `ioredis` constructor - */ - redis?: Redis.RedisOptions; - - /** - * When specified, the `Queue` will use this function to create new `ioredis` client connections. - * This is useful if you want to re-use connections. - */ - createClient?(type: 'client' | 'subscriber', redisOpts?: Redis.RedisOptions): Redis.Redis; - - /** - * Prefix to use for all redis keys - */ - prefix?: string; - - settings?: AdvancedSettings; - } - - interface AdvancedSettings { - /** - * Key expiration time for job locks - */ - lockDuration?: number; - - /** - * How often check for stalled jobs (use 0 for never checking) - */ - stalledInterval?: number; - - /** - * Max amount of times a stalled job will be re-processed - */ - maxStalledCount?: number; - - /** - * Poll interval for delayed jobs and added jobs - */ - guardInterval?: number; - - /** - * Delay before processing next job in case of internal error - */ - retryProcessDelay?: number; - } - - type DoneCallback = (error?: Error | null, value?: any) => void; - - type JobId = number | string; - - interface Job { - id: JobId; - - /** - * The custom data passed when the job was created - */ - data: any; - - /** - * Report progress on a job - */ - progress(value: any): Promise; - - /** - * Removes a job from the queue and from any lists it may be included in. - * @returns A promise that resolves when the job is removed. - */ - remove(): Promise; - - /** - * Re-run a job that has failed. - * @returns A promise that resolves when the job is scheduled for retry. - */ - retry(): Promise; - - /** - * Returns a promise the resolves when the job has been finished. - * TODO: Add a watchdog to check if the job has finished periodically. - * since pubsub does not give any guarantees. - */ - finished(): Promise; - - /** - * Promotes a job that is currently "delayed" to the "waiting" state and executed as soon as possible. - */ - promote(): Promise; - } - - type JobStatus = 'completed' | 'waiting' | 'active' | 'delayed' | 'failed'; - - interface BackoffOptions { - /** - * Backoff type, which can be either `fixed` or `exponential` - */ - type: 'fixed' | 'exponential'; - - /** - * Backoff delay, in milliseconds - */ - delay: number; - } - - interface RepeatOptions { - /** - * Cron pattern specifying when the job should execute - */ - cron: string; - - /** - * Timezone - */ - tz?: string; - - /** - * End date when the repeat job should stop repeating - */ - endDate?: Date | string | number; - } - - interface JobOptions { - /** - * Optional priority value. ranges from 1 (highest priority) to MAX_INT (lowest priority). - * Note that using priorities has a slight impact on performance, so do not use it if not required - */ - priority?: number; - - /** - * An amount of miliseconds to wait until this job can be processed. - * Note that for accurate delays, both server and clients should have their clocks synchronized. [optional] - */ - delay?: number; - - /** - * The total number of attempts to try the job until it completes - */ - attempts?: number; - - /** - * Repeat job according to a cron specification - */ - repeat?: RepeatOptions; - - /** - * Backoff setting for automatic retries if the job fails - */ - backoff?: number | BackoffOptions; - - /** - * A boolean which, if true, adds the job to the right - * of the queue instead of the left (default false) - */ - lifo?: boolean; - - /** - * The number of milliseconds after which the job should be fail with a timeout error - */ - timeout?: number; - - /** - * Override the job ID - by default, the job ID is a unique - * integer, but you can use this setting to override it. - * If you use this option, it is up to you to ensure the - * jobId is unique. If you attempt to add a job with an id that - * already exists, it will not be added. - */ - jobId?: JobId; - - /** - * A boolean which, if true, removes the job when it successfully completes. - * Default behavior is to keep the job in the completed set. - */ - removeOnComplete?: boolean; - - /** - * A boolean which, if true, removes the job when it fails after all attempts - * Default behavior is to keep the job in the completed set. - */ - removeOnFail?: boolean; - } - - interface JobCounts { - wait: number; - active: number; - completed: number; - failed: number; - delayed: number; - } - - interface Queue { - /** - * Returns a promise that resolves when Redis is connected and the queue is ready to accept jobs. - * This replaces the `ready` event emitted on Queue in previous verisons. - */ - isReady(): Promise; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * The done callback can be called with an Error instance, to signal that the job did not complete successfully, - * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. - * Errors will be passed as a second argument to the "failed" event; - * results, as a second argument to the "completed" event. - * - * concurrency: Bull will then call you handler in parallel respecting this max number. - */ - process(concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * The done callback can be called with an Error instance, to signal that the job did not complete successfully, - * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. - * Errors will be passed as a second argument to the "failed" event; - * results, as a second argument to the "completed" event. - */ - process(callback: (job: Job, done: DoneCallback) => void): void; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * A promise must be returned to signal job completion. - * If the promise is rejected, the error will be passed as a second argument to the "failed" event. - * If it is resolved, its value will be the "completed" event's second argument. - * - * concurrency: Bull will then call you handler in parallel respecting this max number. - */ - process(concurrency: number, callback: (job: Job) => void): Promise; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * A promise must be returned to signal job completion. - * If the promise is rejected, the error will be passed as a second argument to the "failed" event. - * If it is resolved, its value will be the "completed" event's second argument. - */ - process(callback: (job: Job) => void): Promise; - - /** - * Creates a new job and adds it to the queue. - * If the queue is empty the job will be executed directly, - * otherwise it will be placed in the queue and executed as soon as possible. - */ - add(data: any, opts?: JobOptions): Promise; - - /** - * Returns a promise that resolves when the queue is paused. - * The pause is global, meaning that all workers in all queue instances for a given queue will be paused. - * A paused queue will not process new jobs until resumed, - * but current jobs being processed will continue until they are finalized. - * - * Pausing a queue that is already paused does nothing. - */ - pause(): Promise; - - /** - * Returns a promise that resolves when the queue is resumed after being paused. - * The resume is global, meaning that all workers in all queue instances for a given queue will be resumed. - * - * Resuming a queue that is not paused does nothing. - */ - resume(): Promise; - - /** - * Returns a promise that returns the number of jobs in the queue, waiting or paused. - * Since there may be other processes adding or processing jobs, this value may be true only for a very small amount of time. - */ - count(): Promise; - - /** - * Empties a queue deleting all the input lists and associated jobs. - */ - empty(): Promise; - - /** - * Closes the underlying redis client. Use this to perform a graceful shutdown. - * - * `close` can be called from anywhere, with one caveat: - * if called from within a job handler the queue won't close until after the job has been processed - */ - close(): Promise; - - /** - * Returns a promise that will return the job instance associated with the jobId parameter. - * If the specified job cannot be located, the promise callback parameter will be set to null. - */ - getJob(jobId: JobId): Promise; - - /** - * Returns a promise that resolves with the job counts for the given queue - */ - getJobCounts(): Promise; - - /** - * Tells the queue remove all jobs created outside of a grace period in milliseconds. - * You can clean the jobs with the following states: completed, waiting, active, delayed, and failed. - */ - clean(grace: number, status?: JobStatus, limit?: number): Promise; - - // tslint:disable:unified-signatures - - /** - * Listens to queue events - */ - on(event: string, callback: (...args: any[]) => void): this; - - /** - * An error occured - */ - on(event: 'error', callback: ErrorEventCallback): this; - - /** - * A job has started. You can use `jobPromise.cancel()` to abort it - */ - on(event: 'active', callback: ActiveEventCallback): this; - - /** - * A job has been marked as stalled. - * This is useful for debugging job workers that crash or pause the event loop. - */ - on(event: 'stalled', callback: StalledEventCallback): this; - - /** - * A job's progress was updated - */ - on(event: 'progress', callback: ProgressEventCallback): this; - - /** - * A job successfully completed with a `result` - */ - on(event: 'completed', callback: CompletedEventCallback): this; - - /** - * A job failed with `err` as the reason - */ - on(event: 'failed', callback: FailedEventCallback): this; - - /** - * The queue has been paused - */ - on(event: 'paused', callback: EventCallback): this; - - /** - * The queue has been resumed - */ - on(event: 'resumed', callback: EventCallback): this; - - /** - * Old jobs have been cleaned from the queue. - * `jobs` is an array of jobs that were removed, and `type` is the type of those jobs. - * - * @see Queue#clean() for details - */ - on(event: 'cleaned', callback: CleanedEventCallback): this; - - // tslint:enable:unified-signatures - } - - type EventCallback = () => void; - - type ErrorEventCallback = (error: Error) => void; - - interface JobPromise { - /** - * Abort this job - */ - cancel(): void; - } - - type ActiveEventCallback = (job: Job, jobPromise?: JobPromise) => void; - - type StalledEventCallback = (job: Job) => void; - - type ProgressEventCallback = (job: Job, progress: any) => void; - - type CompletedEventCallback = (job: Job, result: any) => void; - - type FailedEventCallback = (job: Job, error: Error) => void; - - type CleanedEventCallback = (jobs: Job[], status: JobStatus) => void; + interface RateLimiter { + /** Max numbers of jobs processed */ + max: number; + /** Per duration in milliseconds */ + duration: number; + } + + interface QueueOptions { + /** + * Options passed directly to the `ioredis` constructor + */ + redis?: Redis.RedisOptions; + + /** + * When specified, the `Queue` will use this function to create new `ioredis` client connections. + * This is useful if you want to re-use connections. + */ + createClient?(type: 'client' | 'subscriber', redisOpts?: Redis.RedisOptions): Redis.Redis; + + /** + * Prefix to use for all redis keys + */ + prefix?: string; + + settings?: AdvancedSettings; + + limiter?: RateLimiter; + } + + interface AdvancedSettings { + /** + * Key expiration time for job locks + */ + lockDuration?: number; + + /** + * How often check for stalled jobs (use 0 for never checking) + */ + stalledInterval?: number; + + /** + * Max amount of times a stalled job will be re-processed + */ + maxStalledCount?: number; + + /** + * Poll interval for delayed jobs and added jobs + */ + guardInterval?: number; + + /** + * Delay before processing next job in case of internal error + */ + retryProcessDelay?: number; + } + + type DoneCallback = (error?: Error | null, value?: any) => void; + + type JobId = number | string; + + interface Job { + id: JobId; + + /** + * The custom data passed when the job was created + */ + data: any; + + /** + * Report progress on a job + */ + progress(value: any): Promise; + + /** + * Returns a promise resolving to the current job's status. + * Please take note that the implementation of this method is not very efficient, nor is + * it atomic. If your queue does have a very large quantity of jobs, you may want to + * avoid using this method. + */ + getState(): Promise; + + /** + * Update a specific job's data. Promise resolves when the job has been updated. + */ + update(data: any): Promise; + + /** + * Removes a job from the queue and from any lists it may be included in. + * The returned promise resolves when the job has been removed. + */ + remove(): Promise; + + /** + * Re-run a job that has failed. The returned promise resolves when the job + * has been scheduled for retry. + */ + retry(): Promise; + + /** + * Returns a promise that resolves to the returned data when the job has been finished. + * TODO: Add a watchdog to check if the job has finished periodically. + * since pubsub does not give any guarantees. + */ + finished(): Promise; + + /** + * Promotes a job that is currently "delayed" to the "waiting" state and executed as soon as possible. + */ + promote(): Promise; + } + + type JobStatus = 'completed' | 'waiting' | 'active' | 'delayed' | 'failed'; + + interface BackoffOptions { + /** + * Backoff type, which can be either `fixed` or `exponential` + */ + type: 'fixed' | 'exponential'; + + /** + * Backoff delay, in milliseconds + */ + delay: number; + } + + interface RepeatOptions { + /** + * Cron pattern specifying when the job should execute + */ + cron: string; + + /** + * Timezone + */ + tz?: string; + + /** + * End date when the repeat job should stop repeating + */ + endDate?: Date | string | number; + } + + interface JobOptions { + /** + * Optional priority value. ranges from 1 (highest priority) to MAX_INT (lowest priority). + * Note that using priorities has a slight impact on performance, so do not use it if not required + */ + priority?: number; + + /** + * An amount of miliseconds to wait until this job can be processed. + * Note that for accurate delays, both server and clients should have their clocks synchronized. [optional] + */ + delay?: number; + + /** + * The total number of attempts to try the job until it completes + */ + attempts?: number; + + /** + * Repeat job according to a cron specification + */ + repeat?: RepeatOptions; + + /** + * Backoff setting for automatic retries if the job fails + */ + backoff?: number | BackoffOptions; + + /** + * A boolean which, if true, adds the job to the right + * of the queue instead of the left (default false) + */ + lifo?: boolean; + + /** + * The number of milliseconds after which the job should be fail with a timeout error + */ + timeout?: number; + + /** + * Override the job ID - by default, the job ID is a unique + * integer, but you can use this setting to override it. + * If you use this option, it is up to you to ensure the + * jobId is unique. If you attempt to add a job with an id that + * already exists, it will not be added. + */ + jobId?: JobId; + + /** + * A boolean which, if true, removes the job when it successfully completes. + * Default behavior is to keep the job in the completed set. + */ + removeOnComplete?: boolean; + + /** + * A boolean which, if true, removes the job when it fails after all attempts + * Default behavior is to keep the job in the completed set. + */ + removeOnFail?: boolean; + } + + interface JobCounts { + wait: number; + active: number; + completed: number; + failed: number; + delayed: number; + } + + interface JobInformation { + key: string; + name: string; + id?: string; + endDate?: number; + tz?: string; + cron: string; + next: number; + } + + interface Queue { + /** + * Returns a promise that resolves when Redis is connected and the queue is ready to accept jobs. + * This replaces the `ready` event emitted on Queue in previous verisons. + */ + isReady(): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; + * results, as a second argument to the "completed" event. + */ + process(callback: (job: Job, done: DoneCallback) => void): void; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * A promise must be returned to signal job completion. + * If the promise is rejected, the error will be passed as a second argument to the "failed" event. + * If it is resolved, its value will be the "completed" event's second argument. + */ + process(callback: (job: Job) => void): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * A promise must be returned to signal job completion. + * If the promise is rejected, the error will be passed as a second argument to the "failed" event. + * If it is resolved, its value will be the "completed" event's second argument. + * + * @param concurrency Bull will then call you handler in parallel respecting this max number. + */ + process(concurrency: number, callback: (job: Job) => void): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; + * results, as a second argument to the "completed" event. + * + * @param concurrency Bull will then call you handler in parallel respecting this max number. + */ + process(concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; + + /** + * Defines a named processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * A promise must be returned to signal job completion. + * If the promise is rejected, the error will be passed as a second argument to the "failed" event. + * If it is resolved, its value will be the "completed" event's second argument. + * + * @param name Bull will only call the handler if the job name matches + */ + // tslint:disable-next-line:unified-signatures + process(name: string, callback: (job: Job) => void): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; + * results, as a second argument to the "completed" event. + * + * @param name Bull will only call the handler if the job name matches + */ + // tslint:disable-next-line:unified-signatures + process(name: string, callback: (job: Job, done: DoneCallback) => void): void; + + /** + * Defines a named processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * A promise must be returned to signal job completion. + * If the promise is rejected, the error will be passed as a second argument to the "failed" event. + * If it is resolved, its value will be the "completed" event's second argument. + * + * @param name Bull will only call the handler if the job name matches + * @param concurrency Bull will then call you handler in parallel respecting this max number. + */ + process(name: string, concurrency: number, callback: (job: Job) => void): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; + * results, as a second argument to the "completed" event. + * + * @param name Bull will only call the handler if the job name matches + * @param concurrency Bull will then call you handler in parallel respecting this max number. + */ + process(name: string, concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; + + /** + * Creates a new job and adds it to the queue. + * If the queue is empty the job will be executed directly, + * otherwise it will be placed in the queue and executed as soon as possible. + */ + add(data: any, opts?: JobOptions): Promise; + + /** + * Creates a new named job and adds it to the queue. + * If the queue is empty the job will be executed directly, + * otherwise it will be placed in the queue and executed as soon as possible. + */ + add(name: string, data: any, opts?: JobOptions): Promise; + + /** + * Returns a promise that resolves when the queue is paused. + * The pause is global, meaning that all workers in all queue instances for a given queue will be paused. + * A paused queue will not process new jobs until resumed, + * but current jobs being processed will continue until they are finalized. + * + * Pausing a queue that is already paused does nothing. + */ + pause(): Promise; + + /** + * Returns a promise that resolves when the queue is resumed after being paused. + * The resume is global, meaning that all workers in all queue instances for a given queue will be resumed. + * + * Resuming a queue that is not paused does nothing. + */ + resume(): Promise; + + /** + * Returns a promise that returns the number of jobs in the queue, waiting or paused. + * Since there may be other processes adding or processing jobs, this value may be true only for a very small amount of time. + */ + count(): Promise; + + /** + * Empties a queue deleting all the input lists and associated jobs. + */ + empty(): Promise; + + /** + * Closes the underlying redis client. Use this to perform a graceful shutdown. + * + * `close` can be called from anywhere, with one caveat: + * if called from within a job handler the queue won't close until after the job has been processed + */ + close(): Promise; + + /** + * Returns a promise that will return the job instance associated with the jobId parameter. + * If the specified job cannot be located, the promise callback parameter will be set to null. + */ + getJob(jobId: JobId): Promise; + + /** + * Returns a promise that will return an array with the active jobs between start and end. + */ + getActive(start?: number, end?: number): Promise; + + /** + * Returns a promise that will return an array with the delayed jobs between start and end. + */ + getDelayed(start?: number, end?: number): Promise; + + /** + * Returns a promise that will return an array with the completed jobs between start and end. + */ + getCompleted(start?: number, end?: number): Promise; + + /** + * Returns a promise that will return an array with the failed jobs between start and end. + */ + getFailed(start?: number, end?: number): Promise; + + /** + * Returns JobInformation of repeatable jobs (ordered descending). Provide a start and/or an end + * index to limit the number of results. Start defaults to 0, end to -1 and asc to false. + */ + getRepeatableJobs(start?: number, end?: number, asc?: boolean): Promise; + + /** + * ??? + */ + nextRepeatableJob(name: string, data: any, opts: JobOptions): Promise; + + /** + * Removes a given repeatable job. The RepeatOpts needs to be the same as the ones used for + * the job when it was added. + */ + removeRepeatable(repeat: RepeatOptions): Promise; + + /** + * Removes a given repeatable job. The RepeatOpts needs to be the same as the ones used for + * the job when it was added. + * + * name: The name of the to be removed job + */ + removeRepeatable(name: string, repeat: RepeatOptions): Promise; + + /** + * Returns a promise that resolves with the job counts for the given queue. + */ + getJobCounts(): Promise; + + /** + * Returns a promise that resolves with the quantity of completed jobs. + */ + getCompletedCount(): Promise; + + /** + * Returns a promise that resolves with the quantity of failed jobs. + */ + getFailedCount(): Promise; + + /** + * Returns a promise that resolves with the quantity of delayed jobs. + */ + getDelayedCount(): Promise; + + /** + * Returns a promise that resolves with the quantity of waiting jobs. + */ + getWaitingCount(): Promise; + + /** + * Returns a promise that resolves with the quantity of paused jobs. + */ + getPausedCount(): Promise; + + /** + * Returns a promise that resolves with the quantity of active jobs. + */ + getActiveCount(): Promise; + + /** + * Returns a promise that resolves to the quantity of repeatable jobs. + */ + getRepeatableCount(): Promise; + + /** + * Tells the queue remove all jobs created outside of a grace period in milliseconds. + * You can clean the jobs with the following states: completed, waiting, active, delayed, and failed. + * @param grace Grace period in milliseconds. + * @param status Status of the job to clean. Values are completed, wait, active, delayed, and failed. Defaults to completed. + * @param limit Maximum amount of jobs to clean per call. If not provided will clean all matching jobs. + */ + clean(grace: number, status?: JobStatus, limit?: number): Promise; + + // tslint:disable:unified-signatures + + /** + * Listens to queue events + */ + on(event: string, callback: (...args: any[]) => void): this; + + /** + * An error occured + */ + on(event: 'error', callback: ErrorEventCallback): this; + + /** + * A job has started. You can use `jobPromise.cancel()` to abort it + */ + on(event: 'active', callback: ActiveEventCallback): this; + + /** + * A job has been marked as stalled. + * This is useful for debugging job workers that crash or pause the event loop. + */ + on(event: 'stalled', callback: StalledEventCallback): this; + + /** + * A job's progress was updated + */ + on(event: 'progress', callback: ProgressEventCallback): this; + + /** + * A job successfully completed with a `result` + */ + on(event: 'completed', callback: CompletedEventCallback): this; + + /** + * A job failed with `err` as the reason + */ + on(event: 'failed', callback: FailedEventCallback): this; + + /** + * The queue has been paused + */ + on(event: 'paused', callback: EventCallback): this; + + /** + * The queue has been resumed + */ + on(event: 'resumed', callback: EventCallback): this; + + /** + * Old jobs have been cleaned from the queue. + * `jobs` is an array of jobs that were removed, and `type` is the type of those jobs. + * + * @see Queue#clean() for details + */ + on(event: 'cleaned', callback: CleanedEventCallback): this; + + // tslint:enable:unified-signatures + } + + type EventCallback = () => void; + + type ErrorEventCallback = (error: Error) => void; + + interface JobPromise { + /** + * Abort this job + */ + cancel(): void; + } + + type ActiveEventCallback = (job: Job, jobPromise?: JobPromise) => void; + + type StalledEventCallback = (job: Job) => void; + + type ProgressEventCallback = (job: Job, progress: any) => void; + + type CompletedEventCallback = (job: Job, result: any) => void; + + type FailedEventCallback = (job: Job, error: Error) => void; + + type CleanedEventCallback = (jobs: Job[], status: JobStatus) => void; } export = Bull; diff --git a/types/c3/index.d.ts b/types/c3/index.d.ts index 287e030445..afae3cff31 100644 --- a/types/c3/index.d.ts +++ b/types/c3/index.d.ts @@ -459,11 +459,11 @@ declare namespace c3 { /** * Set max value of x axis range. */ - max?: number; + max?: string | number | Date; /** * Set min value of x axis range. */ - min?: number; + min?: string | number | Date; /** * Set padding for x axis. * If this option is set, the range of x axis will increase/decrease according to the values. If no padding is needed in the ragen of x axis, 0 should be set. On category axis, this option diff --git a/types/case-sensitive-paths-webpack-plugin/case-sensitive-paths-webpack-plugin-tests.ts b/types/case-sensitive-paths-webpack-plugin/case-sensitive-paths-webpack-plugin-tests.ts new file mode 100644 index 0000000000..a4370cff73 --- /dev/null +++ b/types/case-sensitive-paths-webpack-plugin/case-sensitive-paths-webpack-plugin-tests.ts @@ -0,0 +1,15 @@ +import { Configuration } from 'webpack'; +import CaseSensitivePathsWebpackPlugin = require('case-sensitive-paths-webpack-plugin'); + +const options: CaseSensitivePathsWebpackPlugin.Options = { + debug: true, +}; + +const c: Configuration = { + plugins: [ + new CaseSensitivePathsWebpackPlugin(), + new CaseSensitivePathsWebpackPlugin({ + debug: true + }), + ], +}; diff --git a/types/case-sensitive-paths-webpack-plugin/index.d.ts b/types/case-sensitive-paths-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..360d3d6d08 --- /dev/null +++ b/types/case-sensitive-paths-webpack-plugin/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for case-sensitive-paths-webpack-plugin 2.1 +// Project: https://github.com/Urthen/case-sensitive-paths-webpack-plugin#readme +// Definitions by: Andrew Makarov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin } from 'webpack'; + +export = CaseSensitivePathsWebpackPlugin; + +declare class CaseSensitivePathsWebpackPlugin extends Plugin { + constructor(options?: CaseSensitivePathsWebpackPlugin.Options); +} + +declare namespace CaseSensitivePathsWebpackPlugin { + interface Options { + /** + * Show more information + */ + debug?: boolean; + } +} diff --git a/types/case-sensitive-paths-webpack-plugin/tsconfig.json b/types/case-sensitive-paths-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..b8cb05390a --- /dev/null +++ b/types/case-sensitive-paths-webpack-plugin/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "case-sensitive-paths-webpack-plugin-tests.ts" + ] +} diff --git a/types/case-sensitive-paths-webpack-plugin/tslint.json b/types/case-sensitive-paths-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/case-sensitive-paths-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cassandra-driver/cassandra-driver-tests.ts b/types/cassandra-driver/cassandra-driver-tests.ts index 40971c7183..891c5a0167 100644 --- a/types/cassandra-driver/cassandra-driver-tests.ts +++ b/types/cassandra-driver/cassandra-driver-tests.ts @@ -1,9 +1,16 @@ import * as cassandra from 'cassandra-driver'; import * as util from 'util'; +import * as fs from 'fs'; -var client = new cassandra.Client({ contactPoints: ['h1', 'h2'], keyspace: 'ks1'}); +const client = new cassandra.Client({ + contactPoints: ['h1', 'h2'], + keyspace: 'ks1', + sslOptions: { + cert: fs.readFileSync('certFilePath') + } +}); -var query = 'SELECT email, last_name FROM user_profiles WHERE key=?'; +const query = 'SELECT email, last_name FROM user_profiles WHERE key=?'; client.execute(query, ['guy'], function(err, result) { console.log('got user profile with email ' + result.rows[0].email); }); diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index a581071dfb..bdaed6559c 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -12,11 +12,12 @@ export type ResultCallback = (err: Error, result: types.ResultSet) => void; import * as events from "events"; import * as stream from "stream"; +import * as tls from "tls"; import _Long = require("long"); export namespace policies { namespace addressResolution { - var EC2MultiRegionTranslator: EC2MultiRegionTranslatorStatic; + let EC2MultiRegionTranslator: EC2MultiRegionTranslatorStatic; interface AddressTranslator { translate(address: string, port: number, callback: Callback): void; @@ -32,10 +33,10 @@ export namespace policies { } namespace loadBalancing { - var DCAwareRoundRobinPolicy: DCAwareRoundRobinPolicyStatic; - var RoundRobinPolicy: RoundRobinPolicyStatic; - var TokenAwarePolicy: TokenAwarePolicyStatic; - var WhiteListPolicy: WhiteListPolicyStatic; + let DCAwareRoundRobinPolicy: DCAwareRoundRobinPolicyStatic; + let RoundRobinPolicy: RoundRobinPolicyStatic; + let TokenAwarePolicy: TokenAwarePolicyStatic; + let WhiteListPolicy: WhiteListPolicyStatic; interface LoadBalancingPolicy { init(client: Client, hosts: HostMap, callback: Callback): void; @@ -72,8 +73,8 @@ export namespace policies { } namespace reconnection { - var ConstantReconnectionPolicy: ConstantReconnectionPolicyStatic; - var ExponentialReconnectionPolicy: ExponentialReconnectionPolicyStatic; + let ConstantReconnectionPolicy: ConstantReconnectionPolicyStatic; + let ExponentialReconnectionPolicy: ExponentialReconnectionPolicyStatic; interface ReconnectionPolicy { newSchedule(): { next: Function }; @@ -93,7 +94,7 @@ export namespace policies { } namespace retry { - var RetryPolicy: RetryPolicyStatic; + let RetryPolicy: RetryPolicyStatic; interface DecisionInfo { decision: number; @@ -128,18 +129,18 @@ export namespace policies { } export namespace types { - var BigDecimal: BigDecimalStatic; - var InetAddress: InetAddressStatic; - var Integer: IntegerStatic; - var LocalDate: LocalDateStatic; - var LocalTime: LocalTimeStatic; - var Long: _Long; - var ResultSet: ResultSetStatic; - // var ResultStream: ResultStreamStatic; - var Row: RowStatic; - var TimeUuid: TimeUuidStatic; - var Tuple: TupleStatic; - var Uuid: UuidStatic; + let BigDecimal: BigDecimalStatic; + let InetAddress: InetAddressStatic; + let Integer: IntegerStatic; + let LocalDate: LocalDateStatic; + let LocalTime: LocalTimeStatic; + let Long: _Long; + let ResultSet: ResultSetStatic; + // let ResultStream: ResultStreamStatic; + let Row: RowStatic; + let TimeUuid: TimeUuidStatic; + let Tuple: TupleStatic; + let Uuid: UuidStatic; enum consistencies { any = 0, @@ -433,10 +434,10 @@ export namespace types { } } -export var Client: ClientStatic; -export var Host: HostStatic; -export var HostMap: HostMapStatic; -export var Encoder: EncoderStatic; +export let Client: ClientStatic; +export let Host: HostStatic; +export let HostMap: HostMapStatic; +export let Encoder: EncoderStatic; export interface ClientOptions { contactPoints: Array, @@ -468,7 +469,7 @@ export interface ClientOptions { coalescingThreshold: number }, authProvider?: auth.AuthProvider, - sslOptions?: any, + sslOptions?: tls.ConnectionOptions, encoding?: { map: Function, set: Function, @@ -564,8 +565,8 @@ export interface Encoder { } export namespace auth { - var Authenticator: AuthenticatorStatic; - var PlainTextAuthProvider: PlainTextAuthProviderStatic; + let Authenticator: AuthenticatorStatic; + let PlainTextAuthProvider: PlainTextAuthProviderStatic; interface AuthenticatorStatic { new (): Authenticator; @@ -623,12 +624,12 @@ export namespace errors { } export namespace metadata { - var Aggregate: AggregateStatic; - var Index: IndexStatic; - var MaterializedView: MaterializedViewStatic; - var Metadata: MetadataStatic; - var SchemaFunction: SchemaFunctionStatic; - var TableMetadata: TableMetadataStatic; + let Aggregate: AggregateStatic; + let Index: IndexStatic; + let MaterializedView: MaterializedViewStatic; + let Metadata: MetadataStatic; + let SchemaFunction: SchemaFunctionStatic; + let TableMetadata: TableMetadataStatic; type caching = "all" | "keys_only" | "rows_only" | "none"; diff --git a/types/chai/chai-tests.ts b/types/chai/chai-tests.ts index 31802ca303..401e5f468a 100644 --- a/types/chai/chai-tests.ts +++ b/types/chai/chai-tests.ts @@ -1357,6 +1357,56 @@ suite('assert', () => { assert.notInclude(undefined, 'bar'); }); + test('deepInclude', () => { + assert.deepInclude('foobar', 'bar'); + assert.deepInclude([1, 2, 3], 3); + assert.deepInclude('foobar', 'baz'); + assert.deepInclude(undefined, 'bar'); + }); + + test('notDeepInclude', () => { + assert.notDeepInclude('foobar', 'baz'); + assert.notDeepInclude([1, 2, 3], 4); + assert.notDeepInclude('foobar', 'bar'); + assert.notDeepInclude(undefined, 'bar'); + }); + + test('nestedInclude', () => { + assert.nestedInclude({'.a': {'b': 'x'}}, {'\\.a.[b]': 'x'}); + assert.nestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'x'}); + }); + + test('notNestedInclude', () => { + assert.notNestedInclude({'.a': {'b': 'x'}}, {'\\.a.b': 'y'}); + assert.notNestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'y'}); + }); + + test('deepNestedInclude', () => { + assert.deepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {x: 1}}); + assert.deepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {x: 1}}); + }); + + test('notDeepNestedInclude', () => { + assert.notDeepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {y: 1}}) + assert.notDeepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {y: 2}}); + }); + + test('ownInclude', () => { + assert.ownInclude({ a: 1 }, { a: 1 }); + }); + + test('notOwnInclude', () => { + assert.notOwnInclude({ a: 1 }, { a: 1 }); + }); + + test('deepOwnInclude', () => { + assert.deepOwnInclude({a: {b: 2}}, {a: {b: 2}}); + }); + + test('notDeepOwnInclude', () => { + assert.notDeepOwnInclude({a: {b: 2}}, {a: {c: 3}}); + }); + test('lengthOf', () => { assert.lengthOf([1, 2, 3], 3); assert.lengthOf('foobar', 6); @@ -1677,4 +1727,80 @@ suite('assert', () => { assert.notFrozen(obj); assert.notFrozen(obj, 'message'); }); + + test('hasAnyKeys', () => { + assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'iDontExist', 'baz']); + assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, iDontExist: 99, baz: 1337}); + assert.hasAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + assert.hasAnyKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); + }); + + test('hasAllKeys', () => { + assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); + assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337}); + assert.hasAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + assert.hasAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); + }); + + test('containsAllKeys', () => { + assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'baz']); + assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); + assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, baz: 1337}); + assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337}); + assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}]); + assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}]); + assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); + }); + + test('doesNotHaveAnyKeys', () => { + assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); + assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); + assert.doesNotHaveAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); + assert.doesNotHaveAnyKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{one: 'two'}, 'example']); + }); + + test('doesNotHaveAllKeys', () => { + assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); + assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); + assert.doesNotHaveAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); + assert.doesNotHaveAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{one: 'two'}, 'example']); + }); + + test('hasAnyDeepKeys', () => { + assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); + assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), [{one: 'one'}, {two: 'two'}]); + assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); + assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {three: 'three'}]); + assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + }); + + test('hasAllDeepKeys', () => { + assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne']]), {one: 'one'}); + assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + assert.hasAllDeepKeys(new Set([{one: 'one'}]), {one: 'one'}); + assert.hasAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + }); + + test('containsAllDeepKeys', () => { + assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); + assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); + assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + }); + + test('doesNotHaveAnyDeepKeys', () => { + assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); + assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); + assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); + assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); + }); + + test('doesNotHaveAllDeepKeys', () => { + assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); + assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {one: 'one'}]); + assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); + assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {fifty: 'fifty'}]); + }); }); diff --git a/types/chai/index.d.ts b/types/chai/index.d.ts index bb730fe598..faafa3b2a8 100644 --- a/types/chai/index.d.ts +++ b/types/chai/index.d.ts @@ -7,6 +7,7 @@ // Matt Wistrand , // Josh Goldberg // Shaun Luttin +// Gintautas Miselis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // @@ -706,13 +707,145 @@ declare namespace Chai { /** * Asserts that haystack does not include needle. * - * @type T Type of values in haystack. * @param haystack Container array. * @param needle Potential value contained in haystack. * @param message Message to display on error. */ notInclude(haystack: any[], needle: any, message?: string): void; + + /** + * Asserts that haystack includes needle. Can be used to assert the inclusion of a value in an array or a subset of properties in an object. Deep equality is used. + * + * @param haystack Container string. + * @param needle Potential expected substring of haystack. + * @param message Message to display on error. + */ + deepInclude(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack includes needle. Can be used to assert the inclusion of a value in an array or a subset of properties in an object. Deep equality is used. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that haystack does not include needle. Can be used to assert the absence of a value in an array or a subset of properties in an object. Deep equality is used. + * + * @param haystack Container string. + * @param needle Potential expected substring of haystack. + * @param message Message to display on error. + */ + notDeepInclude(haystack: string, needle: any, message?: string): void; + + /** + * Asserts that haystack does not include needle. Can be used to assert the absence of a value in an array or a subset of properties in an object. Deep equality is used. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notDeepInclude(haystack: any[], needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + nestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ does not include ‘needle’. Can be used to assert the absence of a subset of properties in an object. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while checking for deep equality + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ does not include ‘needle’. Can be used to assert the absence of a subset of properties in an object while checking for deep equality. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notDeepNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while ignoring inherited properties. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + ownInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the absence of a subset of properties in an object while ignoring inherited properties. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while ignoring inherited properties and checking for deep + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the absence of a subset of properties in an object while ignoring inherited properties and checking for deep equality. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notDeepOwnInclude(haystack: any, needle: any, message?: string): void; + /** * Asserts that value matches the regular expression regexp. * @@ -1360,6 +1493,136 @@ declare namespace Chai { * @param message Message to display on error. */ isNotEmpty(object: T, message?: string): void; + + /** + * Asserts that `object` has at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAnyKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all and only all of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAllKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all of the `keys` provided but may have more keys not listed. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + containsAllKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has none of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAnyKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` does not have at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAllKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has at least one of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAnyDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all and only all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAllDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + containsAllDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAnyDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAllDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; } export interface Config { diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index c2ae788396..049488f8db 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Chart.js 2.6 +// Type definitions for Chart.js 2.7 // Project: https://github.com/nnnick/Chart.js // Definitions by: Alberto Nuti // Fabien Lavocat @@ -114,18 +114,25 @@ declare namespace Chart { index?: number; } + interface ChartTooltipLabelColor { + borderColor: ChartColor; + backgroundColor: ChartColor; + } + interface ChartTooltipCallback { - beforeTitle?(item?: ChartTooltipItem[], data?: any): void; - title?(item?: ChartTooltipItem[], data?: any): void; - afterTitle?(item?: ChartTooltipItem[], data?: any): void; - beforeBody?(item?: ChartTooltipItem[], data?: any): void; - beforeLabel?(tooltipItem?: ChartTooltipItem, data?: any): void; - label?(tooltipItem?: ChartTooltipItem, data?: any): void; - afterLabel?(tooltipItem?: ChartTooltipItem, data?: any): void; - afterBody?(item?: ChartTooltipItem[], data?: any): void; - beforeFooter?(item?: ChartTooltipItem[], data?: any): void; - footer?(item?: ChartTooltipItem[], data?: any): void; - afterFooter?(item?: ChartTooltipItem[], data?: any): void; + beforeTitle?(item: ChartTooltipItem[], data: ChartData): string | string[]; + title?(item: ChartTooltipItem[], data: ChartData): string | string[]; + afterTitle?(item: ChartTooltipItem[], data: ChartData): string | string[]; + beforeBody?(item: ChartTooltipItem[], data: ChartData): string | string[]; + beforeLabel?(tooltipItem: ChartTooltipItem, data: ChartData): string | string[]; + label?(tooltipItem: ChartTooltipItem, data: ChartData): string | string[]; + labelColor?(tooltipItem: ChartTooltipItem, chart: Chart): ChartTooltipLabelColor; + labelTextColor?(tooltipItem: ChartTooltipItem, chart: Chart): string; + afterLabel?(tooltipItem: ChartTooltipItem, data: ChartData): string | string[]; + afterBody?(item: ChartTooltipItem[], data: ChartData): string | string[]; + beforeFooter?(item: ChartTooltipItem[], data: ChartData): string | string[]; + footer?(item: ChartTooltipItem[], data: ChartData): string | string[]; + afterFooter?(item: ChartTooltipItem[], data: ChartData): string | string[]; } interface ChartAnimationParameter { @@ -152,6 +159,7 @@ declare namespace Chart { interface ChartOptions { responsive?: boolean; responsiveAnimationDuration?: number; + aspectRatio?: number; maintainAspectRatio?: boolean; events?: string[]; onClick?(event?: MouseEvent, activeElements?: Array<{}>): any; diff --git a/types/cheerio/index.d.ts b/types/cheerio/index.d.ts index 511fce354d..8250848374 100644 --- a/types/cheerio/index.d.ts +++ b/types/cheerio/index.d.ts @@ -263,6 +263,7 @@ interface CheerioElement { parent: CheerioElement; parentNode: CheerioElement; nodeValue: string; + data?: string; } interface CheerioAPI extends CheerioSelector, CheerioStatic { diff --git a/types/ckeditor/index.d.ts b/types/ckeditor/index.d.ts index 150bc7e7a6..20882269fd 100644 --- a/types/ckeditor/index.d.ts +++ b/types/ckeditor/index.d.ts @@ -602,13 +602,17 @@ declare namespace CKEDITOR { browserContextMenuOnCtrl?: boolean; clipboard_defaultContentType?: string; // html | text + clipboard_notificationDuration?: number; codeSnippet_codeClass?: string; codeSnippet_languages?: Object; coceSnippet_theme?: string; colorButton_backStyle?: config.styleObject; colorButton_colors?: string; + colorButton_colorsPerRow?: number; + colorButton_enableAutomatic?: boolean; colorButton_enableMore?: boolean; colorButton_foreStyle?: config.styleObject; + colorButton_normalizeBackground?: boolean; contentsCss?: string | string[]; contentsLangDirection?: string; contentsLanguage?: string; @@ -727,7 +731,7 @@ declare namespace CKEDITOR { magicline_holdDistance?: number; magicline_keystrokeNext?: number; magicline_keystrokePrevious?: number; - magicline_tabuList?: number; + magicline_tabuList?: string[]; magicline_triggerOffset?: number; mathJaxLib?: string; menu_groups?: string; diff --git a/types/cli/cli-tests.ts b/types/cli/cli-tests.ts index 294cb7dd8b..2a88a216db 100644 --- a/types/cli/cli-tests.ts +++ b/types/cli/cli-tests.ts @@ -52,7 +52,8 @@ cli.main(function (args, options) { } return str; } - for (i = 0, l = this.argc; i < l; i++) { + var l: number = this.argc; + for (i = 0; i < l; i++) { args[i] = escape(args[i]); } options.separator = escape(options.separator); diff --git a/types/codemirror/index.d.ts b/types/codemirror/index.d.ts index 126eafe013..4f479b29d0 100644 --- a/types/codemirror/index.d.ts +++ b/types/codemirror/index.d.ts @@ -105,9 +105,9 @@ declare namespace CodeMirror { function signal(target: any, name: string, ...args: any[]): void; type DOMEvent = 'mousedown' | 'dblclick' | 'touchstart' | 'contextmenu' | 'keydown' | 'keypress' | 'keyup' | 'cut' | 'copy' | 'paste' | 'dragstart' | 'dragenter' | 'dragover' | 'dragleave' | 'drop'; - + type CoordsMode = 'window' | 'page' | 'local'; - + interface Token { /** The character(on the given line) at which the token starts. */ start: number; @@ -202,10 +202,10 @@ declare namespace CodeMirror { /** Compute the line at the given pixel height. mode is the relative element to use to compute this line, it may be "window", "page" (the default), or "local" */ lineAtHeight(height: number, mode?: CoordsMode): number; - - /** Computes the height of the top of a line, in the coordinate system specified by mode, it may be "window", - "page" (the default), or "local". When a line below the bottom of the document is specified, the returned value - is the bottom of the last line in the document. By default, the position of the actual text is returned. + + /** Computes the height of the top of a line, in the coordinate system specified by mode, it may be "window", + "page" (the default), or "local". When a line below the bottom of the document is specified, the returned value + is the bottom of the last line in the document. By default, the position of the actual text is returned. If includeWidgets is true and the line has line widgets, the position above the first line widget is returned. */ heightAtLine(line: any, mode?: CoordsMode, includeWidgets?: boolean): number; @@ -292,7 +292,7 @@ declare namespace CodeMirror { charCoords(pos: CodeMirror.Position, mode?: CoordsMode): { left: number; right: number; top: number; bottom: number; }; /** Given an { left , top } object , returns the { line , ch } position that corresponds to it. - The optional mode parameter determines relative to what the coordinates are interpreted. + The optional mode parameter determines relative to what the coordinates are interpreted. It may be "window", "page" (the default), or "local". */ coordsChar(object: { left: number; top: number; }, mode?: CoordsMode): CodeMirror.Position; @@ -512,7 +512,7 @@ declare namespace CodeMirror { /** Get the currently selected code. */ getSelection(): string; - + /** Returns an array containing a string for each selection, representing the content of the selections. */ getSelections(lineSep?: string): Array; @@ -535,8 +535,14 @@ declare namespace CodeMirror { /** Set the cursor position.You can either pass a single { line , ch } object , or the line and the character as two separate parameters. */ setCursor(pos: CodeMirror.Position): void; - /** Set the selection range.anchor and head should be { line , ch } objects.head defaults to anchor when not given. */ - setSelection(anchor: CodeMirror.Position, head: CodeMirror.Position): void; + /** Set a single selection range. anchor and head should be {line, ch} objects. head defaults to anchor when not given. */ + setSelection(anchor: CodeMirror.Position, head: CodeMirror.Position, options?: { bias?: number, origin?: string, scroll?: boolean }): void; + + /** Sets a new set of selections. There must be at least one selection in the given array. When primary is a + number, it determines which selection is the primary one. When it is not given, the primary index is taken from + the previous selection, or set to the last range if the previous selection had less ranges than the new one. + Supports the same options as setSelection. */ + setSelections(ranges: Array<{ anchor: CodeMirror.Position, head: CodeMirror.Position }>, primary?: number, options?: { bias?: number, origin?: string, scroll?: boolean }): void; /** Similar to setSelection , but will, if shift is held or the extending flag is set, move the head of the selection while leaving the anchor at its current place. @@ -779,7 +785,7 @@ declare namespace CodeMirror { /** Determines whether the gutter scrolls along with the content horizontally (false) or whether it stays fixed during horizontal scrolling (true, the default). */ fixedGutter?: boolean; - + /** * Chooses a scrollbar implementation. The default is "native", showing native scrollbars. The core library also * provides the "null" style, which completely hides the scrollbars. Addons can implement additional scrollbar models. @@ -1141,6 +1147,7 @@ declare namespace CodeMirror { interface LintStateOptions { async: boolean; hasGutters: boolean; + onUpdateLinting?: (annotationsNotSorted: Annotation[], annotations: Annotation[], codeMirror: Editor) => void; } /** diff --git a/types/combokeys/index.d.ts b/types/combokeys/index.d.ts index f7e1e5b035..24f3313582 100644 --- a/types/combokeys/index.d.ts +++ b/types/combokeys/index.d.ts @@ -35,7 +35,7 @@ declare namespace Combokeys { * @param {handler} optional - one of "keypress", "keydown", or "keyup" * @returns void */ - bind(keys: string | string[], callback: () => void, action?: string): void; + bind(keys: string | string[], callback: (event: KeyboardEvent) => void, action?: string): void; /** diff --git a/types/command-line-args/index.d.ts b/types/command-line-args/index.d.ts index 442ee5cb93..332368d827 100644 --- a/types/command-line-args/index.d.ts +++ b/types/command-line-args/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for command-line-args 4.0.6 +// Type definitions for command-line-args 4.0.7 // Project: https://github.com/75lb/command-line-args // Definitions by: CzBuCHi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -25,50 +25,63 @@ */ declare function commandLineArgs(optionDefinitions: commandLineArgs.OptionDefinition[], options?: commandLineArgs.Options): any; -declare module commandLineArgs { +declare module commandLineArgs { - export interface OptionDefinition { - /** - * The only required definition property is name, the value of each option will be either a Boolean or string. - */ - name: string, - /** - * The type value is a setter function (you receive the output from this), enabling you to be specific about the type and value received. - */ - type?: (arg: string) => any, - /** - * getopt-style short option names. Can be any single character (unicode included) except a digit or hypen. - */ - alias?: string, - /** - * Set this flag if the option takes a list of values. You will receive an array of values, each passed through the type function (if specified). - */ - multiple?: boolean, - /** - * Any unclaimed command-line args will be set on this option. This flag is typically set on the most commonly-used option to make for more concise usage (i.e. $ myapp *.js instead of $ myapp --files *.js). - */ - defaultOption?: boolean, - /** - * An initial value for the option. - */ - defaultValue?: any, - /** - * When your app has a large amount of options it makes sense to organise them in groups. - * There are two automatic groups: _all (contains all options) and _none (contains options without a group specified in their definition). - */ - group?: string | string[], - } + export interface OptionDefinition { + /** + * The only required definition property is name, the value of each option will be either a Boolean or string. + */ + name: string, + /** + * The type value is a setter function (you receive the output from this), + * enabling you to be specific about the type and value received. + */ + type?: (arg: string) => any, + /** + * getopt-style short option names. Can be any single character (unicode included) except a digit or hypen. + */ + alias?: string, + /** + * Set this flag if the option takes a list of values. You will receive an array of values, each passed + * through the type function (if specified). + */ + multiple?: boolean, + /** + * Any unclaimed command-line args will be set on this option. This flag is typically set on + * the most commonly-used option to make for more concise usage + * (i.e. $ myapp *.js instead of $ myapp --files *.js). + */ + defaultOption?: boolean, + /** + * An initial value for the option. + */ + defaultValue?: any, + /** + * When your app has a large amount of options it makes sense to organise them in groups. + * There are two automatic groups: _all (contains all options) and _none (contains options + * without a group specified in their definition). + */ + group?: string | string[], + /** + * Describes the option. + */ + description?: string, + /** + * A label for the type, e.g. . + */ + typeLabel?: string; + } - export interface Options { - /** - * An array of strings, which if passed will be parsed instead of `process.argv`. - */ - argv?: string[]; - /** - * If `true`, an array of unknown arguments is returned in the `_unknown` property of the output. - */ - partial?: boolean; - } + export interface Options { + /** + * An array of strings, which if passed will be parsed instead of `process.argv`. + */ + argv?: string[]; + /** + * If `true`, an array of unknown arguments is returned in the `_unknown` property of the output. + */ + partial?: boolean; + } } export = commandLineArgs; diff --git a/types/content-type/index.d.ts b/types/content-type/index.d.ts index 5ff4ae7ff1..c81c78c966 100644 --- a/types/content-type/index.d.ts +++ b/types/content-type/index.d.ts @@ -18,7 +18,7 @@ export interface MediaType { } export interface RequestLike { - headers: {[header: string]: string | string[]}; + headers: {[header: string]: string | string[] | undefined}; } export interface ResponseLike { diff --git a/types/cordova-plugin-device/index.d.ts b/types/cordova-plugin-device/index.d.ts index cb75703d1a..0451afb4de 100644 --- a/types/cordova-plugin-device/index.d.ts +++ b/types/cordova-plugin-device/index.d.ts @@ -2,9 +2,9 @@ // Project: https://github.com/apache/cordova-plugin-device // Definitions by: Microsoft Open Technologies Inc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// +// // Copyright (c) Microsoft Open Technologies Inc -// Licensed under the MIT license +// Licensed under the MIT license /** * This plugin defines a global device object, which describes the device's hardware and software. @@ -26,11 +26,16 @@ interface Device { uuid: string; /** Get the operating system version. */ version: string; - /** Get the device's manufacturer. */ - manufacturer: string; - /** Whether the device is running on a simulator. */ - isVirtual: boolean; - /** Get the device hardware serial number. */ - serial: string;} + /** Get the device's manufacturer. */ + manufacturer: string; + /** Whether the device is running on a simulator. */ + isVirtual: boolean; + /** Get the device hardware serial number. */ + serial: string; +} + +interface Window { + device: Device; +} declare var device: Device; diff --git a/types/cordova-plugin-keyboard/cordova-plugin-keyboard-tests.ts b/types/cordova-plugin-keyboard/cordova-plugin-keyboard-tests.ts index 767eaa6ed2..fa5cf72a30 100644 --- a/types/cordova-plugin-keyboard/cordova-plugin-keyboard-tests.ts +++ b/types/cordova-plugin-keyboard/cordova-plugin-keyboard-tests.ts @@ -1,23 +1,31 @@ Keyboard.shrinkView(true); Keyboard.shrinkView(false); +Keyboard.shrinkView(null, (currentValue) => console.log(currentValue)); + Keyboard.hideFormAccessoryBar(true); Keyboard.hideFormAccessoryBar(false); +Keyboard.hideFormAccessoryBar(null, (currentValue) => console.log(currentValue)); + Keyboard.disableScrollingInShrinkView(true); Keyboard.disableScrollingInShrinkView(false); +Keyboard.disableScrollingInShrinkView(null, (currentValue) => console.log(currentValue)); + +Keyboard.hide(); + +Keyboard.show(); + if (Keyboard.isVisible) { console.log('Keyboard is visible'); } -Keyboard.automaticScrollToTopOnHiding = true; -Keyboard.onshow = function () { - console.log('onshow'); -}; -Keyboard.onhide = function () { - console.log('onhide'); -}; -Keyboard.onshowing = function () { - console.log('onshowing'); -}; -Keyboard.onhiding= function () { - console.log('onhiding'); -}; +Keyboard.automaticScrollToTopOnHiding = true; + +window.addEventListener('keyboardDidShow', () => console.log('keyboardDidShow')); + +window.addEventListener('keyboardDidHide', () => console.log('keyboardDidHide')); + +window.addEventListener('keyboardWillShow', () => console.log('keyboardWillShow')); + +window.addEventListener('keyboardWillHide', () => console.log('keyboardWillHide')); + +window.addEventListener('keyboardHeightWillChange', (event: CordovaKeyboardEvent) => console.log(`keyboardHeightWillChange - keyboard height: ${event.keyboardHeight}`)); diff --git a/types/cordova-plugin-keyboard/index.d.ts b/types/cordova-plugin-keyboard/index.d.ts index 427a5425e5..af880d732a 100644 --- a/types/cordova-plugin-keyboard/index.d.ts +++ b/types/cordova-plugin-keyboard/index.d.ts @@ -1,32 +1,9 @@ -// Type definitions for Apache Cordova Keyboard plugin v0.1.2 -// Project: https://github.com/apache/cordova-plugins/tree/master/keyboard -// Definitions by: Dan Manastireanu +// Type definitions for Apache Cordova Keyboard plugin v1.2.0 +// Project: https://github.com/cjpearson/cordova-plugin-keyboard +// Definitions by: Dan Manastireanu +// Jochen Becker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/** - * The Keyboard object provides some functions to customize the iOS keyboard. - * - * Supported Platforms: iOS - * - * This plugin has only been tested in Cordova 3.2 or greater, - * and its use in previous Cordova versions is not recommended - * (potential conflict with keyboard customization code present in the core in previous Cordova versions). - * - * If you do use this plugin in an older Cordova version (again, not recommended), - * you have to make sure the HideKeyboardFormAccessoryBar and KeyboardShrinksView preference values are always false, - * and only use the API functions to turn things on/off. - * - * This plugin supports the HideKeyboardFormAccessoryBar (boolean) - * and KeyboardShrinksView (boolean) preferences in config.xml. - * - * Permissions in config.xml - * - * - * - * - * - * - */ interface Keyboard { // Methods @@ -39,15 +16,20 @@ interface Keyboard { * This applies to apps that position their elements relative to the bottom of the WebView. * This is the default behaviour on Android, and makes a lot of sense when building apps as opposed to webpages. * + * Supported Platforms: + * - iOS + * * Example: * * Keyboard.shrinkView(true); * Keyboard.shrinkView(false); + * Keyboard.shrinkView(null, function (currentValue) { console.log(currentValue); }); * * * @param shrink + * @param successCallback A success callbackfunction */ - shrinkView(shrink:boolean): void, + shrinkView(shrink: boolean, successCallback?: (currentValue: any) => void): void, /** * Hide the keyboard toolbar. @@ -55,21 +37,29 @@ interface Keyboard { * Set to true to hide the additional toolbar that is on top of the keyboard. * This toolbar features the Prev, Next, and Done buttons. * + * Supported Platforms: + * - iOS + * * Example: * * Keyboard.hideFormAccessoryBar(true); * Keyboard.hideFormAccessoryBar(false); + * Keyboard.hideFormAccessoryBar(null, function (currentValue) { console.log(currentValue); }); * * * @param hide + * @param successCallback A success callbackfunction */ - hideFormAccessoryBar(hide:boolean): void, + hideFormAccessoryBar(hide: boolean, successCallback?: (currentValue: any) => void): void, /** * Disable scrolling when the the WebView is shrunk. * * Set to true to disable scrolling when the WebView is shrunk. * + * Supported Platforms: + * - iOS + * * Example: * * Keyboard.disableScrollingInShrinkView(true); @@ -77,8 +67,40 @@ interface Keyboard { * * * @param disable + * @param successCallback A success callbackfunction */ - disableScrollingInShrinkView(disable:boolean): void, + disableScrollingInShrinkView(disable: boolean, successCallback?: (currentValue: any) => void): void, + + /** + * Hide the keyboard + * + * Call this method to hide the keyboard + * + * Supported Platforms: + * - iOS + * - Android + * + * Example: + * + * Keyboard.hide(); + * + */ + hide(): void, + + /** + * Show the keyboard + * + * Call this method to show the keyboard. + * + * Supported Platforms: + * - Android + * + * Example: + * + * Keyboard.show(); + * + */ + show(): void, // Properties @@ -87,6 +109,9 @@ interface Keyboard { * * Read this property to determine if the keyboard is visible. * + * Supported Platforms: + * - iOS + * * Example: * * if (Keyboard.isVisible) { @@ -102,6 +127,9 @@ interface Keyboard { * Set this to true if you need that page scroll to beginning when keyboard is hiding. * This is allows to fix issue with elements declared with position: fixed, after keyboard is hiding. * + * Supported Platforms: + * - iOS + * * Example: * * Keyboard.automaticScrollToTopOnHiding = true; @@ -110,65 +138,48 @@ interface Keyboard { */ automaticScrollToTopOnHiding: boolean, - // Events + /** + * Deprecated Events + */ + onshow(): void, - /** - * If defined, this function is fired when keyboard fully shown. - * - * Attach handler to this event to be able to receive notification when keyboard is shown. - * - * Example: - * - * Keyboard.onshow = function () { - * // Describe your logic which will be run each time keyboard is shown. - * } - * - * - */ - onshow():void, - /** - * If defined, this function is fired when keyboard fully closed. - * - * Attach handler to this event to be able to receive notification when keyboard is closed. - * - * Example: - * - * Keyboard.onhide = function () { - * // Describe your logic which will be run each time keyboard is closed. - * } - * - * - */ - onhide():void, - /** - * If defined, this function is fired before keyboard will be shown. - * - * Attach handler to this event to be able to receive notification when keyboard is about to be shown on the screen. - * - * Example: - * - * Keyboard.onshowing = function () { - * // Describe your logic which will be run each time when keyboard is about to be shown. - * } - * - * - */ - onshowing():void, - /** - * If defined, this function is fired when keyboard is about to be closed. - * - * Attach handler to this event to be able to receive notification when keyboard is about to be closed. - * - * Example: - * - * Keyboard.onhiding = function () { - * // Describe your logic which will be run each time when keyboard is about to be closed. - * } - * - * - */ - onhiding():void, + onhide(): void, + onhiding(): void, + + onshowing(): void } -declare var Keyboard:Keyboard; +interface CordovaKeyboardEvent extends Event { + /** The height of the keyboard */ + keyboardHeight: number; +} + +interface WindowEventMap { + /** + * This event is fired when keyboard fully shown. + */ + 'keyboardDidShow': Event, + + /** + * This event is fired when the keyboard is fully closed. + */ + 'keyboardDidHide': Event, + + /** + * This event fires before keyboard will be shown. + */ + 'keyboardWillShow': Event, + + /** + * This event is fired when the keyboard is fully closed. + */ + 'keyboardWillHide': Event, + + /** + * This event is fired when the keyboard is fully closed. + */ + 'keyboardHeightWillChange': CordovaKeyboardEvent + } + +declare var Keyboard: Keyboard; diff --git a/types/css/index.d.ts b/types/css/index.d.ts index c892d5c3a2..be8f1323a0 100644 --- a/types/css/index.d.ts +++ b/types/css/index.d.ts @@ -112,7 +112,7 @@ export interface Comment extends Node { /** * The @charset at-rule. */ -export interface Charset { +export interface Charset extends Node { /** The part following @charset. */ charset?: string; } @@ -120,7 +120,7 @@ export interface Charset { /** * The @custom-media at-rule */ -export interface CustomMedia { +export interface CustomMedia extends Node { /** The ---prefixed name. */ name?: string; /** The part following the name. */ @@ -130,7 +130,7 @@ export interface CustomMedia { /** * The @document at-rule. */ -export interface Document { +export interface Document extends Node { /** The part following @document. */ document?: string; /** The vendor prefix in @document, or undefined if there is none. */ @@ -142,7 +142,7 @@ export interface Document { /** * The @font-face at-rule. */ -export interface FontFace { +export interface FontFace extends Node { /** Array of nodes with the types declaration and comment. */ declarations?: Array; } @@ -150,7 +150,7 @@ export interface FontFace { /** * The @host at-rule. */ -export interface Host { +export interface Host extends Node { /** Array of nodes with the types rule, comment and any of the at-rule types. */ rules?: Array; } @@ -158,7 +158,7 @@ export interface Host { /** * The @import at-rule. */ -export interface Import { +export interface Import extends Node { /** The part following @import. */ import?: string; } @@ -166,7 +166,7 @@ export interface Import { /** * The @keyframes at-rule. */ -export interface KeyFrames { +export interface KeyFrames extends Node { /** The name of the keyframes rule. */ name?: string; /** The vendor prefix in @keyframes, or undefined if there is none. */ @@ -175,7 +175,7 @@ export interface KeyFrames { keyframes?: Array; } -export interface KeyFrame { +export interface KeyFrame extends Node { /** The list of "selectors" of the keyframe rule, split on commas. Each “selector” is trimmed from whitespace. */ values?: Array; /** Array of nodes with the types declaration and comment. */ @@ -185,7 +185,7 @@ export interface KeyFrame { /** * The @media at-rule. */ -export interface Media { +export interface Media extends Node { /** The part following @media. */ media?: string; /** Array of nodes with the types rule, comment and any of the at-rule types. */ @@ -195,7 +195,7 @@ export interface Media { /** * The @namespace at-rule. */ -export interface Namespace { +export interface Namespace extends Node { /** The part following @namespace. */ namespace?: string; } @@ -203,7 +203,7 @@ export interface Namespace { /** * The @page at-rule. */ -export interface Page { +export interface Page extends Node { /** The list of selectors of the rule, split on commas. Each selector is trimmed from whitespace and comments. */ selectors?: Array; /** Array of nodes with the types declaration and comment. */ @@ -213,7 +213,7 @@ export interface Page { /** * The @supports at-rule. */ -export interface Supports { +export interface Supports extends Node { /** The part following @supports. */ supports?: string; /** Array of nodes with the types rule, comment and any of the at-rule types. */ @@ -223,16 +223,21 @@ export interface Supports { /** All at-rules. */ export type AtRule = Charset | CustomMedia | Document | FontFace | Host | Import | KeyFrames | Media | Namespace | Page | Supports; +/** + * A collection of rules + */ +export interface StyleRules { + /** Array of nodes with the types rule, comment and any of the at-rule types. */ + rules: Array; + /** Array of Errors. Errors collected during parsing when option silent is true. */ + parsingErrors?: Array +} + /** * The root node returned by css.parse. */ export interface Stylesheet extends Node { - stylesheet?: { - /** Array of nodes with the types rule, comment and any of the at-rule types. */ - rules?: Array; - /** Array of Errors. Errors collected during parsing when option silent is true. */ - parsingErrors?: Array - }; + stylesheet?: StyleRules; } // --------------------------------------------------------------------------------- diff --git a/types/cucumber/index.d.ts b/types/cucumber/index.d.ts index d72b3ee4ac..ce2f586d9b 100644 --- a/types/cucumber/index.d.ts +++ b/types/cucumber/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cucumber-js 2.0 +// Type definitions for cucumber-js 2.1 // Project: https://github.com/cucumber/cucumber-js // Definitions by: Abraão Alves // Jan Molak @@ -23,9 +23,7 @@ export interface TableDefinition { hashes(): Array<{ [colName: string]: string }>; } -export type StepDefinitionParam = string | number | CallbackStepDefinition | TableDefinition; - -export type StepDefinitionCode = (this: World, ...stepArgs: StepDefinitionParam[]) => PromiseLike | any | void; +export type StepDefinitionCode = (this: World, ...stepArgs: any[]) => any; export interface StepDefinitionOptions { timeout?: number; diff --git a/types/cypress/cypress-tests.ts b/types/cypress/cypress-tests.ts index ac987e757a..9502f1a63d 100644 --- a/types/cypress/cypress-tests.ts +++ b/types/cypress/cypress-tests.ts @@ -12,10 +12,13 @@ cy .get('.query-button') .contains('Save Form').should('have.class', 'btn'); +cy.location('host'); + cy .get('form') .find('input') - .then($input => $input.click()); + .then($input => $input.click()) + .then($input => $input.click(), {timeout: 12}); cy .wrap({ sum: (a: number, b: number, c: number) => a + b + c }) diff --git a/types/cypress/index.d.ts b/types/cypress/index.d.ts index e7f2a59447..1ffb365418 100644 --- a/types/cypress/index.d.ts +++ b/types/cypress/index.d.ts @@ -249,7 +249,8 @@ declare namespace Cypress { /** * @see https://on.cypress.io/api/location */ - location(options?: Loggable): Chainable; + location(options?: LoggableTimeoutable): Chainable; + location(key: string, options?: LoggableTimeoutable): Chainable; /** * @see https://on.cypress.io/api/log @@ -317,9 +318,9 @@ declare namespace Cypress { /** * @see https://on.cypress.io/api/route */ - route(url: string, response?: any): Chainable; - route(method: string, url: string, response?: any): Chainable; - route(fn: () => RouteOptions | RouteOptions): Chainable; + route(url: string | RegExp, response?: any): Chainable; + route(method: string, url: string | RegExp, response?: any): Chainable; + route(fn: (() => RouteOptions) | RouteOptions): Chainable; /** * @see https://on.cypress.io/api/screenshot @@ -369,7 +370,7 @@ declare namespace Cypress { /** * @see https://on.cypress.io/api/then */ - then(fn: (currentSubject: any) => any): Chainable; + then(fn: (currentSubject: any) => any, options?: Timeoutable): Chainable; /** * @see https://on.cypress.io/api/title diff --git a/types/d3-geo/index.d.ts b/types/d3-geo/index.d.ts index 4093b696e9..7efbb72010 100644 --- a/types/d3-geo/index.d.ts +++ b/types/d3-geo/index.d.ts @@ -36,7 +36,10 @@ export type GeoGeometryObjects = GeoJSON.GeometryObject | GeoSphere; export interface ExtendedGeometryCollection { type: string; bbox?: number[]; - crs?: GeoJSON.CoordinateReferenceSystem; + crs?: { + type: string; + properties: any; + }; geometries: GeometryType[]; } diff --git a/types/d3-selection/d3-selection-tests.ts b/types/d3-selection/d3-selection-tests.ts index 96d421f828..6019084be2 100644 --- a/types/d3-selection/d3-selection-tests.ts +++ b/types/d3-selection/d3-selection-tests.ts @@ -1036,6 +1036,19 @@ positions = d3Selection.touches(svg, changedTouches); positions = d3Selection.touches(g, changedTouches); positions = d3Selection.touches(h, changedTouches); +// clientPoint() --------------------------------------------------------------------- + +let clientPoint: [number, number]; +declare let mEvt: MouseEvent; +declare let tEvt: Touch; +declare let msgEvt: MSGestureEvent; +declare let customEvt: {clientX: number, clientY: number}; // minimally conforming object + +clientPoint = d3Selection.clientPoint(svg, mEvt); +clientPoint = d3Selection.clientPoint(g, tEvt); +clientPoint = d3Selection.clientPoint(h, msgEvt); +clientPoint = d3Selection.clientPoint(h, customEvt); + // --------------------------------------------------------------------------------------- // Tests of style // --------------------------------------------------------------------------------------- diff --git a/types/d3-selection/index.d.ts b/types/d3-selection/index.d.ts index abbb14db0f..b5231f37c2 100644 --- a/types/d3-selection/index.d.ts +++ b/types/d3-selection/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for D3JS d3-selection module 1.1 +// Type definitions for D3JS d3-selection module 1.2 // Project: https://github.com/d3/d3-selection/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.1 +// Last module patch version validated against: 1.2.0 // -------------------------------------------------------------------------- // Shared Type Definitions and Interfaces @@ -44,6 +44,14 @@ export interface EnterElement { */ export type ContainerElement = HTMLElement | SVGSVGElement | SVGGElement; +/** + * A User interface event (e.g. mouse event, touch or MSGestureEvent) with captured clientX and clientY properties. + */ +export interface ClientPointEvent { + clientX: number; + clientY: number; +} + /** * Interface for optional parameters map, when dispatching custom events * on a selection @@ -670,7 +678,8 @@ export interface Selection; /** - * Return the exit selection: existing DOM elements in the selection for which no new datum was found. - * The exit selection is determined by the previous selection.data, and is thus empty until the selection is - * joined to data. If the exit selection is retrieved more than once after a data join, subsequent calls return - * the empty selection. + * Returns the exit selection: existing DOM elements in the selection for which no new datum was found. + * (The exit selection is empty for selections not returned by selection.data.) * * IMPORTANT: The generic refers to the type of the old datum associated with the exit selection elements. * Ensure you set the generic to the correct type, if you need to access the data on the exit selection in @@ -972,6 +979,16 @@ export function touch(container: ContainerElement, touches: TouchList, identifie */ export function touches(container: ContainerElement, touches?: TouchList): Array<[number, number]>; +/** + * Returns the x and y coordinates of the specified event relative to the specified container. + * (The event may also be a touch.) The container may be an HTML or SVG container element, such as a G element or an SVG element. + * The coordinates are returned as a two-element array of numbers [x, y]. + * + * @param container Container element relative to which coordinates are calculated. + * @param event A User interface event (e.g. mouse event, touch or MSGestureEvent) with captured clientX and clientY properties. + */ +export function clientPoint(container: ContainerElement, event: ClientPointEvent): [number, number]; + // --------------------------------------------------------------------------- // style // --------------------------------------------------------------------------- diff --git a/types/d3/index.d.ts b/types/d3/index.d.ts index cb48077985..de522828ff 100644 --- a/types/d3/index.d.ts +++ b/types/d3/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3 standard bundle 4.11 +// Type definitions for D3JS d3 standard bundle 4.12 // Project: https://github.com/d3/d3 // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/dagre/dagre-tests.ts b/types/dagre/dagre-tests.ts index ae81c2c896..a29cf0128a 100644 --- a/types/dagre/dagre-tests.ts +++ b/types/dagre/dagre-tests.ts @@ -1,8 +1,39 @@ -const gDagre = new dagre.graphlib.Graph(); +const gDagre = new dagre.graphlib.Graph({compound: true, multigraph: false}); gDagre.setGraph({}) .setDefaultEdgeLabel(() => ({})) + .setDefaultNodeLabel(() => ({})) .setNode("a", {}) .setEdge("b", "c") .setEdge("c", "d", {class: "class"}); dagre.layout(gDagre); + +gDagre.edge({v: 'b', w: 'c'}); +gDagre.hasEdge({v: 'b', w: 'c'}); +gDagre.inEdges('c'); +gDagre.outEdges('c'); + +gDagre.setParent('a', 'b'); +gDagre.children('b'); +gDagre.hasNode('d'); +gDagre.neighbors('c'); +gDagre.node({}); +gDagre.parent('a'); +gDagre.predecessors('d'); +gDagre.successors('b'); + +gDagre.removeEdge('c', 'd').removeNode('d'); + +dagre.graphlib.json.read(dagre.graphlib.json.write(gDagre)); + +dagre.graphlib.alg.components(gDagre); +dagre.graphlib.alg.dijkstra(gDagre, 'a', (edge) => 5); +dagre.graphlib.alg.dijkstraAll(gDagre); +dagre.graphlib.alg.findCycles(gDagre); +dagre.graphlib.alg.floydWarchall(gDagre); +dagre.graphlib.alg.isAcyclic(gDagre); +dagre.graphlib.alg.postorder(gDagre, 'a'); +dagre.graphlib.alg.preorder(gDagre, ['b', 'c']); +dagre.graphlib.alg.prim(gDagre); +dagre.graphlib.alg.tarjam(gDagre); +dagre.graphlib.alg.topsort(gDagre); diff --git a/types/dagre/index.d.ts b/types/dagre/index.d.ts index 55d98b0535..6c5e5e00ec 100644 --- a/types/dagre/index.d.ts +++ b/types/dagre/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Qinfeng Chen // Lisa Vallfors // Pete Vilter +// David Newell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -10,24 +11,69 @@ export as namespace dagre; export namespace graphlib { class Graph { - edges(): Edge[]; - edge(id: any): any; - nodes(): string[]; - node(id: any): any; - setDefaultEdgeLabel(callback: string|(() => string|object)): Graph; - setDefaultNodeLabel(callback: string|(() => string|object)): 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; + + graph(): GraphLabel; + isDirected(): boolean; + isMultiGraph(): boolean; + setGraph(label: GraphLabel): Graph; + + edge(edgeObj: Edge): GraphEdge; + edge(outNodeName: string, inNodeName: string, name?: string): GraphEdge; + edgeCount(): number; + edges(): Edge[]; + hasEdge(edgeObj: Edge): boolean; + hasEdge(outNodeName: string, inNodeName: string, name?: string): boolean; + inEdges(inNodeName: string, outNodeName?: string): Edge[]|undefined; + outEdges(outNodeName: string, inNodeName?: string): Edge[]|undefined; + removeEdge(outNodeName: string, inNodeName: string): Graph; + setDefaultEdgeLabel(callback: string|((edge: Edge) => string|Label)): Graph; + setEdge(params: Edge, value?: string|{[key: string]: any}): Graph; + setEdge(sourceId: string, targetId: string, value?: string|Label, name?: string): Graph; + + children(parentName: string): string|undefined; hasNode(name: string): boolean; + neighbors(name: string): Node[]|undefined; + node(id: string|Label): Node; + nodeCount(): number; + nodes(): string[]; + parent(childName: string): string|undefined; + predecessors(name: string): Node[]|undefined; + removeNode(name: string): Graph; + setDefaultNodeLabel(callback: string|((nodeId: string) => string|Label)): Graph; + setNode(name: string, label: string|Label): Graph; + setParent(childName: string, parentName: string): void; + sinks(): Node[]; + sources(): Node[]; + successors(name: string): Node[]|undefined; + } + + namespace json { + function read(graph: any): Graph; + function write(graph: Graph): any; + } + + namespace alg { + function components(graph: Graph): string[][]; + function dijkstra(graph: Graph, source: string, weightFn?: WeightFn, edgeFn?: EdgeFn): any; + function dijkstraAll(graph: Graph, weightFn?: WeightFn, edgeFn?: EdgeFn): any; + function findCycles(graph: Graph): string[][]; + function floydWarchall(graph: Graph, weightFn?: WeightFn, edgeFn?: EdgeFn): any; + function isAcyclic(graph: Graph): boolean; + function postorder(graph: Graph, nodeNames: string|string[]): string[]; + function preorder(graph: Graph, nodeNames: string|string[]): string[]; + function prim(graph: Graph, weightFn?: WeightFn): Graph; + function tarjam(graph: Graph): string[][]; + function topsort(graph: Graph): string[]; } } +export interface Label { + [key: string]: any; +} +export type WeightFn = (edge: Edge) => number; +export type EdgeFn = (outNodeName: string) => GraphEdge[]; + export interface GraphLabel { width?: number; height?: number; @@ -43,10 +89,37 @@ export interface GraphLabel { ranker?: string; } -export function layout(graph: graphlib.Graph): void; +export interface NodeConfig { + width?: number; + height?: number; +} + +export interface EdgeConfig { + minlen: number; + weight: number; + width: number; + height: number; + lablepos: 'l'|'c'|'r'; + labeloffest: number; +} + +export function layout(graph: graphlib.Graph, layout?: GraphLabel&NodeConfig&EdgeConfig): void; export interface Edge { v: string; w: string; name?: string; } + +export interface GraphEdge { + points: Array<{x: number, y: number}>; + [key: string]: any; +} + +export interface Node { + x: number; + y: number; + width: number; + height: number; + [key: string]: any; +} diff --git a/types/daterangepicker/index.d.ts b/types/daterangepicker/index.d.ts index f01ffd59a3..4fddcc4fbd 100644 --- a/types/daterangepicker/index.d.ts +++ b/types/daterangepicker/index.d.ts @@ -25,6 +25,7 @@ declare namespace daterangepicker { startDate: moment.Moment; endDate: moment.Moment; + container: JQuery; setStartDate(date: Date | moment.Moment | string): void; setEndDate(date: Date | moment.Moment | string): void; diff --git a/types/dc/index.d.ts b/types/dc/index.d.ts index 7d893baf3e..62fbd8330c 100644 --- a/types/dc/index.d.ts +++ b/types/dc/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for DCJS // Project: https://github.com/dc-js/dc.js -// Definitions by: hans windhoff , matt traynham +// Definitions by: hans windhoff +// matt traynham +// matthias jobst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // this makes only sense together with d3 and crossfilter so you need the d3.d.ts and crossfilter.d.ts files @@ -49,8 +51,9 @@ declare namespace dc { format: Accessor; } + // http://dc-js.github.io/dc.js/docs/html/dc.units.html export interface UnitFunction { - (start: number, end: number, domain?: Array): number|Array; + (start: number|Date, end: number|Date, domain?: number|Array): number | Array; } export interface FloatPointUnits { @@ -135,12 +138,13 @@ declare namespace dc { minHeight: IGetSet; dimension: IGetSet; data: IGetSetComputed<(group: any) => Array, Array, T>; - group: IGetSet; + // http://dc-js.github.io/dc.js/docs/html/dc.baseMixin.html#group__anchor + group: IBiGetSet; ordering: IGetSet, T>; filterAll(): void; - select(selector: d3.Selection|string): d3.Selection; - selectAll(selector: d3.Selection|string): d3.Selection; - anchor(anchor: BaseMixin|d3.Selection|string, chartGroup?: string): d3.Selection; + select(selector: d3.Selection | string): d3.Selection; + selectAll(selector: d3.Selection | string): d3.Selection; + anchor(anchor: BaseMixin | d3.Selection | string, chartGroup?: string): d3.Selection; anchorName(): string; svg: IGetSet, d3.Selection>; resetSvg(): void; @@ -196,10 +200,11 @@ declare namespace dc { } export interface ColorMixin { - colors: IGetSet | Scale, T>; - ordinalColors(r: Array): void; - linearColors(r: Array): void; - colorAccessor: IGetSet, T>; + // http://dc-js.github.io/dc.js/docs/html/dc.colorMixin.html + colors: IGetSet | Scale | string, T>; + ordinalColors(r: Array): T; + linearColors(r: Array): T; + colorAccessor: IGetSet, T>; colorDomain: IGetSet, T>; calculateColorDomain(): void; getColor(datum: any, index?: number): string; @@ -291,7 +296,7 @@ declare namespace dc { dashStyle: IGetSet, LineChart>; renderArea: IGetSet; dotRadius: IGetSet; - renderDataPoints: IGetSet; + renderDataPoints: IGetSet; } export interface DataCountWidgetHTML { @@ -307,7 +312,7 @@ declare namespace dc { export interface DataTableWidget extends BaseMixin { size: IGetSet; showGroups: IGetSet; - columns: IGetSet|Columns>, DataTableWidget>; + columns: IGetSet | Columns>, DataTableWidget>; sortBy: IGetSet, DataTableWidget>; order: IGetSet<(a: any, b: any) => number, DataTableWidget>; } @@ -336,7 +341,7 @@ declare namespace dc { rightYAxis: IGetSet>; } - export interface CompositeChart extends ICompositeChart {} + export interface CompositeChart extends ICompositeChart { } export interface SeriesChart extends ICompositeChart { chart: IGetSet<(c: any) => BaseMixin, SeriesChart>; @@ -444,11 +449,16 @@ declare namespace dc { round: Round; utils: Utils; + // http://dc-js.github.io/dc.js/docs/html/core.js.html, Line 20 + version: string; + legend(): Legend; pieChart(parent: string, chartGroup?: string): PieChart; - barChart(parent: string, chartGroup?: string): BarChart; - lineChart(parent: string, chartGroup?: string): LineChart; + // http://dc-js.github.io/dc.js/docs/html/dc.barChart.html + barChart(parent: string | CompositeChart, chartGroup?: string): BarChart; + // http://dc-js.github.io/dc.js/docs/html/dc.lineChart.html + lineChart(parent: string | CompositeChart, chartGroup?: string): LineChart; dataCount(parent: string, chartGroup?: string): DataCountWidget; dataTable(parent: string, chartGroup?: string): DataTableWidget; dataGrid(parent: string, chartGroup?: string): DataGridWidget; @@ -463,5 +473,4 @@ declare namespace dc { heatMap(parent: string, chartGroup?: string): HeatMap; boxPlot(parent: string, chartGroup?: string): BoxPlot; } -} - +} \ No newline at end of file diff --git a/types/deepmerge/index.d.ts b/types/deepmerge/index.d.ts index 797e52c8a5..05f5c96d2e 100644 --- a/types/deepmerge/index.d.ts +++ b/types/deepmerge/index.d.ts @@ -18,3 +18,10 @@ declare namespace deepmerge { function all(objects: Array>, options?: Options): T; } + +declare global { + interface Window { + deepmerge(x: Partial, y: Partial, options?: deepmerge.Options): T; + deepmerge(x: T1, y: T2, options?: deepmerge.Options): T1 & T2; + } +} diff --git a/types/docker-file-parser/docker-file-parser-tests.ts b/types/docker-file-parser/docker-file-parser-tests.ts new file mode 100644 index 0000000000..21cd715f47 --- /dev/null +++ b/types/docker-file-parser/docker-file-parser-tests.ts @@ -0,0 +1,25 @@ +import { parse, CommandEntry, ParseOptions } from 'docker-file-parser'; + +const file = ` +FROM node:8 + +ADD . /opt/ +WORKDIR /opt + +RUN npm install --production + +EXPOSE 8080 +VOLUME /opt/scripts + +CMD ["npm", "start"] +`; + +const options: ParseOptions = { + includeComments: false +}; + +const result: CommandEntry[] = parse(file, options); +const line1Name = result[0].name; +const line1Number = result[0].lineno; +const line1Args = result[0].args; +const line1Raw = result[0].raw; diff --git a/types/docker-file-parser/index.d.ts b/types/docker-file-parser/index.d.ts new file mode 100644 index 0000000000..5263ef3353 --- /dev/null +++ b/types/docker-file-parser/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for docker-file-parser 1.0 +// Project: https://github.com/joyent/docker-file-parse +// Definitions by: Yash Kulshrestha +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface CommandEntry { + name: string; + args: string[]; + lineno: number; + raw: string; + error?: string; +} + +export interface ParseOptions { + includeComments: boolean; +} + +export function parse( + contents: string, + options?: ParseOptions +): CommandEntry[]; diff --git a/types/docker-file-parser/tsconfig.json b/types/docker-file-parser/tsconfig.json new file mode 100644 index 0000000000..7c529341c4 --- /dev/null +++ b/types/docker-file-parser/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "docker-file-parser-tests.ts" + ] +} diff --git a/types/docker-file-parser/tslint.json b/types/docker-file-parser/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/docker-file-parser/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dotdir-regex/dotdir-regex-tests.ts b/types/dotdir-regex/dotdir-regex-tests.ts new file mode 100644 index 0000000000..ff40d153f8 --- /dev/null +++ b/types/dotdir-regex/dotdir-regex-tests.ts @@ -0,0 +1,4 @@ +import dotdir = require('dotdir-regex'); + +// $ExpectType RegExp +dotdir(); diff --git a/types/dotdir-regex/index.d.ts b/types/dotdir-regex/index.d.ts new file mode 100644 index 0000000000..59b68ae322 --- /dev/null +++ b/types/dotdir-regex/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for dotdir-regex 1.0 +// Project: https://github.com/regexhq/dotdir-regex +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function dotdirRegex(): RegExp; + +export = dotdirRegex; diff --git a/types/dotdir-regex/tsconfig.json b/types/dotdir-regex/tsconfig.json new file mode 100644 index 0000000000..48f516abd8 --- /dev/null +++ b/types/dotdir-regex/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dotdir-regex-tests.ts" + ] +} diff --git a/types/dotdir-regex/tslint.json b/types/dotdir-regex/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dotdir-regex/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dotfile-regex/dotfile-regex-tests.ts b/types/dotfile-regex/dotfile-regex-tests.ts new file mode 100644 index 0000000000..f6bad1d84b --- /dev/null +++ b/types/dotfile-regex/dotfile-regex-tests.ts @@ -0,0 +1,4 @@ +import dotfile = require('dotfile-regex'); + +// $ExpectType RegExp +dotfile(); diff --git a/types/dotfile-regex/index.d.ts b/types/dotfile-regex/index.d.ts new file mode 100644 index 0000000000..3a96f4fbad --- /dev/null +++ b/types/dotfile-regex/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for dotfile-regex 1.0 +// Project: https://github.com/regexhq/dotfile-regex +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function dotfileRegex(): RegExp; + +export = dotfileRegex; diff --git a/types/dotfile-regex/tsconfig.json b/types/dotfile-regex/tsconfig.json new file mode 100644 index 0000000000..899be54b3b --- /dev/null +++ b/types/dotfile-regex/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dotfile-regex-tests.ts" + ] +} diff --git a/types/dotfile-regex/tslint.json b/types/dotfile-regex/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dotfile-regex/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/download/download-tests.ts b/types/download/download-tests.ts new file mode 100644 index 0000000000..7a498ef0dd --- /dev/null +++ b/types/download/download-tests.ts @@ -0,0 +1,30 @@ +import * as fs from 'fs'; +import download = require('download'); + +download('http://unicorn.com/foo.jpg', 'dist').then(() => { + console.log('done!'); +}); + +download('http://unicorn.com/foo.jpg').then(data => { + fs.writeFileSync('dist/foo.jpg', data); +}); + +download('unicorn.com/foo.jpg').pipe(fs.createWriteStream('dist/foo.jpg')); + +download('unicorn.com/foo.jpg', 'dest', { + body: '', + decompress: true, + encoding: 'utf8', + extract: true, + filename: 'filename', + followRedirect: true, + proxy: '', + query: '', + retries: (retry: number, error: any) => 4, + timeout: { + connect: 20, + request: 20, + socket: 20 + }, + useElectronNet: true +}); diff --git a/types/download/index.d.ts b/types/download/index.d.ts new file mode 100644 index 0000000000..f3af9778bf --- /dev/null +++ b/types/download/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for download 6.2 +// Project: https://github.com/kevva/download +// Definitions by: Nico Jansen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +interface TimeoutOptions { + connect?: number; + socket?: number; + request?: number; +} +type RetryFunction = (retry: number, error: any) => number; + +interface DownloadOptions { + body?: string | Buffer | NodeJS.ReadableStream; + encoding?: string | null; + query?: string | object; + timeout?: number | TimeoutOptions; + retries?: number | RetryFunction; + followRedirect?: boolean; + decompress?: boolean; + useElectronNet?: boolean; + /** + * If set to true, try extracting the file using decompress. + */ + extract?: boolean; + /** + * Name of the saved file. + */ + filename?: string; + /** + * Proxy endpoint + */ + proxy?: string; +} + +declare function download(url: string, destination?: string, options?: DownloadOptions): Promise & NodeJS.WritableStream & NodeJS.ReadableStream; + +export = download; diff --git a/types/download/tsconfig.json b/types/download/tsconfig.json new file mode 100644 index 0000000000..634ae5ab32 --- /dev/null +++ b/types/download/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "download-tests.ts" + ] +} diff --git a/types/download/tslint.json b/types/download/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/download/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 87172d9471..63821eda98 100644 --- a/types/draft-js/draft-js-tests.tsx +++ b/types/draft-js/draft-js-tests.tsx @@ -12,7 +12,17 @@ import { SelectionState, getDefaultKeyBinding, ContentState, - convertFromHTML + RawDraftInlineStyleRange, + RawDraftEntityRange, + RawDraftEntity, + RawDraftContentBlock, + RawDraftContentState, + DraftBlockType, + DraftInlineStyleType, + DraftEntityMutability, + DraftEntityType, + convertFromHTML, + convertToRaw } from 'draft-js'; const SPLIT_HEADER_BLOCK = 'split-header-block'; @@ -274,7 +284,7 @@ var INLINE_STYLES = [ const InlineStyleControls = (props: {editorState: EditorState, onToggle: (blockType: string) => void}) => { var currentStyle = props.editorState.getCurrentInlineStyle(); - return ( + return (
{INLINE_STYLES.map(type => , document.getElementById('target') ); + +const editorState = EditorState.createEmpty(); +const contentState = editorState.getCurrentContent(); +const rawContentState: RawDraftContentState = convertToRaw(contentState); + +rawContentState.blocks.forEach((block: RawDraftContentBlock) => { + block.entityRanges.forEach((entityRange: RawDraftEntityRange) => { + const { key, offset, length } = entityRange; + const entity: RawDraftEntity = rawContentState.entityMap[key]; + const entityType: DraftEntityType = entity.type; + const entityMutability: DraftEntityMutability = entity.mutability; + console.log(entityType, entityMutability, offset, length); + }); + + block.inlineStyleRanges.forEach((inlineStyleRange: RawDraftInlineStyleRange) => { + const { offset, length } = inlineStyleRange + const inlineStyle: DraftInlineStyleType = inlineStyleRange.style; + console.log(inlineStyle, offset, length); + }); +}); diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index bf7c2bac71..3eaa05aa30 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -262,9 +262,10 @@ declare namespace Draft { * or block types. */ "bold" | - "italic" | - "underline" | "code" | + "italic" | + "strikethrough" | + "underline" | /** * Split a block in two. @@ -328,6 +329,60 @@ declare namespace Draft { * another fragment or if the selected fragment shall be replaced */ type DraftInsertionType = "replace" | "before" | "after"; + + /** + * Valid inline styles. + */ + type DraftInlineStyleType = ( + "BOLD" | + "CODE" | + "ITALIC" | + "STRIKETHROUGH" | + "UNDERLINE" + ) + + /** + * Default entity types. + */ + type ComposedEntityType = ( + "LINK" | + "TOKEN" | + "PHOTO" | + "IMAGE" + ) + + /** + * Possible entity types. + */ + type DraftEntityType = string | ComposedEntityType; + + /** + * Possible "mutability" options for an entity. This refers to the behavior + * that should occur when inserting or removing characters in a text range + * with an entity applied to it. + * + * `MUTABLE`: + * The text range can be modified freely. Generally used in cases where + * the text content and the entity do not necessarily have a direct + * relationship. For instance, the text and URI for a link may be completely + * different. The user is allowed to edit the text as needed, and the entity + * is preserved and applied to any characters added within the range. + * + * `IMMUTABLE`: + * Not to be confused with immutable data structures used to represent the + * state of the editor. Immutable entity ranges cannot be modified in any + * way. Adding characters within the range will remove the entity from the + * entire range. Deleting characters will delete the entire range. Example: + * Facebook Page mentions. + * + * `SEGMENTED`: + * Segmented entities allow the removal of partial ranges of text, as + * separated by a delimiter. Adding characters wihin the range will remove + * the entity from the entire range. Deleting characters within a segmented + * entity will delete only the segments affected by the deletion. Example: + * Facebook User mentions. + */ + type DraftEntityMutability = "MUTABLE" | "IMMUTABLE" | "SEGMENTED"; } namespace Decorators { @@ -408,14 +463,24 @@ declare namespace Draft { } namespace Encoding { + import DraftInlineStyleType = Draft.Model.Constants.DraftInlineStyleType; + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; + import DraftEntityType = Draft.Model.Constants.DraftEntityType; + import ContentBlock = Draft.Model.ImmutableData.ContentBlock; import ContentState = Draft.Model.ImmutableData.ContentState; import DraftBlockRenderMap = Draft.Component.Base.DraftBlockRenderMap; - import DraftBlockType = Draft.Model.Constants.DraftBlockType; - import DraftEntityType = Draft.Model.Entity.DraftEntityType; - import DraftEntityMutability = Draft.Model.Entity.DraftEntityMutability; + /** + * A plain object representation of an inline style range. + */ + interface RawDraftInlineStyleRange { + style: DraftInlineStyleType; + offset: number; + length: number; + } /** * A plain object representation of an entity attribution. @@ -423,21 +488,12 @@ declare namespace Draft { * The `key` value corresponds to the key of the entity in the `entityMap` of * a `ComposedText` object, not for use with `DraftEntity.get()`. */ - interface EntityRange { + interface RawDraftEntityRange { key: number, offset: number, length: number, } - /** - * A plain object representation of an inline style range. - */ - interface InlineStyleRange { - style: string; - offset: number; - length: number; - } - /** * A plain object representation of an EntityInstance. */ @@ -456,8 +512,8 @@ declare namespace Draft { type: DraftBlockType; text: string; depth: number; - inlineStyleRanges: Array; - entityRanges: Array; + inlineStyleRanges: Array; + entityRanges: Array; data?: Object; } @@ -481,36 +537,8 @@ declare namespace Draft { } namespace Entity { - type ComposedEntityType = "LINK" | "TOKEN" | "PHOTO"; - type DraftEntityType = string | ComposedEntityType; - - /** - * An enum representing the possible "mutability" options for an entity. - * This refers to the behavior that should occur when inserting or removing - * characters in a text range with an entity applied to it. - * - * `MUTABLE`: - * The text range can be modified freely. Generally used in cases where - * the text content and the entity do not necessarily have a direct - * relationship. For instance, the text and URI for a link may be completely - * different. The user is allowed to edit the text as needed, and the entity - * is preserved and applied to any characters added within the range. - * - * `IMMUTABLE`: - * Not to be confused with immutable data structures used to represent the - * state of the editor. Immutable entity ranges cannot be modified in any - * way. Adding characters within the range will remove the entity from the - * entire range. Deleting characters will delete the entire range. Example: - * Facebook Page mentions. - * - * `SEGMENTED`: - * Segmented entities allow the removal of partial ranges of text, as - * separated by a delimiter. Adding characters wihin the range will remove - * the entity from the entire range. Deleting characters within a segmented - * entity will delete only the segments affected by the deletion. Example: - * Facebook User mentions. - */ - type DraftEntityMutability = "MUTABLE" | "IMMUTABLE" | "SEGMENTED"; + import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; + import DraftEntityType = Draft.Model.Constants.DraftEntityType; /** * A "document entity" is an object containing metadata associated with a @@ -579,10 +607,10 @@ declare namespace Draft { namespace ImmutableData { import DraftBlockType = Draft.Model.Constants.DraftBlockType; - import DraftDecoratorType = Draft.Model.Decorators.DraftDecoratorType; + import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; + import DraftEntityType = Draft.Model.Constants.DraftEntityType; - import DraftEntityType = Draft.Model.Entity.DraftEntityType; - import DraftEntityMutability = Draft.Model.Entity.DraftEntityMutability; + import DraftDecoratorType = Draft.Model.Decorators.DraftDecoratorType; type DraftInlineStyle = Immutable.OrderedSet; type BlockMap = Immutable.OrderedMap; @@ -938,6 +966,10 @@ import RichUtils = Draft.Model.Modifier.RichTextEditorUtil; import DefaultDraftBlockRenderMap = Draft.Model.ImmutableData.DefaultDraftBlockRenderMap; import DefaultDraftInlineStyle = Draft.Model.ImmutableData.DefaultDraftInlineStyle; +import RawDraftInlineStyleRange = Draft.Model.Encoding.RawDraftInlineStyleRange; +import RawDraftEntityRange = Draft.Model.Encoding.RawDraftEntityRange; +import RawDraftEntity = Draft.Model.Encoding.RawDraftEntity; +import RawDraftContentBlock = Draft.Model.Encoding.RawDraftContentBlock; import RawDraftContentState = Draft.Model.Encoding.RawDraftContentState; import convertFromRaw = Draft.Model.Encoding.convertFromRawToDraftState; import convertToRaw = Draft.Model.Encoding.convertFromDraftStateToRaw; @@ -950,6 +982,9 @@ import getVisibleSelectionRect = Draft.Component.Selection.getVisibleSelectionRe import DraftEditorCommand = Draft.Model.Constants.DraftEditorCommand; import DraftDragType = Draft.Model.Constants.DraftDragType; import DraftBlockType = Draft.Model.Constants.DraftBlockType; +import DraftInlineStyleType = Draft.Model.Constants.DraftInlineStyleType; +import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; +import DraftEntityType = Draft.Model.Constants.DraftEntityType; import DraftRemovalDirection = Draft.Model.Constants.DraftRemovalDirection; import DraftHandleValue = Draft.Model.Constants.DraftHandleValue; import DraftInsertionType = Draft.Model.Constants.DraftInsertionType; @@ -979,6 +1014,10 @@ export { DefaultDraftBlockRenderMap, DefaultDraftInlineStyle, + RawDraftInlineStyleRange, + RawDraftEntityRange, + RawDraftEntity, + RawDraftContentBlock, RawDraftContentState, convertFromRaw, convertToRaw, @@ -991,6 +1030,9 @@ export { DraftEditorCommand, DraftDragType, DraftBlockType, + DraftInlineStyleType, + DraftEntityType, + DraftEntityMutability, DraftRemovalDirection, DraftHandleValue, DraftInsertionType, diff --git a/types/dygraphs/index.d.ts b/types/dygraphs/index.d.ts index c8617b18fc..6e45d5ccd7 100644 --- a/types/dygraphs/index.d.ts +++ b/types/dygraphs/index.d.ts @@ -526,6 +526,12 @@ declare namespace dygraphs { */ highlightSeriesBackgroundAlpha?: number; + /** + * Sets the background color used to fade out the series in conjunction with 'highlightSeriesBackgroundAlpha'. + * Default: rgb(255, 255, 255) + */ + highlightSeriesBackgroundColor?: string; + /** * When set, the options from this object are applied to the timeseries closest to the mouse * pointer for interactive highlighting. See also 'highlightCallback'. Example: diff --git a/types/dynogels/dynogels-tests.ts b/types/dynogels/dynogels-tests.ts new file mode 100644 index 0000000000..ca16707256 --- /dev/null +++ b/types/dynogels/dynogels-tests.ts @@ -0,0 +1,795 @@ +import dynogels = require("dynogels"); +import { DynamoDB } from "aws-sdk"; +import * as Joi from "joi"; + +// AWS Configs +dynogels.AWS.config.loadFromPath('credentials.json'); +dynogels.AWS.config.update({ region: "REGION" }); + +// Define a Model +const Account = dynogels.define('Account', { + hashKey: 'email', + + // add the timestamp attributes (updatedAt, createdAt) + timestamps: true, + + schema: { + email: Joi.string().email(), + name: Joi.string(), + age: Joi.number(), + roles: dynogels.types.stringSet(), + settings: { + nickname: Joi.string(), + acceptedTerms: Joi.boolean().default(false), + test: { + evan: Joi.string() + } + } + } +}); + +const BlogPost = dynogels.define('BlogPost', { + hashKey: 'email', + rangeKey: 'title', + schema: { + email: Joi.string().email(), + title: Joi.string(), + content: Joi.binary(), + tags: dynogels.types.stringSet(), + } +}); + +const BlogPost1 = dynogels.define('BlogPost', { + hashKey: 'email', + rangeKey: 'title', + schema: { + email: Joi.string().email(), + title: Joi.string() + }, + validation: { + // allow properties not defined in the schema + allowUnknown: true + } +}); + +// Create Tables +dynogels.createTables((err) => { }); + +dynogels.createTables({ + BlogPost: { readCapacity: 5, writeCapacity: 10 }, + Account: { + readCapacity: 20, + writeCapacity: 4, + streamSpecification: { + streamEnabled: true, + streamViewType: 'NEW_IMAGE' + } + } +}, (err) => { }); + +dynogels.createTables({ + $dynogels: { pollingInterval: 100 } +}, (err) => { }); + +// Delete Table +BlogPost.deleteTable((err) => { }); + +// UUID +const Tweet = dynogels.define('Tweet', { + hashKey: 'TweetID', + timestamps: true, + schema: { + TweetID: dynogels.types.uuid(), + content: Joi.string(), + } +}); + +// Configuration +const Account1 = dynogels.define('Account', { + hashKey: 'email', + + // add the timestamp attributes (updatedAt, createdAt) + timestamps: true, + + schema: { + email: Joi.string().email(), + } +}); + +const Account2 = dynogels.define('Account', { + hashKey: 'email', + + // enable timestamps support + timestamps: true, + + // I don't want createdAt + createdAt: false, + + // I want updatedAt to actually be called updateTimestamp + updatedAt: 'updateTimestamp', + + schema: { + email: Joi.string().email(), + } +}); + +const Event = dynogels.define('Event', { + hashKey: 'name', + schema: { + name: Joi.string(), + total: Joi.number() + }, + + tableName: 'deviceEvents' +}); + +const Event1 = dynogels.define('Event', { + hashKey: 'name', + schema: { + name: Joi.string(), + total: Joi.number() + }, + + // store monthly event data + tableName: () => { + const d = new Date(); + return ['events', d.getFullYear(), d.getMonth() + 1].join('_'); + } +}); + +Account.config({ tableName: 'AccountsTable' }); + +const dynamodb = new DynamoDB(); +Account.config({ dynamodb }); + +// or globally use custom DynamoDB instance +// all defined models will now use this driver +dynogels.dynamoDriver(dynamodb); + +// Saving Models To DynamoDB +Account.create({ email: 'foo@example.com', name: 'Foo Bar', age: 21 }, (err, acc) => { + acc.get('email'); +}); + +const acc = new Account({ email: 'test@example.com', name: 'Test Example' }); +acc.save((err) => { + acc.get('email'); +}); + +BlogPost.create({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + content: 'Today, we are excited to announce the limited preview...' +}, (err, post) => { }); + +const item1 = { email: 'foo1@example.com', name: 'Foo 1', age: 10 }; +const item2 = { email: 'foo2@example.com', name: 'Foo 2', age: 20 }; +const item3 = { email: 'foo3@example.com', name: 'Foo 3', age: 30 }; + +Account.create([item1, item2, item3], (err, accounts) => { }); + +const params: dynogels.CreateItemOptions = {}; + +params.ConditionExpression = '#i <> :x'; +params.ExpressionAttributeNames = { '#i': 'id' }; +params.ExpressionAttributeValues = { ':x': 123 }; + +Account.create({ id: 123, name: 'Kurt Warner' }, params, (error, acc) => { }); + +// setting overwrite to false will generate +// the same Condition Expression as in the previous example +Account.create({ id: 123, name: 'Kurt Warner' }, { overwrite: false }, (error, acc) => { }); + +// Updating +Account.update({ email: 'foo@example.com', name: 'Bar Tester' }, (err, acc) => { }); + +Account.update({ email: 'foo@example.com', name: 'Bar Tester' }, { ReturnValues: 'ALL_OLD' }, (err, acc) => { }); + +// Only update the account if the current age of the account is 22 +Account.update({ email: 'foo@example.com', name: 'Bar Tester' }, { expected: { age: 22 } }, (err, acc) => { }); + +// setting an attribute to null will delete the attribute from DynamoDB +Account.update({ email: 'foo@example.com', age: null }, (err, acc) => { }); + +Account.update( + { email: 'foo@example.com', name: 'FooBar Testers' }, + { expected: { email: { Exists: true } } }, + (err, acc) => { } +); + +Account.update( + { email: 'baz@example.com', name: 'Bar Tester' }, + { expected: { email: { Exists: true } } }, + (err, acc) => { } +); + +Account.update({ email: 'foo@example.com', age: { $add: 1 } }, (err, acc) => { }); + +BlogPost.update({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + tags: { $add: 'cloud' } +}, (err, post) => { }); + +BlogPost.update({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + tags: { $add: ['cloud', 'dynamodb'] } +}, (err, post) => { }); + +BlogPost.update({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + tags: { $del: 'cloud' } +}, (err, post) => { }); + +BlogPost.update({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + tags: { $del: ['aws', 'node'] } +}, (err, post) => { }); + +const params1: dynogels.UpdateItemOptions = {}; +params1.UpdateExpression = 'SET #year = #year + :inc, #dir.titles = list_append(#dir.titles, :title), #act[0].firstName = :firstName ADD tags :tag'; +params1.ConditionExpression = '#year = :current'; +params1.ExpressionAttributeNames = { + '#year': 'releaseYear', + '#dir': 'director', + '#act': 'actors' +}; + +params1.ExpressionAttributeValues = { + ':inc': 1, + ':current': 2001, + ':title': ['The Man'], + ':firstName': 'Rob', + ':tag': dynogels.Set(['Sports', 'Horror'], 'S') +}; + +BlogPost.update({ title: 'Movie 0', description: 'This is a description' }, params1, (err, mov) => { }); + +// Deleting +Account.destroy('foo@example.com', (err) => { }); + +// Destroy model using hash and range key +BlogPost.destroy('foo@example.com', 'Hello World!', (err) => { }); + +BlogPost.destroy({ email: 'foo@example.com', title: 'Another Post' }, (err) => { }); + +Account.destroy('foo@example.com', { ReturnValues: 'ALL_OLD' }, (err, acc) => { }); + +Account.destroy('foo@example.com', { expected: { age: 22 } }, (err) => { }); + +const params2: dynogels.DestroyItemOptions = {}; +params2.ConditionExpression = '#v = :x'; +params2.ExpressionAttributeNames = { '#v': 'version' }; +params2.ExpressionAttributeValues = { ':x': '2' }; + +Account.destroy({ id: 123 }, params2, (err, acc) => { }); + +// Loading Models from DynamoDB +Account.get('test@example.com', (err, acc) => { + console.log('got account', acc.get('email')); +}); + +Account.get('test@example.com', { ConsistentRead: true }, (err, acc) => { }); + +Account.get('test@example.com', { ConsistentRead: true, AttributesToGet: ['name', 'age'] }, (err, acc) => { }); + +BlogPost.get('werner@example.com', 'dynamodb-keeps-getting-better-and-cheaper', (err, post) => { }); + +BlogPost.get({ email: 'werner@example.com', title: 'Expanding the Cloud' }, (err, post) => { }); + +BlogPost.get({ id: '123456789' }, { ProjectionExpression: 'email, age, settings.nickname' }, (err, acc) => { }); + +// Query + +const callback = () => { }; +// query for blog posts by werner@example.com +BlogPost + .query('werner@example.com') + .exec(callback); + +// same as above, but load all results +BlogPost + .query('werner@example.com') + .loadAll() + .exec(callback); + +// only load the first 5 posts by werner +BlogPost + .query('werner@example.com') + .limit(5) + .exec(callback); + +// query for posts by werner where the tile begins with 'Expanding' +BlogPost + .query('werner@example.com') + .where('title').beginsWith('Expanding') + .exec(callback); + +// return only the count of documents that begin with the title Expanding +BlogPost + .query('werner@example.com') + .where('title').beginsWith('Expanding') + .select('COUNT') + .exec(callback); + +// query the first 10 posts by werner@example.com but only return +// the title and content from posts where the title starts with 'Expanding' +// WARNING: See notes below on the implementation of limit in DynamoDB +BlogPost + .query('werner@example.com') + .where('title').beginsWith('Expanding') + .attributes(['title', 'content']) + .limit(10) + .exec(callback); + +// sorting by title ascending +BlogPost + .query('werner@example.com') + .ascending() + .exec(callback); + +// sorting by title descending +BlogPost + .query('werner@example.com') + .descending() + .exec(callback); + +// All query options are chainable +BlogPost + .query('werner@example.com') + .where('title').gt('Expanding') + .attributes(['title', 'content']) + .limit(10) + .ascending() + .loadAll() + .exec(callback); + +// Traversing Map Data Types +Account + .query('werner@example.com') + .filter('settings.acceptedTerms').equals(true) + .exec(callback); + +BlogPost + .query('werner@example.com') + .where('title').equals('Expanding') + .exec(); + +// less than equals +BlogPost + .query('werner@example.com') + .where('title').lte('Expanding') + .exec(); + +// less than +BlogPost + .query('werner@example.com') + .where('title').lt('Expanding') + .exec(); + +// greater than +BlogPost + .query('werner@example.com') + .where('title').gt('Expanding') + .exec(); + +// greater than equals +BlogPost + .query('werner@example.com') + .where('title').gte('Expanding') + .exec(); + +// attribute doesn't exist +BlogPost + .query('werner@example.com') + .where('title').null() + .exec(); + +// attribute exists +BlogPost + .query('werner@example.com') + .where('title').exists() + .exec(); + +BlogPost + .query('werner@example.com') + .where('title').beginsWith('Expanding') + .exec(); + +BlogPost + .query('werner@example.com') + .where('title').between('foo@example.com', 'test@example.com') + .exec(); + +BlogPost + .query('werner@example.com') + .where('title').equals('Expanding') + .filter('tags').contains('cloud') + .exec(); + +BlogPost + .query('werner@example.com') + .filterExpression('#title < :t') + .expressionAttributeValues({ ':t': 'Expanding' }) + .expressionAttributeNames({ '#title': 'title' }) + .projectionExpression('#title, tag') + .exec(); + +const GameScore = dynogels.define('GameScore', { + hashKey: 'userId', + rangeKey: 'gameTitle', + schema: { + userId: Joi.string(), + gameTitle: Joi.string(), + topScore: Joi.number(), + topScoreDateTime: Joi.date(), + wins: Joi.number(), + losses: Joi.number() + }, + indexes: [{ + hashKey: 'gameTitle', rangeKey: 'topScore', name: 'GameTitleIndex', type: 'global' + }] +}); + +GameScore + .query('Galaxy Invaders') + .usingIndex('GameTitleIndex') + .descending() + .exec(callback); + +const GameScore1 = dynogels.define('GameScore', { + hashKey: 'userId', + rangeKey: 'gameTitle', + schema: { + userId: Joi.string(), + gameTitle: Joi.string(), + topScore: Joi.number(), + topScoreDateTime: Joi.date(), + wins: Joi.number(), + losses: Joi.number() + }, + indexes: [{ + hashKey: 'gameTitle', + rangeKey: 'topScore', + name: 'GameTitleIndex', + type: 'global', + projection: { NonKeyAttributes: ['wins'], ProjectionType: 'INCLUDE' } // optional, defaults to ALL + }] +}); + +GameScore + .query('Galaxy Invaders') + .usingIndex('GameTitleIndex') + .where('topScore').gt(1000) + .descending() + .exec((err, data) => { }); + +const BlogPost5 = dynogels.define('Account', { + hashKey: 'email', + rangeKey: 'title', + schema: { + email: Joi.string().email(), + title: Joi.string(), + content: Joi.binary(), + PublishedDateTime: Joi.date() + }, + + indexes: [{ + hashKey: 'email', rangeKey: 'PublishedDateTime', type: 'local', name: 'PublishedIndex' + }] +}); + +BlogPost + .query('werner@example.com') + .usingIndex('PublishedIndex') + .descending() + .exec(callback); + +BlogPost + .query('werner@example.com') + .usingIndex('PublishedIndex') + .ascending() + .exec(callback); + +BlogPost + .query('werner@example.com') + .usingIndex('PublishedIndex') + .descending() + .loadAll() + .exec(callback); + +// scan all accounts, returning the first page or results +Account.scan().exec(callback); + +// scan all accounts, this time loading all results +// note this will potentially make several calls to DynamoDB +// in order to load all results +Account + .scan() + .loadAll() + .exec(callback); + +// Load 20 accounts +Account + .scan() + .limit(20) + .exec(); + +// Load All accounts, 20 at a time per request +Account + .scan() + .limit(20) + .loadAll() + .exec(); + +// Load accounts which match a filter +// only return email and created attributes +// and return back the consumed capacity the request took +Account + .scan() + .where('email').gte('f@example.com') + .attributes(['email', 'created']) + .returnConsumedCapacity() + .exec(); + +// Load All accounts, if settings.acceptedTerms is true +Account + .scan() + .where('settings.acceptedTerms').equals(true) + .exec(); + +// Returns number of matching accounts, rather than the matching accounts themselves +Account + .scan() + .where('age').gte(21) + .select('COUNT') + .exec(); + +// Start scan using start key +Account + .scan() + .where('age').notNull() + .startKey('foo@example.com') + .exec(); + +// equals +Account + .scan() + .where('name').equals('Werner') + .exec(); + +// not equals +Account + .scan() + .where('name').ne('Werner') + .exec(); + +// less than equals +Account + .scan() + .where('name').lte('Werner') + .exec(); + +// less than +Account + .scan() + .where('name').lt('Werner') + .exec(); + +// greater than equals +Account + .scan() + .where('name').gte('Werner') + .exec(); + +// greater than +Account + .scan() + .where('name').gt('Werner') + .exec(); + +// name attribute doesn't exist +Account + .scan() + .where('name').null() + .exec(); + +// name attribute exists +Account + .scan() + .where('name').notNull() + .exec(); + +// contains +Account + .scan() + .where('name').contains('ner') + .exec(); + +// not contains +Account + .scan() + .where('name').notContains('ner') + .exec(); + +// in +Account + .scan() + .where('name').in(['foo@example.com', 'bar@example.com']) + .exec(); + +// begins with +Account + .scan() + .where('name').beginsWith('Werner') + .exec(); + +// between +Account + .scan() + .where('name').between('Bar', 'Foo') + .exec(); + +// multiple filters +Account + .scan() + .where('name').equals('Werner') + .where('age').notNull() + .exec(); + +Account.scan() + .filterExpression('#age BETWEEN :low AND :high AND begins_with(#email, :e)') + .expressionAttributeValues({ ':low': 18, ':high': 22, ':e': 'test1' }) + .expressionAttributeNames({ '#age': 'age', '#email': 'email' }) + .projectionExpression('#age, #email') + .exec(); + +const totalSegments = 8; + +Account.parallelScan(totalSegments) + .where('age').gte(18) + .attributes('age') + .exec(callback); + +// Load All accounts +Account + .parallelScan(totalSegments) + .exec(); + +Account.getItems(['foo@example.com', 'bar@example.com', 'test@example.com'], (err, accounts) => { + console.log(`loaded ${accounts.length} accounts`); // prints loaded 3 accounts +}); + +// Get both accounts, using a consistent read +Account.getItems(['foo@example.com', 'bar@example.com'], { ConsistentRead: true }, (err, accounts) => { + console.log(`loaded ${accounts.length} accounts`); // prints loaded 2 accounts +}); + +// Streaming API + +const stream = Account.parallelScan(4).exec(); + +stream.on('readable', () => { + console.log('single parallel scan response', stream.read()); +}); + +stream.on('end', () => { + console.log('Parallel scan of accounts finished'); +}); + +const querystream = BlogPost.query('werner@dynogels.com').loadAll().exec(); + +querystream.on('readable', () => { + console.log('single query response', stream.read()); +}); + +querystream.on('end', () => { + console.log('query for blog posts finished'); +}); + +// Dynamic Table Names + +const Event2 = dynogels.define('Event', { + hashKey: 'name', + schema: { + name: Joi.string(), + total: Joi.number() + }, + + // store monthly event data + tableName: () => { + const d = new Date(); + return ['events', d.getFullYear(), d.getMonth() + 1].join('_'); + } +}); + +// Logging + +const accountLogger = { + info: (...args: any[]) => { }, + warn: (...args: any[]) => { } +}; + +dynogels.log = accountLogger; + +const Account3 = dynogels.define('Account', { + hashKey: 'email', + log: accountLogger +}); // INFO level on account table + +const Account4 = dynogels.define('Account', { + hashKey: 'email', + + // add the timestamp attributes (updatedAt, createdAt) + timestamps: true, + + schema: { + email: Joi.string().email(), + name: Joi.string().required(), + age: Joi.number(), + } +}); + +Account.create({ email: 'test@example.com', name: 'Test Account' }, (err, acc) => { + console.log('created account at', acc.get('created')); // prints created Date + + acc.set({ age: 22 }); + + acc.update((err) => { + console.log('updated account age'); + }); +}); + +// For models with range keys you must pass in objects of hash and range key attributes +const postKey1 = { email: 'test@example.com', title: 'Hello World!' }; +const postKey2 = { email: 'test@example.com', title: 'Another Post' }; + +BlogPost.getItems([postKey1, postKey2], (err, posts) => { + console.log('loaded posts'); +}); + +dynogels.log.info("test", "123", {}); +dynogels.log.warn("test", "123", {}); + +// Lifecycle hooks +Account.before('create', (data, next) => { + if (!data.name) { + data.name = 'Foo Bar'; + } + + next(null, data); +}); + +Account.before('update', (data, next) => { + data.age = 45; + next(null, data); +}); + +Account.after('create', item => { + console.log('Account created', item.get()); +}); + +Account.after('update', item => { + console.log('Account updated', item.get()); +}); + +Account.after('destroy', item => { + console.log('Account destroyed', item.get()); +}); + +dynogels.createTables(err => { + if (err) { + process.exit(1); + } + + Account.create({ email: 'test11@example.com' }, (err, acc) => { + acc.set({ age: 25 }); + + acc.update(() => { + acc.destroy({ ReturnValues: 'ALL_OLD' }); + }); + }); +}); diff --git a/types/dynogels/index.d.ts b/types/dynogels/index.d.ts new file mode 100644 index 0000000000..2e4c5acbf4 --- /dev/null +++ b/types/dynogels/index.d.ts @@ -0,0 +1,263 @@ +// Type definitions for dynogels 8.0 +// Project: https://github.com/clarkie/dynogels#readme +// Definitions by: Spartan Labs +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +export import AWS = require("aws-sdk"); +import * as joi from "joi"; +import stream = require("stream"); + +// Dynogels Data Members +export let log: Log; +export let models: { [key: string]: Model }; +export let types: { + stringSet(): joi.AnySchema; + numberSet(): joi.AnySchema; + binarySet(): joi.AnySchema; + uuid(): joi.AnySchema; + timeUUID(): joi.AnySchema; +}; + +export interface Log { + info(...args: any[]): void; + warn(...args: any[]): void; +} + +// Dynogels global functions +export function dynamoDriver(dynamoDB: AWS.DynamoDB): AWS.DynamoDB; +export function reset(): void; +export function define(modelName: string, config: ModelConfiguration): Model; +export function createTables(callback: (err: string) => void): void; +export function createTables(options: { [key: string]: CreateTablesOptions } | DynogelsGlobalOptions, callback: (err: string) => void): void; +export function Set(...args: any[]): any; + +export interface DynogelsGlobalOptions { + $dynogels: { + pollingInterval: number; + }; +} + +export interface CreateTablesOptions { + readCapacity?: number; + writeCapacity?: number; + streamSpecification?: { + streamEnabled: boolean; + streamViewType: string; + }; +} + +export type LifeCycleAction = "create" | "update" | "destroy"; + +// Dynogels Model +export interface Model { + new(attrs: { [key: string]: any }): Item; + + get(hashKey: any, rangeKey: any, options: GetItemOptions, callback: DynogelsItemCallback): void; + get(haskKey: any, options: GetItemOptions, callback: DynogelsItemCallback): void; + get(hashKey: any, callback: DynogelsItemCallback): void; + get(hashKey: any, rangeKey: any, callback: DynogelsItemCallback): void; + create(item: any, options: CreateItemOptions, callback: DynogelsItemCallback): void; + create(item: any, callback: DynogelsItemCallback): void; + update(item: any, options: UpdateItemOptions, callback: DynogelsItemCallback): void; + update(item: any, callback: DynogelsItemCallback): void; + destroy(hashKey: any, rangeKey: any, options: DestroyItemOptions, callback: DynogelsItemCallback): void; + destroy(haskKey: any, options: DestroyItemOptions, callback: DynogelsItemCallback): void; + destroy(hashKey: any, callback: DynogelsItemCallback): void; + destroy(hashKey: any, rangeKey: any, callback: DynogelsItemCallback): void; + destroy(item: any, options: DestroyItemOptions, callback: DynogelsItemCallback): void; + destroy(item: any, callback: DynogelsItemCallback): void; + query(hashKey: any): Query; + scan(): Scan; + parallelScan(totalSegments: number): Scan; + getItems(items: string[] | Array<{ [key: string]: string }>, callback: (err: Error, items: any[]) => void): void; + getItems(items: string[] | Array<{ [key: string]: string }>, options: GetItemOptions, callback: (err: Error, items: any[]) => void): void; + batchGetItems(items: string[] | Array<{ [key: string]: string }>, callback: (err: Error, items: any[]) => void): void; + batchGetItems(items: string[] | Array<{ [key: string]: string }>, options: GetItemOptions, callback: (err: Error, items: any[]) => void): void; + createTable(options: { [key: string]: CreateTablesOptions } | DynogelsGlobalOptions, callback: (err: Error, data: AWS.DynamoDB.CreateTableOutput) => void): void; + createTable(callback: (err: Error, data: AWS.DynamoDB.CreateTableOutput) => void): void; + updateTable(throughput: Throughput, callback: (err: Error, data: AWS.DynamoDB.UpdateTableOutput) => void): void; + updateTable(callback: (err: Error, data: AWS.DynamoDB.UpdateTableOutput) => void): void; + describeTable(callback: (err: Error, data: AWS.DynamoDB.DescribeTableOutput) => void): void; + deleteTable(callback: (err: Error) => void): void; + tableName(): string; + + after(action: LifeCycleAction, listner: (item: Item) => void): void; + before(action: LifeCycleAction, listner: (data: any, next: (err: Error | null, data: any) => void) => void): void; + config(config: ModelConfig): { name: string }; +} + +export type DynogelsItemCallback = (err: Error, data: Item) => void; + +export interface Throughput { + readCapacity: number; + writeCapacity: number; +} + +export interface CreateItemOptions { + expected?: { [key: string]: any }; + overwrite?: boolean; + + Expected?: AWS.DynamoDB.ExpectedAttributeMap; + ReturnValues?: AWS.DynamoDB.ReturnValue; + ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; + ReturnItemCollectionMetrics?: AWS.DynamoDB.ReturnItemCollectionMetrics; + ConditionalOperator?: AWS.DynamoDB.ConditionalOperator; + ConditionExpression?: AWS.DynamoDB.ConditionExpression; + ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; + ExpressionAttributeValues?: { [key: string]: any }; +} + +export interface UpdateItemOptions { + expected?: { [key: string]: any }; + + AttributeUpdates?: AWS.DynamoDB.AttributeUpdates; + Expected?: AWS.DynamoDB.ExpectedAttributeMap; + ConditionalOperator?: AWS.DynamoDB.ConditionalOperator; + ReturnValues?: AWS.DynamoDB.ReturnValue; + ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; + ReturnItemCollectionMetrics?: AWS.DynamoDB.ReturnItemCollectionMetrics; + UpdateExpression?: AWS.DynamoDB.UpdateExpression; + ConditionExpression?: AWS.DynamoDB.ConditionExpression; + ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; + ExpressionAttributeValues?: { [key: string]: any }; +} + +export interface DestroyItemOptions { + Expected?: AWS.DynamoDB.ExpectedAttributeMap; + ConditionalOperator?: AWS.DynamoDB.ConditionalOperator; + ReturnValues?: AWS.DynamoDB.ReturnValue; + ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; + ReturnItemCollectionMetrics?: AWS.DynamoDB.ReturnItemCollectionMetrics; + ConditionExpression?: AWS.DynamoDB.ConditionExpression; + ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; + ExpressionAttributeValues?: { [key: string]: any }; +} + +export interface GetItemOptions { + AttributesToGet?: AWS.DynamoDB.AttributeNameList; + ConsistentRead?: AWS.DynamoDB.ConsistentRead; + ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; + ProjectionExpression?: AWS.DynamoDB.ProjectionExpression; + ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; +} + +export interface ModelConfig { + tableName?: string; + docClient?: any; + dynamodb?: AWS.DynamoDB; +} + +// Dynogels Item +export interface Item { + get(key?: string): { [key: string]: any }; + set(params: {}): Item; + save(callback?: DynogelsItemCallback): void; + update(options: UpdateItemOptions, callback?: DynogelsItemCallback): void; + update(callback?: DynogelsItemCallback): void; + destroy(options: DestroyItemOptions, callback?: DynogelsItemCallback): void; + destroy(callback?: DynogelsItemCallback): void; + toJSON(): any; + toPlainObject(): any; +} + +export interface BaseChain { + equals(value: any): T; + eq(value: any): T; + lte(value: any): T; + lt(value: any): T; + gte(value: any): T; + gt(value: any): T; + null(): T; + exists(): T; + beginsWith(value: any): T; + between(value1: any, value2: any): T; +} + +export interface ExtendedChain extends BaseChain { + contains(value: any): T; + notContains(value: any): T; + in(values: any[]): T; + ne(value: any): T; +} + +export type QueryWhereChain = BaseChain; +export type QueryFilterChain = ExtendedChain; + +// Dynogels Query +export interface Query { + limit(number: number): Query; + filterExpression(expression: any): Query; + expressionAttributeNames(data: any): Query; + expressionAttributeValues(data: any): Query; + projectionExpression(data: any): Query; + usingIndex(name: string): Query; + consistentRead(read: boolean): Query; + addKeyCondition(condition: any): Query; + addFilterCondition(condition: any): Query; + startKey(hashKey: any, rangeKey: any): Query; + attributes(attrs: any): Query; + ascending(): Query; + descending(): Query; + select(value: any): Query; + returnConsumedCapacity(value: any): Query; + loadAll(): Query; + where(keyName: string): QueryWhereChain; + filter(keyName: string): QueryFilterChain; + exec(): stream.Readable; + exec(callback: (err: Error, data: any) => void): void; +} + +export interface ScanWhereChain extends ExtendedChain { + notNull(): Scan; +} + +// Dynogels Scan +export interface Scan { + limit(number: number): Scan; + addFilterCondition(condition: any): Scan; + startKey(hashKey: any, rangeKey?: any): Scan; + attributes(attrs: any): Scan; + select(value: any): Scan; + returnConsumedCapacity(): Scan; + segments(segment: any, totalSegments: number): Scan; + where(keyName: string): ScanWhereChain; + filterExpression(expression: any): Scan; + expressionAttributeNames(data: any): Scan; + expressionAttributeValues(data: any): Scan; + projectionExpression(data: any): Scan; + exec(): stream.Readable; + exec(callback: (err: Error, data: any) => void): void; + loadAll(): Scan; +} + +export type tableResolve = () => string; + +export interface SchemaType { + [key: string]: joi.AnySchema | SchemaType; +} + +export interface ModelConfiguration { + hashKey: string; + rangeKey?: string; + timestamps?: boolean; + createdAt?: boolean; + updatedAt?: string; + schema?: SchemaType; + validation?: joi.ValidationOptions; + tableName?: string | tableResolve; + indexes?: any[]; + log?: Log; +} + +export interface Document { + [key: string]: any; +} + +export interface DocumentCollection { + Items: Document[]; + Count: number; + ScannedCount: number; +} diff --git a/types/dynogels/package.json b/types/dynogels/package.json new file mode 100644 index 0000000000..28676516a3 --- /dev/null +++ b/types/dynogels/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "aws-sdk": "^2.58.0" + } +} \ No newline at end of file diff --git a/types/error-stack-parser/tsconfig.json b/types/dynogels/tsconfig.json similarity index 85% rename from types/error-stack-parser/tsconfig.json rename to types/dynogels/tsconfig.json index 98f3beb1a5..40297f0a43 100644 --- a/types/error-stack-parser/tsconfig.json +++ b/types/dynogels/tsconfig.json @@ -6,18 +6,18 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, + "strictFunctionTypes": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", - "error-stack-parser-tests.ts" + "dynogels-tests.ts" ] } \ No newline at end of file diff --git a/types/dynogels/tslint.json b/types/dynogels/tslint.json new file mode 100644 index 0000000000..c7d87e32cc --- /dev/null +++ b/types/dynogels/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "unified-signatures": false + } +} \ No newline at end of file diff --git a/types/ej.web.all/ej.web.all-tests.ts b/types/ej.web.all/ej.web.all-tests.ts index d1d67be14c..9a1b418da0 100644 --- a/types/ej.web.all/ej.web.all-tests.ts +++ b/types/ej.web.all/ej.web.all-tests.ts @@ -1,4 +1,6 @@ /* tslint:disable */ +/* tslint:disable */ + module AccordionComponent { $(function () { @@ -76,6 +78,35 @@ module Bulletgraphcomponent { $(function () { var bulletsample = new ej.datavisualization.BulletGraph($("#BulletGraph"), { isResponsive: true, + load: function () { + var sender = $("#BulletGraph").data("ejBulletGraph"); + var bulletTheme = window.themeStyle + window.themeColor + window.themeVarient; + if (bulletTheme) { + switch (bulletTheme) { + case "flatdark": + case "flatazuredark": + case "flatlimedark": + case "flatsaffrondark": + case "gradientdark": + case "gradientazuredark": + case "gradientlimedark": + case "gradientsaffrondark": + case "flathigh-contrast-01dark": + case "flathigh-contrast-02dark": + theme = "flatdark"; + break; + case "flatoffice-365light": + case "flatmateriallight": + theme = "material"; + break; + default: + theme = "flatlight"; + break; + } + sender.model.theme = theme; + } + + }, tooltipSettings: { visible: true }, quantitativeScaleSettings: { featureMeasures: [{ @@ -232,10 +263,50 @@ module ChartComponent { model.primaryYAxis.labelIntersectAction = "rotate45"; model.primaryYAxis.edgeLabelPlacement = "hide"; } + var theme = window.themeStyle + window.themeColor + window.themeVarient; + if (theme) { + switch (theme) { + case "flatdark": + case "flatazuredark": + case "flatlimedark": + case "flatsaffrondark": + theme = "flatdark"; + break; + case "gradientlight": + case "gradientazurelight": + case "gradientlimelight": + case "gradientsaffronlight": + theme = "gradientlight"; + break; + case "gradientdark": + case "gradientazuredark": + case "gradientlimedark": + case "gradientsaffrondark": + theme = "gradientdark"; + break; + case "flatbootstraplight": + theme = "bootstrap"; + break; + case "flathigh-contrast-01dark": + case "flathigh-contrast-02dark": + theme = "high-contrast-01"; + break; + case "flatmateriallight": + case "flatoffice-365light": + theme = "material"; + break; + + default: + theme = "flatlight"; + break; + } + sender.model.theme = theme; + } }, title: { text: 'Efficiency of oil-fired power production' }, size: { height: "600" }, - legend: { visible: true} + legend: { visible: true}, + load:"loadTheme" }); }); } @@ -307,6 +378,28 @@ module ColorPickerComponent { } + + +module ComboBoxComponent{ + var BikeList = [ + { empid: "bk1", text: "Apache RTR" }, { empid: "bk2", text: "CBR 150-R" }, { empid: "bk3", text: "CBZ Xtreme" }, + { empid: "bk4", text: "Discover" }, { empid: "bk5", text: "Dazzler" }, { empid: "bk6", text: "Flame" }, + { empid: "bk7", text: "Fazzer" }, { empid: "bk8", text: "FZ-S" }, { empid: "bk9", text: "Pulsar" }, + { empid: "bk10", text: "Shine" }, { empid: "bk11", text: "R15" }, { empid: "bk12", text: "Unicorn" } + ]; + $(function () { + var comboboxInstance =new ej.ComboBox($("#selectCar"), { + width: "100%", + placeholder: "Select a Bike", + fields: { text: "text", value: "empid" }, + dataSource: BikeList, + autofill: true + }); + }); +} + + + module DatePickerComponent { @@ -1065,7 +1158,8 @@ module PivotChartOlap { size: { height: "460px", width: "100%" }, primaryXAxis: { title: { text: "Date - Fiscal" }, labelRotation: 0 }, primaryYAxis: { title: { text: "Internet Sales Amount" } }, - legend: { visible: true, rowCount: 2 } + legend: { visible: true, rowCount: 2 }, + load:"loadTheme" }); }); } @@ -1139,7 +1233,8 @@ module PivotChartRelational { }, size: { height: "460px", width: "100%" }, primaryYAxis: { title: { text: "Amount" } }, - legend: { visible: true } + legend: { visible: true }, + load:"loadTheme" }); }); } @@ -1650,7 +1745,67 @@ module rangecomponent { fill: '#69D2E7' } ]; - } + }, + loaded: function () { + var sender = $("#RangeNavigator").data("ejRangeNavigator"); + var theme = window.themeStyle + window.themeColor + window.themeVarient; + if (theme) { + switch (theme) { + case "flatazurelight": + theme = "azurelight"; + break; + case "flatlimelight": + theme = "limelight"; + break; + case "flatsaffronlight": + theme = "saffronlight"; + break; + case "gradientazurelight": + theme = "gradientazure"; + break; + case "gradientlimelight": + theme = "gradientlime"; + break; + case "gradientsaffronlight": + theme = "gradientsaffron"; + break; + case "flatazuredark": + theme = "azuredark"; + break; + case "flatlimedark": + theme = "limedark"; + break; + case "flatsaffrondark": + theme = "saffrondark"; + break; + case "gradientazuredark": + theme = "gradientazuredark"; + break; + case "gradientlimedark": + theme = "gradientlimedark"; + break; + case "gradientsaffrondark": + theme = "gradientsaffrondark"; + break; + case "flathigh-contrast-01dark": + theme = "highcontrast01"; + break; + case "flathigh-contrast-02dark": + theme = "highcontrast02"; + break; + case "flatmateriallight": + theme = "material"; + break; + case "flatoffice-365light": + theme = "office"; + break; + default: + theme = "flatlight"; + break; + } + sender.model.theme = theme; + } + } }); }); @@ -2621,7 +2776,9 @@ module ScrollerComponent { }); $(window).bind('resize', function () { scrollerSample.refresh(); - }); }); + }); + + }); } @@ -2893,9 +3050,20 @@ module sunburstcomponent { enableAnimation:false, size:{height:"600"}, innerRadius:0.2, + load: function () { + var sender = $("#Sunburst").data("ejSunburstChart"); + var SunBurstTheme = window.themeStyle + window.themeColor + window.themeVarient; + SunBurstTheme = SunBurstTheme.toString(); + if (SunBurstTheme.indexOf("dark") > -1 || SunBurstTheme.indexOf("contrast") > -1) + SunBurstTheme = "flatdark"; + else + SunBurstTheme = "flatlight"; + sender.model.theme = SunBurstTheme; + }, title:{text:"Employees Count"}, zoomSettings:{enable:false}, - legend:{visible:true,position:'top'} + legend:{visible:true,position:'top'}, + load:"loadTheme" }); }); } diff --git a/types/ej.web.all/index.d.ts b/types/ej.web.all/index.d.ts index e9f83b680c..ae1948ba86 100644 --- a/types/ej.web.all/index.d.ts +++ b/types/ej.web.all/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ej.web.all 15.3 +// Type definitions for ej.web.all 15.4 // Project: http://help.syncfusion.com/js/typescript // Definitions by: Syncfusion // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,9 +6,10 @@ /// + /*! * filename: ej.web.all.d.ts -* version : 15.3.0.33 +* version : 15.4.0.17 * Copyright Syncfusion Inc. 2001 - 2017. All rights reserved. * Use of this code is subject to the terms of our license. * A copy of the current license can be obtained at any time by e-mailing @@ -54,7 +55,7 @@ declare namespace ej { function getNameSpace(className: string): string; function getOffset(ele: string): any; function getRenderMode(): string; - function getScrollableParents(element: any): void; + function getScrollableParents(element: any): JQuery; function getTheme(): string; function getZindexPartial(element: any, popupEle: string): number; function hasRenderMode(element: string): void; @@ -5131,6 +5132,10 @@ declare namespace ej { */ beforeUpload?(e: BeforeUploadEventArgs): void; + /** Fires before opening the upload dialog. + */ + beforeUploadDialogOpen?(e: BeforeUploadDialogOpenEventArgs): void; + /** Fires when FileExplorer control was created */ create?(e: CreateEventArgs): void; @@ -5355,6 +5360,21 @@ declare namespace ej { type?: string; } + export interface BeforeUploadDialogOpenEventArgs { + + /** returns Selected FileList objects + */ + files?: any; + + /** returns the FileExplorer model + */ + model?: any; + + /** returns the name of the event. + */ + type?: string; + } + export interface CreateEventArgs { /** Set to true when the event has to be canceled, else false. @@ -16921,6 +16941,11 @@ declare namespace ej { */ readOnly?: boolean; + /** Shows/Hides the increment and decrement buttons of the slider. + * @Default {false} + */ + showButtons?: boolean; + /** Specifies the rounded corner behavior for slider. * @Default {false} */ @@ -32630,17 +32655,13 @@ declare namespace ej { export interface ActionBeginEventArgs { - /** Returns the current date value. - */ - currentDate?: any; - /** Returns the cancel option value. */ cancel?: boolean; - /** Returns the current view value. + /** Returns the data about the view change action. */ - currentView?: string; + data?: any; /** Returns the Schedule model. */ @@ -32650,21 +32671,17 @@ declare namespace ej { */ requestType?: string; - /** Returns the target of the click. - */ - target?: any; - /** Returns the name of the event. */ type?: string; - /** Returns the save appointment value. + /** Returns the name of the CRUD action performed. */ - data?: any; + currentAction?: string; - /** Returns the id of delete appointment. + /** Returns the GUid of appointment. */ - id?: number; + id?: string; } export interface ActionCompleteEventArgs { @@ -32689,6 +32706,10 @@ declare namespace ej { */ type?: string; + /** Returns the name of the CRUD action performed. + */ + currentAction?: string; + /** Returns the appointment data dropped. */ appointment?: any; @@ -32719,13 +32740,17 @@ declare namespace ej { export interface BeforeAppointmentRemoveEventArgs { + /** Returns the deleted appointment object. + */ + appointment?: any; + /** Returns the cancel option value. */ cancel?: boolean; - /** Returns the deleted appointment object. + /** Returns the name of the CRUD action performed. */ - appointment?: any; + currentAction?: string; /** Returns the Schedule model. */ @@ -32746,10 +32771,18 @@ declare namespace ej { */ cancel?: boolean; + /** Returns the name of the CRUD action performed. + */ + currentAction?: string; + /** Returns the Schedule model. */ model?: ej.Schedule.Model; + /** Returns the name of the Scheduler event. + */ + requestType?: string; + /** Returns the name of the Scheduler event. */ type?: string; @@ -32881,14 +32914,14 @@ declare namespace ej { export interface CellClickEventArgs { - /** Returns the object of cellClick event. - */ - object?: any; - /** Returns the cancel option value. */ cancel?: boolean; + /** Returns the index of the cell. + */ + cellIndex?: number; + /** Returns the end time of the clicked cell. */ endTime?: any; @@ -32897,6 +32930,14 @@ declare namespace ej { */ model?: ej.Schedule.Model; + /** Returns day, date and time information. + */ + quickString?: string; + + /** Returns the object of the resource. + */ + resources?: any; + /** Returns the start time of the clicked cell. */ startTime?: any; @@ -32912,10 +32953,6 @@ declare namespace ej { export interface CellDoubleClickEventArgs { - /** Returns the object of cellDoubleClick event. - */ - object?: any; - /** Returns the cancel option value. */ cancel?: boolean; @@ -32928,6 +32965,10 @@ declare namespace ej { */ model?: ej.Schedule.Model; + /** Returns the object of the resource. + */ + resources?: any; + /** Returns the start time of the double clicked cell. */ startTime?: any; @@ -32943,26 +32984,30 @@ declare namespace ej { export interface CellHoverEventArgs { - /** Returns the object of cellHover event. - */ - object?: any; - /** Returns the cancel option value. */ cancel?: boolean; /** Returns the index of the hovered cell. */ - cellIndex?: any; + cellIndex?: number; - /** Returns the current date of the hovered cell. + /** Returns the end time of the clicked cell. */ - currentDate?: any; + endTime?: any; /** Returns the Schedule model. */ model?: ej.Schedule.Model; + /** Returns the object of the resource. + */ + resources?: any; + + /** Returns the start time of the clicked cell. + */ + startTime?: any; + /** Returns the target of the clicked cell. */ target?: any; @@ -33004,10 +33049,6 @@ declare namespace ej { export interface DragEventArgs { - /** Returns the object of dragOver event. - */ - object?: any; - /** Returns the cancel option value. */ cancel?: boolean; @@ -33023,13 +33064,17 @@ declare namespace ej { /** Returns the name of the event. */ type?: string; + + /** Returns the default dragging interval range in minutes + */ + interval?: number; } export interface DragStartEventArgs { - /** Returns the object of dragStart event. + /** Returns the dragged appointment. */ - object?: any; + appointment?: any; /** Returns the cancel option value. */ @@ -33050,10 +33095,6 @@ declare namespace ej { export interface DragStopEventArgs { - /** Returns the object of dragDrop event. - */ - object?: any; - /** Returns the dropped appointment object. */ appointment?: any; @@ -33073,10 +33114,6 @@ declare namespace ej { export interface MenuItemClickEventArgs { - /** Returns the object of menuItemClick event. - */ - object?: any; - /** Returns the cancel option value. */ cancel?: boolean; @@ -33089,6 +33126,10 @@ declare namespace ej { */ model?: ej.Schedule.Model; + /** Returns the right clicked cell details. + */ + targetInfo?: any; + /** Returns the name of the event. */ type?: string; @@ -33120,6 +33161,10 @@ declare namespace ej { */ target?: any; + /** Returns the name of the Scheduler event. + */ + requestType?: string; + /** Returns the name of the event. */ type?: string; @@ -33193,10 +33238,6 @@ declare namespace ej { export interface ResizeEventArgs { - /** Returns the object of resizing event. - */ - object?: any; - /** Returns the cancel option value. */ cancel?: boolean; @@ -33205,6 +33246,10 @@ declare namespace ej { */ element?: any; + /** Returns the default appointment resizing range . + */ + interval?: number; + /** Returns the Schedule model. */ model?: ej.Schedule.Model; @@ -33216,9 +33261,9 @@ declare namespace ej { export interface ResizeStartEventArgs { - /** Returns the object of resizeStart event. + /** Returns the object of the resized appointment. */ - object?: any; + appointment?: any; /** Returns the cancel option value. */ @@ -33239,10 +33284,6 @@ declare namespace ej { export interface ResizeStopEventArgs { - /** Returns the object of resizeStop event. - */ - object?: any; - /** Returns the resized appointment value. */ appointment?: any; @@ -33266,14 +33307,14 @@ declare namespace ej { export interface OverflowButtonClickEventArgs { - /** Returns the object consisting of start time, end time and resource value of the underlying cell on which the clicked overflow button is present. - */ - object?: any; - /** Returns the cancel option value. */ cancel?: boolean; + /** Returns the icon rendered cell information. + */ + Datas?: any; + /** Returns the object of menu item event. */ events?: any; @@ -33289,17 +33330,17 @@ declare namespace ej { export interface OverflowButtonHoverEventArgs { - /** Returns the object consisting of start time, end time and resource value of the underlying cell on which the overflow button is currently hovered. - */ - object?: any; - /** Returns the cancel option value. */ cancel?: boolean; + /** Returns the icon rendered cell information. + */ + datas?: any; + /** Returns the object of menu item event. */ - events?: any; + event?: any; /** Returns the Schedule model. */ @@ -33343,6 +33384,10 @@ declare namespace ej { */ model?: ej.Schedule.Model; + /** Returns the name of the Scheduler event. + */ + requestType?: string; + /** Returns the name of the Scheduler event. */ type?: string; @@ -33358,10 +33403,18 @@ declare namespace ej { */ cancel?: boolean; + /** Returns the name of the CRUD action performed. + */ + currentAction?: string; + /** Returns the Schedule model. */ model?: ej.Schedule.Model; + /** Returns the name of the Scheduler event. + */ + requestType?: string; + /** Returns the name of the Scheduler event. */ type?: string; @@ -33377,10 +33430,18 @@ declare namespace ej { */ appointment?: any; + /** Returns the name of the CRDU action performed. + */ + currentAction?: string; + /** Returns the Schedule model. */ model?: ej.Schedule.Model; + /** Returns the name of the Scheduler event. + */ + requestType?: string; + /** Returns the name of the Scheduler event. */ type?: string; @@ -34190,6 +34251,11 @@ declare namespace ej { */ enablePredecessorValidation?: boolean; + /** Enables or disables serial number column for Gantt. When enabled, the records will be number sequenced. + * @Default {false} + */ + enableSerialNumber?: boolean; + /** Specifies the baseline background color in Gantt * @Default {#fba41c} */ @@ -34271,6 +34337,10 @@ declare namespace ej { */ editDialogFields?: EditDialogField[]; + /** Options for filtering and customizing filter actions. + */ + filterSettings?: FilterSettings; + /** Enables or disables the responsiveness of Gantt * @Default {false} */ @@ -34655,6 +34725,32 @@ declare namespace ej { */ workWeek?: any[]; + /** Specifies the view type for a project in the Gantt. + * @Default {ej.Gantt.ViewType.ProjectView} + */ + viewType?: ej.Gantt.ViewType|string; + + /** Specifies the data collection for grouping the resources in resource allocation view in Gantt. + * @Default {[]} + */ + groupCollection?: any[]; + + /** Default Value + */ + resourceCollectionMapping?: string; + + /** Default Value + */ + taskCollectionMapping?: string; + + /** Default Value + */ + groupIdMapping?: string; + + /** Default Value + */ + groupNameMapping?: string; + /** Triggered for every Gantt action before its starts. */ actionBegin?(e: ActionBeginEventArgs): void; @@ -35479,6 +35575,33 @@ declare namespace ej { editType?: string; } + export interface FilterSettingsFilteredColumn { + + /** Specifies the value to be filtered in Gantt. + */ + value?: string; + + /** Specifies the field where filtering has to be performed. + */ + field?: string; + + /** Specifies the predicate(and/or) value to perform filtering. + */ + predicate?: string; + + /** Specifies the filter condition to filtered column. See operator + */ + operator?: string; + } + + export interface FilterSettings { + + /** Specifies the column collection for filtering the Gantt content on initial load + * @Default {[]} + */ + filteredColumns?: FilterSettingsFilteredColumn[]; + } + export interface SplitterSettings { /** Specifies position of the splitter in Gantt , splitter can be placed either based on percentage values or pixel values. @@ -35867,6 +35990,16 @@ declare namespace ej { TimeScale24Hours } + + enum ViewType { + + ///Displays the project in task view in Gantt. + ProjectView, + + ///Displays the project in resource allocation view in Gantt. + ResourceView + } + } class ReportViewer extends ej.Widget { @@ -36620,6 +36753,141 @@ declare namespace ej { * @returns {void} */ reorderColumn(fieldName: string, targetIndex: string): void; + + /** To get the updated data source of TreeGrid. + * @returns {any[]} + */ + getUpdatedRecords(): any[]; + + /** Sends request to navigate to a specific page in TreeGrid. + * @param {number} Pass the page index to perform paging at specified page index. + * @returns {void} + */ + gotoPage(PageIndex: number): void; + + /** To change the checkbox selection to any column. + * @param {string} Pass the column field name to check box selection to that column. + * @returns {void} + */ + updateCheckboxColumn(fieldName: string): void; + + /** Gets the selected cell(s) element details in TreeGrid. + * @returns {any[]} + */ + getSelectedCells(): any[]; + + /** Sets the minimum responsive width for TreeGrid. + * @param {string} Pass the minimum responsive width, above which the TreeGrid needs to work in responsive mode. + * @returns {void} + */ + updateResponsiveMinWidth(width: string): void; + + /** To open the dialog to add new record/row in TreeGrid. + * @returns {void} + */ + showAddDialog(): void; + + /** To open the dialog to edit a row/record in TreeGrid. + * @param {number} Pass the index of row to be edit. + * @returns {void} + */ + showEditDialog(Index: number): void; + + /** Sets the scroll left and scroll top offsets of TreeGrid. + * @param {string} Pass a value to set left position of horizontal scroll bar. + * @param {string} Pass a value to set top position of vertical scroll bar. + * @returns {void} + */ + scrollOffset(Left: string, Top: string): void; + + /** Gets the scroll top offset of TreeGrid. + * @returns {number} + */ + getScrollTopOffset(): number; + + /** Gets the scroll left offset of TreeGrid. + * @returns {number} + */ + getScrollLeftOffset(): number; + + /** Sets the scroll top offset of TreeGrid to 0. + * @returns {void} + */ + scrollToTop(): void; + + /** Sets the scroll top offset of TreeGrid to maximum value. + * @returns {void} + */ + scrollToBottom(): void; + + /** To expand and collapse an item in TreeGrid using item’s index. + * @param {number} Pass the row index of row to expand/collapse. + * @returns {void} + */ + expandCollapseRow(Index: number): void; + + /** To expand all the root level nodes in TreeGrid. + * @returns {void} + */ + expandAll(): void; + + /** Show/Hide the detail row of a specific record. + * @param {number} Pass the row index of record to show/hide the detail row. + * @returns {void} + */ + showHideDetailsRow(rowIndex: number): void; + + /** Sends filtering request to filter a column in TreeGrid. + * @param {string} Pass the field name of the column. + * @param {string} string/integer/dateTime operator. + * @param {string} Pass the value to be filtered in a column. + * @param {string} Pass the predicate as and/or. + * @param {boolean} Optional pass the match case value as true/false. + * @param {any} Optional actualFilterValue denote the filter object of current filtered columns. + * @returns {void} + */ + filterColumn(fieldName: string, filterOperator: string, filterValue: string, predicate: string, matchcase: boolean, actualFilterValue: any): void; + + /** To change the index of the tree column in TreeGrid. + * @param {number} Pass the column index to make the column as treeColumnIndex. + * @returns {void} + */ + columnIndex(Index: number): void; + + /** To clear the sorting from sorted columns in TreeGrid. + * @returns {void} + */ + clearSorting(): void; + + /** Gets the column index of specific column with data source field. + * @param {string} Pass the column field name to get its index. + * @returns {number} + */ + getColumnIndexByField(fieldName: string): number; + + /** Gets the column field name using column header text. + * @param {string} Pass the column header text to get its field name. + * @returns {string} + */ + getFieldNameByHeaderText(headerText: string): string; + + /** Gets the column object of specific column. + * @param {string} Pass the column header text to get details of that column. + * @returns {any} + */ + getColumnByHeaderText(headerText: string): any; + + /** Clears the filter applied to a specific column. + * @param {string} Pass the column field name to clear filtering done in that column. + * @returns {void} + */ + clearFilter(fieldName: string): void; + + /** Gets the column object of specific column. + * @param {string} Pass the column field name to get details of that column. + * @returns {any} + */ + getColumnByField(fieldName: string): any; } export namespace TreeGrid { @@ -36851,6 +37119,16 @@ declare namespace ej { */ detailsRowHeight?: number; + /** Gets or sets a value that indicates stacked header should be shown on TreeGrid layout when the property “stackedHeaderRows” is set. + * @Default {false} + */ + showStackedHeader?: boolean; + + /** Gets or sets an object that indicates to managing the collection of stacked header rows for the treegrid. + * @Default {[]} + */ + stackedHeaderRows?: StackedHeaderRow[]; + /** Specifies the visibility of summary row * @Default {false} */ @@ -38263,6 +38541,42 @@ declare namespace ej { enableSelectAll?: boolean; } + export interface StackedHeaderRowsStackedHeaderColumn { + + /** Gets or sets a value that indicates the header text for the particular stacked header column. + * @Default {null} + */ + column?: any; + + /** Gets or sets a value that indicates class to the corresponding stackedHeaderColumn. + * @Default {null} + */ + cssClass?: string; + + /** Gets or sets a value that indicates the header text for the particular stacked header column. + * @Default {null} + */ + headerText?: string; + + /** Gets or sets a value that indicates the text alignment of the corresponding headerText. + * @Default {ej.TextAlign.Left} + */ + textAlign?: string; + + /** Sets the template for tooltip for the Grid stackedHeaderColumns. + * @Default {null} + */ + tooltip?: string; + } + + export interface StackedHeaderRow { + + /** Gets or sets a value that indicates whether to add stacked header columns into the stacked header rows + * @Default {[]} + */ + stackedHeaderColumns?: StackedHeaderRowsStackedHeaderColumn[]; + } + export interface SummaryRowsSummaryColumn { /** Specifies the summary type to perform calculations in a corresponding summary column. See summaryType. @@ -39019,63 +39333,79 @@ declare namespace ej { export interface AjaxCompleteEventArgs { - /** returns true if the event should be canceled; otherwise, false. + /** Set this option to true to cancel the event. */ cancel?: boolean; - /** returns the name of the event. + /** Instance of the navigation drawer model object. + */ + model?: ej.NavigationDrawer.Model; + + /** Name of the event. */ type?: string; - /** returns the model value of the control. + /** URL of the content. */ - model?: ej.NavigationDrawer.Model; + URL?: string; + + /** Response content. + */ + data?: string; } export interface AjaxErrorEventArgs { - /** returns true if the event should be canceled; otherwise, false. + /** Set this option to true to cancel the event. */ cancel?: boolean; - /** returns the name of the event. - */ - type?: string; - - /** returns the model value of the control. + /** Instance of the navigation drawer model object. */ model?: ej.NavigationDrawer.Model; - /** returns the error thrown in the AJAX post. + /** Name of the event. */ - errorThrown?: any; + type?: string; - /** returns the status. + /** URL of the content. */ - textStatus?: any; + URL?: string; + + /** Error page content. + */ + responseText?: string; + + /** Error code. + */ + status?: number; + + /** The corresponding error description. + */ + statusText?: string; } export interface AjaxSuccessEventArgs { - /** returns true if the event should be canceled; otherwise, false. + /** Set this option to true to cancel the event. */ cancel?: boolean; - /** returns the name of the event. - */ - type?: string; - - /** returns the model value of the control. + /** Instance of the navigation drawer model object. */ model?: ej.NavigationDrawer.Model; - /** returns the AJAX current content. + /** Name of the event. */ - content?: string; + type?: string; - /** returns the current URL of the AJAX post. + /** URL of the content. */ URL?: string; + + /** Response content. + */ + data?: string; } export interface BeforeCloseEventArgs { @@ -45056,6 +45386,12 @@ declare namespace ej { */ enableAsync?: boolean; + /** Sets the data type for the ajax call used within the SpellCheck control, denoting the type of data that are expected to be retrieved from the server. The applicable values are + * json and jsonp. + * @Default {jsonp} + */ + ajaxDataType?: string; + /** Triggers on the success of AJAX call request. */ actionSuccess?(e: ActionSuccessEventArgs): void; @@ -45789,209 +46125,283 @@ declare namespace ej.datavisualization { destroy(): void; /** To export Image + * @param {number} for the Image + * @param {number} for the Image * @returns {void} */ - exportImage(): void; + exportImage(fileName: number, fileType: number): void; /** To get Bar Distance From Scale in number + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getBarDistanceFromScale(): any; + getBarDistanceFromScale(scaleIndex: number, pointerIndex: number): any; /** To get Bar Pointer Value in number + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getBarPointerValue(): any; + getBarPointerValue(scaleIndex: number, pointerIndex: number): any; /** To get Bar Width in number + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getBarWidth(): any; + getBarWidth(scaleIndex: number, pointerIndex: number): any; /** To get CustomLabel Angle in number + * @param {number} scaleIndex value for the Gauge + * @param {number} customLabelIndex value for the Gauge * @returns {any} */ - getCustomLabelAngle(): any; + getCustomLabelAngle(scaleIndex: number, customLabelIndex: number): any; /** To get CustomLabel Value in string + * @param {number} scaleIndex value for the Gauge + * @param {number} customLabelIndex value for the Gauge * @returns {any} */ - getCustomLabelValue(): any; + getCustomLabelValue(scaleIndex: number, customLabelIndex: number): any; /** To get Label Angle in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getLabelAngle(): any; + getLabelAngle(scaleIndex: number, labelIndex: number): any; /** To get LabelPlacement in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getLabelPlacement(): any; + getLabelPlacement(scaleIndex: number, labelIndex: number): any; /** To get LabelStyle in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getLabelStyle(): any; + getLabelStyle(scaleIndex: number, labelIndex: number): any; /** To get Label XDistance From Scale in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getLabelXDistanceFromScale(): any; + getLabelXDistanceFromScale(scaleIndex: number, labelIndex: number): any; /** To get PointerValue in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getLabelYDistanceFromScale(): any; + getLabelYDistanceFromScale(scaleIndex: number, labelIndex: number): any; /** To get Major Interval Value in number + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getMajorIntervalValue(): any; + getMajorIntervalValue(scaleIndex: number): any; /** To get MarkerStyle in number + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getMarkerStyle(): any; + getMarkerStyle(scaleIndex: number, pointerIndex: number): any; /** To get Maximum Value in number + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getMaximumValue(): any; + getMaximumValue(scaleIndex: number): any; /** To get PointerValue in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getMinimumValue(): any; + getMinimumValue(scaleIndex: number, pointerIndex: number): any; /** To get Minor Interval Value in number + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getMinorIntervalValue(): any; + getMinorIntervalValue(scaleIndex: number): any; /** To get Pointer Distance From Scale in number + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerDistanceFromScale(): any; + getPointerDistanceFromScale(scaleIndex: number, pointerIndex: number): any; /** To get PointerHeight in number + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerHeight(): any; + getPointerHeight(scaleIndex: number, pointerIndex: number): any; /** To get Pointer Placement in String + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerPlacement(): any; + getPointerPlacement(scaleIndex: number, pointerIndex: number): any; /** To get PointerValue in number + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerValue(): any; + getPointerValue(scaleIndex: number, pointerIndex: number): any; /** To get PointerWidth in number + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerWidth(): any; + getPointerWidth(scaleIndex: number, pointerIndex: number): any; /** To get Range Border Width in number + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeBorderWidth(): any; + getRangeBorderWidth(scaleIndex: number, rangeIndex: number): any; /** To get Range Distance From Scale in number + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeDistanceFromScale(): any; + getRangeDistanceFromScale(scaleIndex: number, rangeIndex: number): any; /** To get Range End Value in number + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeEndValue(): any; + getRangeEndValue(scaleIndex: number, rangeIndex: number): any; /** To get Range End Width in number + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeEndWidth(): any; + getRangeEndWidth(scaleIndex: number, rangeIndex: number): any; /** To get Range Position in number + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangePosition(): any; + getRangePosition(scaleIndex: number, rangeIndex: number): any; /** To get Range Start Value in number + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeStartValue(): any; + getRangeStartValue(scaleIndex: number, rangeIndex: number): any; /** To get Range Start Width in number + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeStartWidth(): any; + getRangeStartWidth(scaleIndex: number, rangeIndex: number): any; /** To get ScaleBarLength in number + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleBarLength(): any; + getScaleBarLength(scaleIndex: number): any; /** To get Scale Bar Size in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getScaleBarSize(): any; + getScaleBarSize(scaleIndex: number, pointerIndex: number): any; /** To get Scale Border Width in number + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleBorderWidth(): any; + getScaleBorderWidth(scaleIndex: number): any; /** To get Scale Direction in number + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleDirection(): any; + getScaleDirection(scaleIndex: number): any; /** To get Scale Location in object + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleLocation(): any; + getScaleLocation(scaleIndex: number): any; /** To get Scale Style in string + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleStyle(): any; + getScaleStyle(scaleIndex: number): any; /** To get Tick Angle in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getTickAngle(): any; + getTickAngle(scaleIndex: number, tickIndex: number): any; /** To get Tick Height in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getTickHeight(): any; + getTickHeight(scaleIndex: number, tickIndex: number): any; /** To get getTickPlacement in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getTickPlacement(): any; + getTickPlacement(scaleIndex: number, tickIndex: number): any; /** To get Tick Style in string + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getTickStyle(): any; + getTickStyle(scaleIndex: number, tickIndex: number): any; /** To get Tick Width in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getTickWidth(): any; + getTickWidth(scaleIndex: number, tickIndex: number): any; /** To get get Tick XDistance From Scale in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getTickXDistanceFromScale(): any; + getTickXDistanceFromScale(scaleIndex: number, tickIndex: number): any; /** To get Tick YDistance From Scale in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getTickYDistanceFromScale(): any; + getTickYDistanceFromScale(scaleIndex: number, tickIndex: number): any; /** Specifies the scales. * @returns {void} @@ -45999,204 +46409,314 @@ declare namespace ej.datavisualization { scales(): void; /** To set setBarDistanceFromScale + * @param {number} scaleIndex,value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {number} Bar DistanceFromScale value for Gauge * @returns {void} */ - setBarDistanceFromScale(): void; + setBarDistanceFromScale(scaleIndex: number, pointerIndex: number, value: number): void; /** To set setBarPointerValue + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {number} Bar Pointer Value for Gauge * @returns {void} */ - setBarPointerValue(): void; + setBarPointerValue(scaleIndex: number, pointerIndex: number, value: number): void; /** To set setBarWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {number} Bar Width for Gauge * @returns {void} */ - setBarWidth(): void; + setBarWidth(scaleIndex: number, pointerIndex: number, value: number): void; /** To set setCustomLabelAngle + * @param {number} scaleIndex value for the Gauge + * @param {number} customLabelIndex value for the Gauge + * @param {number} Custom Label Angle for Gauge * @returns {void} */ - setCustomLabelAngle(): void; + setCustomLabelAngle(scaleIndex: number, customLabelIndex: number, value: number): void; /** To set setCustomLabelValue + * @param {number} scaleIndex value for the Gauge + * @param {number} customLabelIndex value for the Gauge + * @param {number} CustomLabel value for Gauge * @returns {void} */ - setCustomLabelValue(): void; + setCustomLabelValue(scaleIndex: number, customLabelIndex: number, value: number): void; /** To set setLabelAngle + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Label Angle for Gauge * @returns {void} */ - setLabelAngle(): void; + setLabelAngle(scaleIndex: number, labelIndex: number, angle: number): void; /** To set setLabelPlacement + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Label Placement for Gauge * @returns {void} */ - setLabelPlacement(): void; + setLabelPlacement(scaleIndex: number, labelIndex: number, value: number): void; /** To set setLabelStyle + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {string} Label Style for Gauge * @returns {void} */ - setLabelStyle(): void; + setLabelStyle(scaleIndex: number, labelIndex: number, value: string): void; /** To set setLabelXDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Label XDistance From Scale for Gauge * @returns {void} */ - setLabelXDistanceFromScale(): void; + setLabelXDistanceFromScale(scaleIndex: number, labelIndex: number, value: number): void; /** To set setLabelYDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Label YDistance From Scale for Gauge * @returns {void} */ - setLabelYDistanceFromScale(): void; + setLabelYDistanceFromScale(scaleIndex: number, labelIndex: number, value: number): void; /** To set setMajorIntervalValue + * @param {number} scaleIndex value for the Gauge + * @param {number} Major Interval Value for Gauge * @returns {void} */ - setMajorIntervalValue(): void; + setMajorIntervalValue(scaleIndex: number, value: number): void; /** To set setMarkerStyle + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {string} marker Style for Gauge * @returns {void} */ - setMarkerStyle(): void; + setMarkerStyle(scaleIndex: number, pointerIndex: number, value: string): void; /** To set setMaximumValue + * @param {number} scaleIndex value for the Gauge + * @param {number} MaximumValue for Gauge * @returns {void} */ - setMaximumValue(): void; + setMaximumValue(scaleIndex: number, value: number): void; /** To set setMinimumValue + * @param {number} scaleIndex value for the Gauge + * @param {number} MinimumValue for Gauge * @returns {void} */ - setMinimumValue(): void; + setMinimumValue(scaleIndex: number, value: number): void; /** To set setMinorIntervalValue + * @param {number} scaleIndex value for the Gauge + * @param {number} Minor Interval Value for Gauge * @returns {void} */ - setMinorIntervalValue(): void; + setMinorIntervalValue(scaleIndex: number, value: number): void; /** To set setPointerDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {number} for Gauge * @returns {void} */ - setPointerDistanceFromScale(): void; + setPointerDistanceFromScale(scaleIndex: number, pointerIndex: number, value: number): void; /** To set PointerHeight + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {number} for Gauge * @returns {void} */ - setPointerHeight(): void; + setPointerHeight(scaleIndex: number, pointerIndex: number, height: number): void; /** To set setPointerPlacement + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {number} pointer placement for Gauge * @returns {void} */ - setPointerPlacement(): void; + setPointerPlacement(scaleIndex: number, pointerIndex: number, value: number): void; /** To set PointerValue + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {number} Pointer value for Gauge * @returns {void} */ - setPointerValue(): void; + setPointerValue(scaleIndex: number, pointerIndex: number, value: number): void; /** To set PointerWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {number} Pointer width for Gauge * @returns {void} */ - setPointerWidth(): void; + setPointerWidth(scaleIndex: number, pointerIndex: number, width: number): void; /** To set setRangeBorderWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge + * @param {number} Range Border Width for Gauge * @returns {void} */ - setRangeBorderWidth(): void; + setRangeBorderWidth(scaleIndex: number, rangeIndex: number, value: number): void; /** To set setRangeDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge + * @param {number} Range Distance FromScale for Gauge * @returns {void} */ - setRangeDistanceFromScale(): void; + setRangeDistanceFromScale(scaleIndex: number, rangeIndex: number, value: number): void; /** To set setRangeEndValue + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge + * @param {number} Range end value for Gauge * @returns {void} */ - setRangeEndValue(): void; + setRangeEndValue(scaleIndex: number, rangeIndex: number, value: number): void; /** To set setRangeEndWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge + * @param {number} Range End Width for Gauge * @returns {void} */ - setRangeEndWidth(): void; + setRangeEndWidth(scaleIndex: number, rangeIndex: number, value: number): void; /** To set setRangePosition + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge + * @param {number} Range Position for Gauge * @returns {void} */ - setRangePosition(): void; + setRangePosition(scaleIndex: number, rangeIndex: number, value: number): void; /** To set setRangeStartValue + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge + * @param {number} range start value for Gauge * @returns {void} */ - setRangeStartValue(): void; + setRangeStartValue(scaleIndex: number, rangeIndex: number, value: number): void; /** To set setRangeStartWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge + * @param {number} Range Start Width for Gauge * @returns {void} */ - setRangeStartWidth(): void; + setRangeStartWidth(scaleIndex: number, rangeIndex: number, value: number): void; /** To set setScaleBarLength + * @param {number} scaleIndex value for the Gauge + * @param {number} Scale Bar Length for Gauge * @returns {void} */ - setScaleBarLength(): void; + setScaleBarLength(scaleIndex: number, value: number): void; /** To set setScaleBarSize + * @param {number} scaleIndex value for the Gauge + * @param {number} ScaleBarSize for Gauge * @returns {void} */ - setScaleBarSize(): void; + setScaleBarSize(scaleIndex: number, value: number): void; /** To set setScaleBorderWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} Scale Border Width for Gauge * @returns {void} */ - setScaleBorderWidth(): void; + setScaleBorderWidth(scaleIndex: number, value: number): void; /** To set setScaleDirection + * @param {number} scaleIndex value for the Gauge + * @param {number} Scale Direction for Gauge * @returns {void} */ - setScaleDirection(): void; + setScaleDirection(scaleIndex: number, value: number): void; /** To set setScaleLocation + * @param {number} scaleIndex value for the Gauge + * @param {any} Scale position for Gauge * @returns {void} */ - setScaleLocation(): void; + setScaleLocation(scaleIndex: number, value: any): void; /** To set setScaleStyle + * @param {number} scaleIndex value for the Gauge + * @param {number} for Gauge * @returns {void} */ - setScaleStyle(): void; + setScaleStyle(scaleIndex: number, value: number): void; /** To set setTickAngle + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Tick Angle for Gauge * @returns {void} */ - setTickAngle(): void; + setTickAngle(scaleIndex: number, tickIndex: number, angle: number): void; /** To set setTickHeight + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Tick Height for Gauge * @returns {void} */ - setTickHeight(): void; + setTickHeight(scaleIndex: number, tickIndex: number, value: number): void; /** To set setTickPlacement + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Tick Placement for Gauge * @returns {void} */ - setTickPlacement(): void; + setTickPlacement(scaleIndex: number, tickIndex: number, value: number): void; /** To set setTickStyle + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {string} Tick Style for Gauge * @returns {void} */ - setTickStyle(): void; + setTickStyle(scaleIndex: number, tickIndex: number, value: string): void; /** To set setTickWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Tick Width for Gauge * @returns {void} */ - setTickWidth(): void; + setTickWidth(scaleIndex: number, tickIndex: number, value: number): void; /** To set setTickXDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Tick XDistance From Scale for Gauge * @returns {void} */ - setTickXDistanceFromScale(): void; + setTickXDistanceFromScale(scaleIndex: number, tickIndex: number, value: number): void; /** To set setTickYDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Tick YDistance From Scale for Gauge * @returns {void} */ - setTickYDistanceFromScale(): void; + setTickYDistanceFromScale(scaleIndex: number, tickIndex: number, value: number): void; } export namespace LinearGauge { @@ -47833,419 +48353,601 @@ declare namespace ej.datavisualization { destroy(): void; /** To export Image + * @param {string} fileName for the Image + * @param {string} fileType for the Image * @returns {boolean} */ - exportImage(): boolean; + exportImage(fileName: string, fileType: string): boolean; /** To get BackNeedleLength + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getBackNeedleLength(): any; + getBackNeedleLength(scaleIndex: number, pointerIndex: number): any; /** To get CustomLabelAngle + * @param {number} scaleIndex value for the Gauge + * @param {number} customLabelIndex value for the Gauge * @returns {any} */ - getCustomLabelAngle(): any; + getCustomLabelAngle(scaleIndex: number, customLabelIndex: number): any; /** To get CustomLabelValue + * @param {number} scaleIndex value for the Gauge + * @param {number} customLabelIndex value for the Gauge * @returns {any} */ - getCustomLabelValue(): any; + getCustomLabelValue(scaleIndex: number, customLabelIndex: number): any; /** To get LabelAngle + * @param {number} scaleIndex value for the Gauge + * @param {number} labelIndex value for the Gauge * @returns {any} */ - getLabelAngle(): any; + getLabelAngle(scaleIndex: number, labelIndex: number): any; /** To get LabelDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} labelIndex value for the Gauge * @returns {any} */ - getLabelDistanceFromScale(): any; + getLabelDistanceFromScale(scaleIndex: number, labelIndex: number): any; /** To get LabelPlacement + * @param {number} scaleIndex value for the Gauge + * @param {number} labelIndex value for the Gauge * @returns {any} */ - getLabelPlacement(): any; + getLabelPlacement(scaleIndex: number, labelIndex: number): any; /** To get LabelStyle + * @param {number} scaleIndex value for the Gauge + * @param {number} labelIndex value for the Gauge * @returns {any} */ - getLabelStyle(): any; + getLabelStyle(scaleIndex: number, labelIndex: number): any; /** To get MajorIntervalValue + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getMajorIntervalValue(): any; + getMajorIntervalValue(scaleIndex: number): any; /** To get MarkerDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getMarkerDistanceFromScale(): any; + getMarkerDistanceFromScale(scaleIndex: number, pointerIndex: number): any; /** To get MarkerStyle + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getMarkerStyle(): any; + getMarkerStyle(scaleIndex: number, pointerIndex: number): any; /** To get MaximumValue + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getMaximumValue(): any; + getMaximumValue(scaleIndex: number): any; /** To get MinimumValue + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getMinimumValue(): any; + getMinimumValue(scaleIndex: number): any; /** To get MinorIntervalValue + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getMinorIntervalValue(): any; + getMinorIntervalValue(scaleIndex: number): any; /** To get NeedleStyle + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getNeedleStyle(): any; + getNeedleStyle(scaleIndex: number, pointerIndex: number): any; /** To get PointerCapBorderWidth + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getPointerCapBorderWidth(): any; + getPointerCapBorderWidth(scaleIndex: number): any; /** To get PointerCapRadius + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getPointerCapRadius(): any; + getPointerCapRadius(scaleIndex: number): any; /** To get PointerLength + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerLength(): any; + getPointerLength(scaleIndex: number, pointerIndex: number): any; /** To get PointerNeedleType + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerNeedleType(): any; + getPointerNeedleType(scaleIndex: number, pointerIndex: number): any; /** To get PointerPlacement + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerPlacement(): any; + getPointerPlacement(scaleIndex: number, pointerIndex: number): any; /** To get PointerValue + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerValue(): any; + getPointerValue(scaleIndex: number, pointerIndex: number): any; /** To get PointerWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerWidth(): any; + getPointerWidth(scaleIndex: number, pointerIndex: number): any; /** To get RangeBorderWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeBorderWidth(): any; + getRangeBorderWidth(scaleIndex: number, rangeIndex: number): any; /** To get RangeDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeDistanceFromScale(): any; + getRangeDistanceFromScale(scaleIndex: number, rangeIndex: number): any; /** To get RangeEndValue + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeEndValue(): any; + getRangeEndValue(scaleIndex: number, rangeIndex: number): any; /** To get RangePosition + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangePosition(): any; + getRangePosition(scaleIndex: number, rangeIndex: number): any; /** To get RangeSize + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeSize(): any; + getRangeSize(scaleIndex: number, rangeIndex: number): any; /** To get RangeStartValue + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeStartValue(): any; + getRangeStartValue(scaleIndex: number, rangeIndex: number): any; /** To get ScaleBarSize + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleBarSize(): any; + getScaleBarSize(scaleIndex: number): any; /** To get ScaleBorderWidth + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleBorderWidth(): any; + getScaleBorderWidth(scaleIndex: number): any; /** To get ScaleDirection + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleDirection(): any; + getScaleDirection(scaleIndex: number): any; /** To get ScaleRadius + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleRadius(): any; + getScaleRadius(scaleIndex: number): any; /** To get StartAngle + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getStartAngle(): any; + getStartAngle(scaleIndex: number): any; /** To get SubGaugeLocation + * @param {number} scaleIndex value for the Gauge + * @param {number} GaugeIndex value for the Gauge * @returns {any} */ - getSubGaugeLocation(): any; + getSubGaugeLocation(scaleIndex: number, GaugeIndex: number): any; /** To get SweepAngle + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getSweepAngle(): any; + getSweepAngle(scaleIndex: number): any; /** To get TickAngle + * @param {number} scaleIndex value for the Gauge + * @param {number} tickIndex value for the Gauge * @returns {any} */ - getTickAngle(): any; + getTickAngle(scaleIndex: number, tickIndex: number): any; /** To get TickDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} tickIndex value for the Gauge * @returns {any} */ - getTickDistanceFromScale(): any; + getTickDistanceFromScale(scaleIndex: number, tickIndex: number): any; /** To get TickHeight + * @param {number} scaleIndex value for the Gauge + * @param {number} labelIndex value for the Gauge * @returns {any} */ - getTickHeight(): any; + getTickHeight(scaleIndex: number, labelIndex: number): any; /** To get TickPlacement + * @param {number} scaleIndex value for the Gauge + * @param {number} tickIndex value for the Gauge * @returns {any} */ - getTickPlacement(): any; + getTickPlacement(scaleIndex: number, tickIndex: number): any; /** To get TickStyle + * @param {number} scaleIndex value for the Gauge + * @param {number} tickIndex value for the Gauge * @returns {any} */ - getTickStyle(): any; + getTickStyle(scaleIndex: number, tickIndex: number): any; /** To get TickWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} tickIndex value for the Gauge * @returns {any} */ - getTickWidth(): any; + getTickWidth(scaleIndex: number, tickIndex: number): any; /** To set includeFirstValue + * @param {number} scaleIndex value for the gauge + * @param {number} labelIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - includeFirstValue(): void; + includeFirstValue(scaleIndex: number, labelIndex: number, value: number): void; /** Switching the redraw option for the gauge + * @param {string} redraw value for the gauge * @returns {void} */ - redraw(): void; + redraw(value: string): void; /** To set BackNeedleLength + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setBackNeedleLength(): void; + setBackNeedleLength(scaleIndex: number, pointerIndex: number, value: number): void; /** To set CustomLabelAngle + * @param {number} scaleIndex value for the gauge + * @param {number} customLabelIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setCustomLabelAngle(): void; + setCustomLabelAngle(scaleIndex: number, customLabelIndex: number, value: number): void; /** To set CustomLabelValue + * @param {number} scaleIndex value for the gauge + * @param {number} customLabelIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setCustomLabelValue(): void; + setCustomLabelValue(scaleIndex: number, customLabelIndex: number, value: number): void; /** To set LabelAngle + * @param {number} scaleIndex value for the gauge + * @param {number} labelIndex value for the gauge + * @param {number} angle value for the gauge * @returns {void} */ - setLabelAngle(): void; + setLabelAngle(scaleIndex: number, labelIndex: number, angle: number): void; /** To set LabelDistanceFromScale + * @param {number} scaleIndex value for the gauge + * @param {number} labelIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setLabelDistanceFromScale(): void; + setLabelDistanceFromScale(scaleIndex: number, labelIndex: number, value: number): void; /** To set LabelPlacement + * @param {number} scaleIndex value for the gauge + * @param {number} labelIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setLabelPlacement(): void; + setLabelPlacement(scaleIndex: number, labelIndex: number, value: number): void; /** To set LabelStyle + * @param {number} scaleIndex value for the gauge + * @param {number} labelIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setLabelStyle(): void; + setLabelStyle(scaleIndex: number, labelIndex: number, value: number): void; /** To set MajorIntervalValue + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setMajorIntervalValue(): void; + setMajorIntervalValue(scaleIndex: number, value: number): void; /** To set MarkerDistanceFromScale + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setMarkerDistanceFromScale(): void; + setMarkerDistanceFromScale(scaleIndex: number, pointerIndex: number, value: number): void; /** To set MarkerStyle + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setMarkerStyle(): void; + setMarkerStyle(scaleIndex: number, pointerIndex: number, value: number): void; /** To set MaximumValue + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setMaximumValue(): void; + setMaximumValue(scaleIndex: number, value: number): void; /** To set MinimumValue + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setMinimumValue(): void; + setMinimumValue(scaleIndex: number, value: number): void; /** To set MinorIntervalValue + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setMinorIntervalValue(): void; + setMinorIntervalValue(scaleIndex: number, value: number): void; /** To set NeedleStyle + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setNeedleStyle(): void; + setNeedleStyle(scaleIndex: number, pointerIndex: number, value: number): void; /** To set PointerCapBorderWidth + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setPointerCapBorderWidth(): void; + setPointerCapBorderWidth(scaleIndex: number, value: number): void; /** To set PointerCapRadius + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setPointerCapRadius(): void; + setPointerCapRadius(scaleIndex: number, value: number): void; /** To set PointerLength + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setPointerLength(): void; + setPointerLength(scaleIndex: number, pointerIndex: number, value: number): void; /** To set PointerNeedleType + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setPointerNeedleType(): void; + setPointerNeedleType(scaleIndex: number, pointerIndex: number, value: number): void; /** To set PointerPlacement + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setPointerPlacement(): void; + setPointerPlacement(scaleIndex: number, pointerIndex: number, value: number): void; /** To set PointerValue + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setPointerValue(): void; + setPointerValue(scaleIndex: number, pointerIndex: number, value: number): void; /** To set PointerWidth + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setPointerWidth(): void; + setPointerWidth(scaleIndex: number, pointerIndex: number, value: number): void; /** To set RangeBorderWidth + * @param {number} scaleIndex value for the gauge + * @param {number} rangeIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setRangeBorderWidth(): void; + setRangeBorderWidth(scaleIndex: number, rangeIndex: number, value: number): void; /** To set RangeDistanceFromScale + * @param {number} scaleIndex value for the gauge + * @param {number} rangeIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setRangeDistanceFromScale(): void; + setRangeDistanceFromScale(scaleIndex: number, rangeIndex: number, value: number): void; /** To set RangeEndValue + * @param {number} scaleIndex value for the gauge + * @param {number} rangeIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setRangeEndValue(): void; + setRangeEndValue(scaleIndex: number, rangeIndex: number, value: number): void; /** To set RangePosition + * @param {number} scaleIndex value for the gauge + * @param {number} rangeIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setRangePosition(): void; + setRangePosition(scaleIndex: number, rangeIndex: number, value: number): void; /** To set RangeSize + * @param {number} scaleIndex value for the gauge + * @param {number} rangeIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setRangeSize(): void; + setRangeSize(scaleIndex: number, rangeIndex: number, value: number): void; /** To set RangeStartValue + * @param {number} scaleIndex value for the gauge + * @param {number} rangeIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setRangeStartValue(): void; + setRangeStartValue(scaleIndex: number, rangeIndex: number, value: number): void; /** To set ScaleBarSize + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setScaleBarSize(): void; + setScaleBarSize(scaleIndex: number, value: number): void; /** To set ScaleBorderWidth + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setScaleBorderWidth(): void; + setScaleBorderWidth(scaleIndex: number, value: number): void; /** To set ScaleDirection + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setScaleDirection(): void; + setScaleDirection(scaleIndex: number, value: number): void; /** To set ScaleRadius + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setScaleRadius(): void; + setScaleRadius(scaleIndex: number, value: number): void; /** To set StartAngle + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setStartAngle(): void; + setStartAngle(scaleIndex: number, value: number): void; /** To set SubGaugeLocation + * @param {number} scaleIndex value for the gauge + * @param {number} GaugeIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setSubGaugeLocation(): void; + setSubGaugeLocation(scaleIndex: number, GaugeIndex: number, value: number): void; /** To set SweepAngle + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setSweepAngle(): void; + setSweepAngle(scaleIndex: number, value: number): void; /** To set TickAngle + * @param {number} scaleIndex value for the gauge + * @param {number} tickIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setTickAngle(): void; + setTickAngle(scaleIndex: number, tickIndex: number, value: number): void; /** To set TickDistanceFromScale + * @param {number} scaleIndex value for the gauge + * @param {number} tickIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setTickDistanceFromScale(): void; + setTickDistanceFromScale(scaleIndex: number, tickIndex: number, value: number): void; /** To set TickHeight + * @param {number} scaleIndex value for the gauge + * @param {number} tickIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setTickHeight(): void; + setTickHeight(scaleIndex: number, tickIndex: number, value: number): void; /** To set TickPlacement + * @param {number} scaleIndex value for the gauge + * @param {number} tickIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setTickPlacement(): void; + setTickPlacement(scaleIndex: number, tickIndex: number, value: number): void; /** To set TickStyle + * @param {number} scaleIndex value for the gauge + * @param {number} tickIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setTickStyle(): void; + setTickStyle(scaleIndex: number, tickIndex: number, value: number): void; /** To set TickWidth + * @param {number} scaleIndex value for the gauge + * @param {number} tickIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setTickWidth(): void; + setTickWidth(scaleIndex: number, tickIndex: number, value: number): void; } export namespace CircularGauge { @@ -50694,7 +51396,7 @@ declare namespace ej.datavisualization { /** Options to customize the left, right, top and bottom margins of chart area. */ - Margin?: any; + margin?: Margin; /** Perspective angle of the 3D view. Chart appears closer when perspective angle is decreased, and distant when perspective angle is increased.This property is applicable only when * 3D view is enabled @@ -52245,6 +52947,11 @@ declare namespace ej.datavisualization { */ enableContrastColor?: boolean; + /** Displays the partially visible labels inside the chart Area + * @Default {false} + */ + showEdgeLabels?: boolean; + /** Options for customizing the border of the data label. */ border?: CommonSeriesOptionsMarkerDataLabelBorder; @@ -53790,6 +54497,29 @@ declare namespace ej.datavisualization { toggleSeriesVisibility?: boolean; } + export interface Margin { + + /** Spacing for the left margin of chart area. Setting positive value decreases the width of the chart area from left side. + * @Default {10} + */ + left?: number; + + /** Spacing for the right margin of chart area. Setting positive value decreases the width of the chart area from right side. + * @Default {10} + */ + right?: number; + + /** Spacing for the top margin of chart area. Setting positive value decreases the height of the chart area from the top. + * @Default {10} + */ + top?: number; + + /** Spacing for the bottom margin of the chart area. Setting positive value decreases the height of the chart area from the bottom. + * @Default {10} + */ + bottom?: number; + } + export interface PrimaryXAxisAlternateGridBandEven { /** Fill color for the even grid bands. @@ -56217,6 +56947,11 @@ declare namespace ej.datavisualization { */ enableContrastColor?: boolean; + /** Displays the partially visible data labels inside the chart Area. + * @Default {false} + */ + showEdgeLabels?: boolean; + /** Options for customizing the border of the data label. */ border?: SeriesMarkerDataLabelBorder; @@ -59604,14 +60339,18 @@ declare namespace ej.datavisualization { redraw(): void; /** To set the value for comparative measure in bullet graph. + * @param {number} value for the graph + * @param {number} value for the graph * @returns {void} */ - setComparativeMeasureSymbol(): void; + setComparativeMeasureSymbol(index: number, measure: number): void; /** To set the value for feature measure bar. + * @param {number} value for the graph + * @param {number} value for the graph * @returns {void} */ - setFeatureMeasureBarValue(): void; + setFeatureMeasureBarValue(index: number, measure: number): void; } export namespace BulletGraph { @@ -62830,6 +63569,13 @@ declare namespace ej.datavisualization { */ exportDiagram(options?: Diagram.Options): string; + /** The exportImage method is used to export the image passed through argument with different image format and exporting options as like exportDiagram method. + * @param {string} pass the base64String image to be exported. + * @param {Diagram.Options} options to export the desired region of diagram to the desired formats. + * @returns {string} + */ + exportImage(image: string, options?: Diagram.Options): string; + /** Read a node/connector object by its name * @param {string} name of the node/connector that is to be identified * @returns {any} @@ -62844,6 +63590,18 @@ declare namespace ej.datavisualization { */ fitToPage(mode?: ej.datavisualization.Diagram.FitMode, region?: ej.datavisualization.Diagram.Region, margin?: any): void; + /** Get the diagram DOM element as a string along with dependent stylesheets. + * @param {any[]} If its specified, will get the diagram DOM element along with specified stylesheet references. Please note that you have to define absolute path for local CSS file. + * If not specified, will get the diagram content along with all stylesheets loaded in the document. + * @returns {void} + */ + getDiagramContent(styleSheets?: any[]): void; + + /** Get the bounds of the diagram. + * @returns {void} + */ + getDiagramBounds(): void; + /** Group the selected nodes and connectors * @returns {void} */ @@ -62888,9 +63646,17 @@ declare namespace ej.datavisualization { paste(object?: any, rename?: boolean): void; /** Print the diagram as image + * @param {Diagram.Options} options to print the desired region of diagram and print the diagram in multiple pages. * @returns {void} */ - print(): void; + print(options?: Diagram.Options): void; + + /** The printImage method is used to print the image passed through argument with desired region and multiple pages as like print method. + * @param {string} pass the base64String image to be printed. + * @param {Diagram.Options} options to export the desired region of diagram to the desired formats. + * @returns {string} + */ + printImage(image: string, options?: Diagram.Options): string; /** Restore the last action that was reverted * @returns {void} @@ -63098,6 +63864,119 @@ declare namespace ej.datavisualization { /** to resize the diagram content to fill its allocated space. */ stretch?: ej.datavisualization.Diagram.Stretch; + + /** to export the diagram into multiple pages + */ + multiplePage?: boolean; + + /** to set the page width of the diagram while exporting the diagram into multiple pages. + */ + pageWidth?: number; + + /** to set the page height of the diagram while exporting the diagram into multiple pages. + */ + pageHeight?: number; + + /** to sets the orientation of the page. + */ + pageOrientation?: ej.datavisualization.Diagram.PageOrientations; + } + + export interface Options { + + /** name of the file to be downloaded. + */ + fileName?: string; + + /** format of the exported file/data. + */ + format?: ej.datavisualization.Diagram.FileFormats; + + /** to set the region of the diagram to be exported. + */ + region?: ej.datavisualization.Diagram.Region; + + /** to export any custom region of diagram. + */ + bounds?: any; + + /** to set margin to the exported data. + */ + margin?: any; + + /** to export the diagram into multiple pages + */ + multiplePage?: boolean; + + /** to set the page width of the diagram while exporting the diagram into multiple pages. + */ + pageWidth?: number; + + /** to set the page height of the diagram while exporting the diagram into multiple pages. + */ + pageHeight?: number; + + /** to sets the orientation of the page. + */ + pageOrientation?: ej.datavisualization.Diagram.PageOrientations; + } + + export interface Options { + + /** to set the region of the diagram to be printed. + */ + region?: ej.datavisualization.Diagram.Region; + + /** to print any custom region of diagram. + */ + bounds?: any; + + /** to resize the diagram content to fill its allocated space and printed. + */ + stretch?: ej.datavisualization.Diagram.Stretch; + + /** to print the diagram into multiple pages + */ + multiplePage?: boolean; + + /** to set the page width of the diagram while printing the diagram into multiple pages. + */ + pageWidth?: number; + + /** to set the page height of the diagram while printing the diagram into multiple pages. + */ + pageHeight?: number; + + /** to sets the orientation of the page. + */ + pageOrientation?: ej.datavisualization.Diagram.PageOrientations; + } + + export interface Options { + + /** to set the region of the diagram to be printed. + */ + region?: ej.datavisualization.Diagram.Region; + + /** to print any custom region of diagram. + */ + bounds?: any; + + /** to export the diagram into multiple pages + */ + multiplePage?: boolean; + + /** to set the page width of the diagram while printing the diagram into multiple pages. + */ + pageWidth?: number; + + /** to set the page height of the diagram while printing the diagram into multiple pages. + */ + pageHeight?: number; + + /** to sets the orientation of the page. + */ + pageOrientation?: ej.datavisualization.Diagram.PageOrientations; } export interface Zoom { @@ -63228,6 +64107,10 @@ declare namespace ej.datavisualization { */ showTooltip?: boolean; + /** Defines diagram serialization properties that would defines how the serialization content would be. + */ + serializationSettings?: SerializationSettings; + /** Defines the properties of the both the horizontal and vertical gauge to measure the diagram area. */ rulerSettings?: RulerSettings; @@ -63375,6 +64258,10 @@ declare namespace ej.datavisualization { /** Triggered when the diagram is rendered completely. */ create?(e: CreateEventArgs): void; + + /** Used to decide on the action on Diagramming elements at runtime. + */ + setTool?(e: SetToolEventArgs): void; } export interface AutoScrollChangeEventArgs { @@ -64144,6 +65031,17 @@ declare namespace ej.datavisualization { diagramId?: string; } + export interface SetToolEventArgs { + + /** Returns the port when mouse move over on it + */ + source?: any; + + /** Defines the tool to be activated. + */ + action?: ej.datavisualization.Diagram.ActiveTool; + } + export interface BackgroundImage { /** Defines how to align the background image over the diagram area. @@ -64266,6 +65164,11 @@ declare namespace ej.datavisualization { */ boundaryConstraints?: boolean; + /** Enables or disables the default behaviors of the label. + * @Default {ej.datavisualization.Diagram.LabelConstraints.None} + */ + constraints?: ej.datavisualization.Diagram.LabelConstraints|string; + /** Sets the fill color of the text area * @Default {transparent} */ @@ -64286,6 +65189,11 @@ declare namespace ej.datavisualization { */ fontSize?: number; + /** Sets the height of the label(the maximum value of label height and the connector height will be considered as label height) + * @Default {0} + */ + height?: number; + /** Sets the horizontal alignment of the label. * @Default {ej.datavisualization.Diagram.HorizontalAlignment.Center} */ @@ -65068,6 +65976,21 @@ declare namespace ej.datavisualization { * @Default {30} */ root?: string; + + /** Defines how long edges should be, ideally. This will be the resting length for the springs. + * @Default {100} + */ + springLength?: number; + + /** Defines how long edges should be, ideally. This will be the resting length for the springs. + * @Default {0.442} + */ + springFactor?: number; + + /** Defines how long edges should be, ideally. This will be the resting length for the springs. + * @Default {1000} + */ + maxIteration?: number; } export interface NodesAnnotation { @@ -65291,11 +66214,6 @@ declare namespace ej.datavisualization { */ stops?: any[]; - /** Defines the type of gradient - * @Default {linear} - */ - type?: string; - /** Defines the left most position(relative to node) of the rectangular region that needs to be painted * @Default {0} */ @@ -65319,11 +66237,6 @@ declare namespace ej.datavisualization { export interface NodesGradientRadialGradient { - /** Defines the type of gradient - * @Default {radial} - */ - type?: string; - /** Defines the position of the outermost circle * @Default {0} */ @@ -65438,6 +66351,11 @@ declare namespace ej.datavisualization { */ borderWidth?: number; + /** Enables or disables the default behaviors of the label. + * @Default {ej.datavisualization.Diagram.LabelConstraints.None} + */ + constraints?: ej.datavisualization.Diagram.LabelConstraints|string; + /** Sets the fill color of the text area * @Default {transparent} */ @@ -65458,6 +66376,11 @@ declare namespace ej.datavisualization { */ fontSize?: number; + /** Sets the height of the label(the maximum value of label height and the node height will be considered as label height) + * @Default {0} + */ + height?: number; + /** Sets the horizontal alignment of the label. * @Default {ej.datavisualization.Diagram.HorizontalAlignment.Center} */ @@ -65733,6 +66656,10 @@ declare namespace ej.datavisualization { * @Default {ej.datavisualization.Diagram.PortVisibility.Default} */ visibility?: ej.datavisualization.Diagram.PortVisibility|string; + + /** Sets the name of the node which contains this port. + */ + parent?: string; } export interface NodesShadow { @@ -65753,6 +66680,38 @@ declare namespace ej.datavisualization { opacity?: number; } + export interface NodesSubProcessEvent { + + /** Sets the type of the event by which the sub-process will be triggered + * @Default {ej.datavisualization.Diagram.BPMNEvents.Start} + */ + event?: ej.datavisualization.Diagram.BPMNEvents|string; + + /** Sets the fraction/ratio(relative to parent) that defines the position of the event shape + * @Default {ej.datavisualization.Diagram.Point(0.5, 0.5)} + */ + offset?: any; + + /** Sets the name of the BPMN event shape. + */ + name?: string; + + /** Defines the type of the event trigger + * @Default {ej.datavisualization.Diagram.BPMNTriggers.Message} + */ + trigger?: ej.datavisualization.Diagram.BPMNTriggers|string; + + /** An array of objects where each object represents a port + * @Default {[]} + */ + ports?: any[]; + + /** A collection of objects where each object represents a label + * @Default {[]} + */ + labels?: any[]; + } + export interface NodesSubProcess { /** Defines whether the BPMN sub process is without any prescribed order or not @@ -65782,7 +66741,7 @@ declare namespace ej.datavisualization { /** Defines the collection of events that need to be appended with BPMN Sub-Process */ - events?: any[]; + events?: NodesSubProcessEvent[]; /** Defines the loop type of a sub process. * @Default {ej.datavisualization.Diagram.BPMNLoops.None} @@ -65826,6 +66785,10 @@ declare namespace ej.datavisualization { * @Default {ej.datavisualization.Diagram.BPMNTasks.None} */ type?: ej.datavisualization.Diagram.BPMNTasks|string; + + /** Defines the collection of events that need to be appended with BPMN tasks + */ + events?: any[]; } export interface Node { @@ -66299,6 +67262,16 @@ declare namespace ej.datavisualization { export interface SelectedItemsUserHandle { + /** Sets the horizontal alignment of the user handle + * @Default {ej.datavisualization.Diagram.HorizontalAlignment.Center} + */ + horizontalAlignment?: ej.datavisualization.Diagram.HorizontalAlignment|string; + + /** To set the margin of the user handle + * @Default {ej.datavisualization.Diagram.Margin()} + */ + margin?: any; + /** Defines the name of the user handle */ name?: string; @@ -66318,6 +67291,11 @@ declare namespace ej.datavisualization { */ enableMultiSelection?: boolean; + /** Sets the fraction/ratio(relative to node) that defines the position of the user handle + * @Default {ej.datavisualization.Diagram.point(0.5, 1)} + */ + offset?: any; + /** Sets the stroke color of the user handle * @Default {transparent} */ @@ -66341,6 +67319,11 @@ declare namespace ej.datavisualization { */ tool?: any; + /** Sets the vertical alignment of the user handle + * @Default {ej.datavisualization.Diagram.VerticalAlignment.Center} + */ + verticalAlignment?: ej.datavisualization.Diagram.VerticalAlignment|string; + /** Defines the visibility of the user handle * @Default {true} */ @@ -66400,6 +67383,14 @@ declare namespace ej.datavisualization { width?: number; } + export interface SerializationSettings { + + /** defines whether the default diagram properties can be serialized or not. + * @Default {false} + */ + preventDefaultValues?: boolean; + } + export interface RulerSettingsHorizontalRuler { /** Defines the number of intervals to be present on the each segment of the horizontal ruler. @@ -66776,6 +67767,8 @@ declare namespace ej.datavisualization { InheritCrispEdges, //Enables the contrast between clean edges of connector over rendering speed and geometric precision DragLimit, + //Enables or disables bridging over a connector, if bridging constraints disabled.. + BridgeObstacle, //Enables connector to be selected and dragged. Interaction, //Enables all constraints @@ -66802,6 +67795,22 @@ declare namespace ej.datavisualization { After, } } + namespace Diagram { + enum LabelConstraints { + //Disable all label Constraints + None, + //Enables label to be selected + Selectable, + //Enables label to be Dragged + Draggable, + //Enables label to be Resized + Resizable, + //Enables label to be Rotated + Rotatable, + //Enables all label constraints + All, + } + } namespace Diagram { enum LabelRelativeMode { //Sets the relativeMode as SegmentPath @@ -67645,6 +68654,16 @@ declare namespace ej.datavisualization { ZoomOut, } } + namespace Diagram { + enum ActiveTool { + //Set the default Tool + None, + //Activate the port tool to drag when the mouse is moved over the port + Drag, + //Activate the draw tool to draw when the mouse is moved over the port + Draw, + } + } class HeatMap extends ej.Widget { static fn: HeatMap; diff --git a/types/elasticsearch/elasticsearch-tests.ts b/types/elasticsearch/elasticsearch-tests.ts index 1be3f740bc..3043a1f473 100644 --- a/types/elasticsearch/elasticsearch-tests.ts +++ b/types/elasticsearch/elasticsearch-tests.ts @@ -1,6 +1,6 @@ -import elasticsearch = require("elasticsearch"); +import * as elasticsearch from "elasticsearch"; -var client = new elasticsearch.Client({ +let client = new elasticsearch.Client({ host: 'localhost:9200', log: 'trace' }); @@ -10,26 +10,26 @@ client = new elasticsearch.Client({ 'box1.server.org', 'box2.server.org' ], - selector: function (hosts: any) { } + selector: (hosts: any) => { } }); client.ping({ requestTimeout: 30000 -}, function (error) { +}, (error) => { }); client.search({ q: 'pants' -}).then(function (body) { - var hits = body.hits.hits; -}, function (error) { +}).then((body) => { + const hits = body.hits.hits; +}, (error) => { }); client.indices.delete({ index: 'test_index', ignore: [404] -}).then(function (body) { -}, function (error) { +}).then((body) => { +}, (error) => { }); client.deleteByQuery({ @@ -39,8 +39,8 @@ client.deleteByQuery({ query: { } } -}).then(function (response) { -}, function (error) { +}).then((response) => { +}, (error) => { }); client.create({ @@ -103,7 +103,7 @@ client.cluster.stats({ client.count({ index: 'index_name' -}, function (error, response) { +}, (error, response) => { // ... }); @@ -120,7 +120,7 @@ client.count({ } } } -}, function (err, response) { +}, (err, response) => { // ... }); @@ -132,7 +132,7 @@ client.explain({ // the query to score it against q: 'field:value' -}, function (error, response) { +}, (error, response) => { // ... }); @@ -145,7 +145,7 @@ client.explain({ match: { title: 'test' } } } -}, function (error, response) { +}, (error, response) => { // ... }); @@ -158,8 +158,7 @@ client.index({ tags: ['y', 'z'], published: true, } -}, function (error, response) { - +}, (error, response) => { }); client.mget({ @@ -170,7 +169,7 @@ client.mget({ { _index: 'indexC', _type: 'typeC', _id: '1' } ] } -}, function (error, response) { +}, (error, response) => { // ... }); @@ -180,14 +179,14 @@ client.mget({ body: { ids: [1, 2, 3] } -}, function (error, response) { +}, (error, response) => { // ... }); client.search({ index: 'myindex', q: 'title:test' -}, function (error, response) { +}, (error, response) => { // ... }); @@ -207,7 +206,7 @@ client.search({ } } } -}, function (error, response) { +}, (error, response) => { // ... }); @@ -221,12 +220,11 @@ client.suggest({ } } } -}, function (error, response) { +}, (error, response) => { }); - // first we do a search, and specify a scroll timeout -var allTitles: string[] = []; +const allTitles: string[] = []; client.search({ index: 'myindex', // Set to 30 seconds because we are calling right back @@ -236,14 +234,14 @@ client.search({ q: 'title:test' }, function getMoreUntilDone(error, response) { // collect the title from each response - response.hits.hits.forEach(function (hit) { + response.hits.hits.forEach((hit) => { allTitles.push(hit.fields.title); }); if (response.hits.total !== allTitles.length) { // now we can call scroll over and over client.scroll({ - scrollId: response._scroll_id, + scrollId: response._scroll_id!, scroll: '30s' }, getMoreUntilDone); } else { @@ -258,8 +256,13 @@ client.indices.updateAliases({ { add: { index: 'logstash-2014.05', alias: 'logstash-current' } } ] } -}).then(function (response) { +}).then((response) => { // ... -}, function (error) { +}, (error) => { // ... }); + +// Errors +function testErrors() { + throw new elasticsearch.errors.AuthenticationException(); +} diff --git a/types/elasticsearch/index.d.ts b/types/elasticsearch/index.d.ts index 8acc7e4097..1b45a237e5 100644 --- a/types/elasticsearch/index.d.ts +++ b/types/elasticsearch/index.d.ts @@ -1,1608 +1,1659 @@ // Type definitions for elasticsearch 5.0 // Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html -// Definitions by: Casper Skydt , Blake Smith , Dave Dunkin , Jeffery Grajkowski , Margus Lamp , Ahmad Ferdous Bin Alam +// Definitions by: Casper Skydt +// Blake Smith +// Dave Dunkin +// Jeffery Grajkowski +// Margus Lamp +// Ahmad Ferdous Bin Alam +// Simon Schick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 -declare module Elasticsearch { - export class Client { - constructor(params: ConfigOptions); - cat: Cat; - cluster: Cluster; - indices: Indices; - ingest: Ingest; - nodes: Nodes; - snapshot: Snapshot; - tasks: Tasks; - bulk(params: BulkIndexDocumentsParams): Promise; - bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; - clearScroll(params: ClearScrollParams, callback: (error: any, response: any) => void): void; - clearScroll(params: ClearScrollParams): Promise; - count(params: CountParams, callback: (error: any, response: CountResponse) => void): void; - count(params: CountParams): Promise; - create(params: CreateDocumentParams): Promise; - create(params: CreateDocumentParams, callback: (err: any, response: CreateDocumentResponse, status: any) => void): void; - delete(params: DeleteDocumentParams): Promise; - delete(params: DeleteDocumentParams, callback: (error: any, response: DeleteDocumentResponse) => void): void; - deleteByQuery(params: DeleteDocumentByQueryParams): Promise; - deleteByQuery(params: DeleteDocumentByQueryParams, callback: (error: any, response: DeleteDocumentByQueryResponse) => void): void; - deleteScript(params: DeleteScriptParams): Promise; - deleteScript(params: DeleteScriptParams, callback: (error: any, response: any) => void): void; - deleteTemplate(params: DeleteTemplateParams): Promise; - deleteTemplate(params: DeleteTemplateParams, callback: (error: any, response: any) => void): void; - exists(params: ExistsParams): Promise; - exists(params: ExistsParams, callback: (error: any, response: any, status?: any) => void): void; - explain(params: ExplainParams): Promise; - explain(params: ExplainParams, callback: (error: any, response: ExplainResponse) => void): void; - fieldStats(params: FieldStatsParams): Promise; - fieldStats(params: FieldStatsParams, callback: (error: any, response: FieldStatsResponse) => void): void; - get(params: GetParams, callback: (error: any, response: GetResponse) => void): void; - get(params: GetParams): Promise>; - getScript(params: GetScriptParams): Promise; - getScript(params: GetScriptParams, callback: (error: any, response: any) => void): void; - getSource(params: GetSourceParams): Promise; - getSource(params: GetSourceParams, callback: (error: any, response: any) => void): void; - getTemplate(params: GetTemplateParams): Promise; - getTemplate(params: GetTemplateParams, callback: (error: any, response: any) => void): void; - index(params: IndexDocumentParams): Promise; - index(params: IndexDocumentParams, callback: (error: any, response: any) => void): void; - info(params: InfoParams): Promise; - info(params: InfoParams, callback: (error: any, response: any) => void): void; - mget(params: MGetParams, callback: (error: any, response: MGetResponse) => void): void; - mget(params: MGetParams): Promise>; - msearch(params: MSearchParams, callback: (error: any, response: MSearchResponse) => void): void; - msearch(params: MSearchParams): Promise>; - msearchTemplate(params: MSearchTemplateParams, callback: (error: any, response: MSearchResponse) => void): void; - msearchTemplate(params: MSearchTemplateParams): Promise>; - mtermvectors(params: MTermVectorsParams): Promise; - mtermvectors(params: MTermVectorsParams, callback: (error: any, response: any) => void): void; - ping(params: PingParams): Promise; - ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void; - putScript(params: PutScriptParams): Promise; - putScript(params: PutScriptParams, callback: (err: any, response: any, status: any) => void): void; - putTemplate(params: PutTemplateParams): Promise; - putTemplate(params: PutTemplateParams, callback: (err: any, response: any, status: any) => void): void; - reindex(params: ReindexParams): Promise; - reindex(params: ReindexParams, callback: (error: any, response: ReindexResponse) => void): void; - reindexRethrottle(params: ReindexRethrottleParams): Promise; - reindexRethrottle(params: ReindexRethrottleParams, callback: (error: any, response: any) => void): void; - renderSearchTemplate(params: RenderSearchTemplateParams): Promise; - renderSearchTemplate(params: RenderSearchTemplateParams, callback: (error: any, response: any) => void): void; - scroll(params: ScrollParams): Promise>; - scroll(params: ScrollParams, callback: (error: any, response: SearchResponse) => void): void; - search(params: SearchParams): Promise>; - search(params: SearchParams, callback: (error: any, response: SearchResponse) => void): void; - searchShards(params: SearchShardsParams): Promise; - searchShards(params: SearchShardsParams, callback: (error: any, response: SearchShardsResponse) => void): void; - searchTemplate(params: SearchTemplateParams): Promise; - searchTemplate(params: SearchTemplateParams, callback: (error: any, response: any) => void): void; - suggest(params: SuggestParams): Promise; - suggest(params: SuggestParams, callback: (error: any, response: any) => void): void; - termvectors(params: TermvectorsParams): Promise; - termvectors(params: TermvectorsParams, callback: (error: any, response: any) => void): void; - update(params: UpdateDocumentParams): Promise; - update(params: UpdateDocumentParams, callback: (error: any, response: any) => void): void; - updateByQuery(params: UpdateDocumentByQueryParams): Promise; - updateByQuery(params: UpdateDocumentByQueryParams, callback: (error: any, response: any) => void): void; - close(): void; - } +export class Client { + constructor(params: ConfigOptions); + cat: Cat; + cluster: Cluster; + indices: Indices; + ingest: Ingest; + nodes: Nodes; + snapshot: Snapshot; + tasks: Tasks; + bulk(params: BulkIndexDocumentsParams): Promise; + bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; + clearScroll(params: ClearScrollParams, callback: (error: any, response: any) => void): void; + clearScroll(params: ClearScrollParams): Promise; + count(params: CountParams, callback: (error: any, response: CountResponse) => void): void; + count(params: CountParams): Promise; + create(params: CreateDocumentParams): Promise; + create(params: CreateDocumentParams, callback: (err: any, response: CreateDocumentResponse, status: any) => void): void; + delete(params: DeleteDocumentParams): Promise; + delete(params: DeleteDocumentParams, callback: (error: any, response: DeleteDocumentResponse) => void): void; + deleteByQuery(params: DeleteDocumentByQueryParams): Promise; + deleteByQuery(params: DeleteDocumentByQueryParams, callback: (error: any, response: DeleteDocumentByQueryResponse) => void): void; + deleteScript(params: DeleteScriptParams): Promise; + deleteScript(params: DeleteScriptParams, callback: (error: any, response: any) => void): void; + deleteTemplate(params: DeleteTemplateParams): Promise; + deleteTemplate(params: DeleteTemplateParams, callback: (error: any, response: any) => void): void; + exists(params: ExistsParams): Promise; + exists(params: ExistsParams, callback: (error: any, response: any, status?: any) => void): void; + explain(params: ExplainParams): Promise; + explain(params: ExplainParams, callback: (error: any, response: ExplainResponse) => void): void; + fieldStats(params: FieldStatsParams): Promise; + fieldStats(params: FieldStatsParams, callback: (error: any, response: FieldStatsResponse) => void): void; + get(params: GetParams, callback: (error: any, response: GetResponse) => void): void; + get(params: GetParams): Promise>; + getScript(params: GetScriptParams): Promise; + getScript(params: GetScriptParams, callback: (error: any, response: any) => void): void; + getSource(params: GetSourceParams): Promise; + getSource(params: GetSourceParams, callback: (error: any, response: any) => void): void; + getTemplate(params: GetTemplateParams): Promise; + getTemplate(params: GetTemplateParams, callback: (error: any, response: any) => void): void; + index(params: IndexDocumentParams): Promise; + index(params: IndexDocumentParams, callback: (error: any, response: any) => void): void; + info(params: InfoParams): Promise; + info(params: InfoParams, callback: (error: any, response: any) => void): void; + mget(params: MGetParams, callback: (error: any, response: MGetResponse) => void): void; + mget(params: MGetParams): Promise>; + msearch(params: MSearchParams, callback: (error: any, response: MSearchResponse) => void): void; + msearch(params: MSearchParams): Promise>; + msearchTemplate(params: MSearchTemplateParams, callback: (error: any, response: MSearchResponse) => void): void; + msearchTemplate(params: MSearchTemplateParams): Promise>; + mtermvectors(params: MTermVectorsParams): Promise; + mtermvectors(params: MTermVectorsParams, callback: (error: any, response: any) => void): void; + ping(params: PingParams): Promise; + ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void; + putScript(params: PutScriptParams): Promise; + putScript(params: PutScriptParams, callback: (err: any, response: any, status: any) => void): void; + putTemplate(params: PutTemplateParams): Promise; + putTemplate(params: PutTemplateParams, callback: (err: any, response: any, status: any) => void): void; + reindex(params: ReindexParams): Promise; + reindex(params: ReindexParams, callback: (error: any, response: ReindexResponse) => void): void; + reindexRethrottle(params: ReindexRethrottleParams): Promise; + reindexRethrottle(params: ReindexRethrottleParams, callback: (error: any, response: any) => void): void; + renderSearchTemplate(params: RenderSearchTemplateParams): Promise; + renderSearchTemplate(params: RenderSearchTemplateParams, callback: (error: any, response: any) => void): void; + scroll(params: ScrollParams): Promise>; + scroll(params: ScrollParams, callback: (error: any, response: SearchResponse) => void): void; + search(params: SearchParams): Promise>; + search(params: SearchParams, callback: (error: any, response: SearchResponse) => void): void; + searchShards(params: SearchShardsParams): Promise; + searchShards(params: SearchShardsParams, callback: (error: any, response: SearchShardsResponse) => void): void; + searchTemplate(params: SearchTemplateParams): Promise; + searchTemplate(params: SearchTemplateParams, callback: (error: any, response: any) => void): void; + suggest(params: SuggestParams): Promise; + suggest(params: SuggestParams, callback: (error: any, response: any) => void): void; + termvectors(params: TermvectorsParams): Promise; + termvectors(params: TermvectorsParams, callback: (error: any, response: any) => void): void; + update(params: UpdateDocumentParams): Promise; + update(params: UpdateDocumentParams, callback: (error: any, response: any) => void): void; + updateByQuery(params: UpdateDocumentByQueryParams): Promise; + updateByQuery(params: UpdateDocumentByQueryParams, callback: (error: any, response: any) => void): void; + close(): void; +} - export interface ConfigOptions { - host?: any; - hosts?: any; - httpAuth?: string; - log?: any; - apiVersion?: string; - plugins?: any; - sniffOnStart?: boolean; - sniffInterval?: number; - sniffOnConnectionFault?: boolean; - maxRetries?: number; - requestTimeout?: number; - deadTimeout?: number; - pingTimeout?: number; - keepAlive?: boolean; - maxSockets?: number; - suggestCompression?: boolean; - connectionClass?: string; - sniffedNodesProtocol?: string; - ssl?: Object; - selector?: any; - defer?: () => void; - nodesToHostCallback?: any; - createNodeAgent?: any; - } +export interface ConfigOptions { + host?: any; + hosts?: any; + httpAuth?: string; + log?: any; + apiVersion?: string; + plugins?: any; + sniffOnStart?: boolean; + sniffInterval?: number; + sniffOnConnectionFault?: boolean; + maxRetries?: number; + requestTimeout?: number; + deadTimeout?: number; + pingTimeout?: number; + keepAlive?: boolean; + maxSockets?: number; + suggestCompression?: boolean; + connectionClass?: string; + sniffedNodesProtocol?: string; + ssl?: object; + selector?: any; + defer?: () => void; + nodesToHostCallback?: any; + createNodeAgent?: any; +} - export interface Explanation { - value: number; - description: string; - details: Explanation[]; - } +export interface Explanation { + value: number; + description: string; + details: Explanation[]; +} - export interface GenericParams { - requestTimeout?: number; - maxRetries?: number; - method?: string; - body?: any; - ignore?: number | number[]; - filterPath?: string | string[]; - } +export interface GenericParams { + requestTimeout?: number; + maxRetries?: number; + method?: string; + body?: any; + ignore?: number | number[]; + filterPath?: string | string[]; +} - export interface ShardsResponse { - total: number; - successful: number; - failed: number; - } +export interface ShardsResponse { + total: number; + successful: number; + failed: number; +} - /** - * A string of a number and a time unit. A time unit is one of - * [d, h, m, s, ms, micros, nanos]. eg: "30s" for 30 seconds. - * These are incorrectly identified as `Date | number` in the docs as of 2016-11-15. - */ - export type TimeSpan = string; +/** + * A string of a number and a time unit. A time unit is one of + * [d, h, m, s, ms, micros, nanos]. eg: "30s" for 30 seconds. + * These are incorrectly identified as `Date | number` in the docs as of 2016-11-15. + */ +export type TimeSpan = string; - export type NameList = string | string[] | boolean; - export type Refresh = boolean | "true" | "false" | "wait_for" | ""; - export type VersionType = "internal" | "external" | "external_gte" | "force"; - export type ExpandWildcards = "open" | "closed" | "none" | "all"; - export type DefaultOperator = "AND" | "OR"; - export type Conflicts = "abort" | "proceed"; +export type NameList = string | string[] | boolean; +export type Refresh = boolean | "true" | "false" | "wait_for" | ""; +export type VersionType = "internal" | "external" | "external_gte" | "force"; +export type ExpandWildcards = "open" | "closed" | "none" | "all"; +export type DefaultOperator = "AND" | "OR"; +export type Conflicts = "abort" | "proceed"; - export interface BulkIndexDocumentsParams extends GenericParams { - waitForActiveShards?: string; - refresh?: Refresh; - routing?: string; - timeout?: TimeSpan; - type?: string; - fields?: NameList; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - pipeline?: string; - index?: string; - } +export interface BulkIndexDocumentsParams extends GenericParams { + waitForActiveShards?: string; + refresh?: Refresh; + routing?: string; + timeout?: TimeSpan; + type?: string; + fields?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + pipeline?: string; + index?: string; +} - export interface ClearScrollParams extends GenericParams { - scrollId: NameList; - } +export interface ClearScrollParams extends GenericParams { + scrollId: NameList; +} - export interface CountParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - minScore?: number; - preference?: string; - routing?: string; - q?: string; - analyzer?: string; - analyzeWildcard?: boolean; - defaultOperator?: DefaultOperator; - df?: string; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - index?: NameList; - type?: NameList; - } +export interface CountParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + minScore?: number; + preference?: string; + routing?: string; + q?: string; + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + index?: NameList; + type?: NameList; +} - export interface CountResponse { - count: number; - _shards: ShardsResponse; - } +export interface CountResponse { + count: number; + _shards: ShardsResponse; +} - export interface CreateDocumentParams extends GenericParams { - waitForActiveShards?: string; - parent?: string; - refresh?: Refresh; - timeout?: TimeSpan; - timestamp?: Date | number; - ttl?: TimeSpan; - version?: number; - versionType?: VersionType; - pipeline?: string; - id?: string; - index: string; - type: string; - } +export interface CreateDocumentParams extends GenericParams { + waitForActiveShards?: string; + parent?: string; + refresh?: Refresh; + timeout?: TimeSpan; + timestamp?: Date | number; + ttl?: TimeSpan; + version?: number; + versionType?: VersionType; + pipeline?: string; + id?: string; + index: string; + type: string; +} - export interface CreateDocumentResponse { - _shards: ShardsResponse; - _index: string; - _type: string; - _id: string; - _version: number; - created: boolean; - result: string; - } +export interface CreateDocumentResponse { + _shards: ShardsResponse; + _index: string; + _type: string; + _id: string; + _version: number; + created: boolean; + result: string; +} - export interface DeleteDocumentParams extends GenericParams { - waitForActiveShards?: string; - parent?: string; - refresh?: Refresh; - routing?: string; - timeout?: TimeSpan; - version?: number; - versionType?: VersionType; - index: string; - type: string; - id: string; - } +export interface DeleteDocumentParams extends GenericParams { + waitForActiveShards?: string; + parent?: string; + refresh?: Refresh; + routing?: string; + timeout?: TimeSpan; + version?: number; + versionType?: VersionType; + index: string; + type: string; + id: string; +} - export interface DeleteDocumentResponse { - _shards: ShardsResponse; - found: boolean; - _index: string; - _type: string; - _id: string; - _version: number; - result: string; - } +export interface DeleteDocumentResponse { + _shards: ShardsResponse; + found: boolean; + _index: string; + _type: string; + _id: string; + _version: number; + result: string; +} - export interface DeleteDocumentByQueryParams extends GenericParams { - analyzer?: string; - analyzeWildcard?: boolean; - defaultOperator?: DefaultOperator; - df?: string; - from?: number; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - conflicts?: Conflicts; - expandWildcards?: ExpandWildcards; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - preference?: string; - q?: string; - routing?: string | string[] | boolean; - scroll?: string; - searchType?: "query_then_fetch" | "dfs_query_then_fetch"; - searchTimeout?: TimeSpan; - size?: number; - sort?: NameList; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - terminateAfter?: number; - stats?: string | string[] | boolean; - version?: number; - requestCache?: boolean; - refresh?: Refresh; - timeout?: TimeSpan; - waitForActiveShards?: string; - scrollSize?: number; - waitForCompletion?: boolean; - requestsPerSecond?: number; - index?: string; - type?: string; - } +export interface DeleteDocumentByQueryParams extends GenericParams { + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + from?: number; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + conflicts?: Conflicts; + expandWildcards?: ExpandWildcards; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + preference?: string; + q?: string; + routing?: string | string[] | boolean; + scroll?: string; + searchType?: "query_then_fetch" | "dfs_query_then_fetch"; + searchTimeout?: TimeSpan; + size?: number; + sort?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + terminateAfter?: number; + stats?: string | string[] | boolean; + version?: number; + requestCache?: boolean; + refresh?: Refresh; + timeout?: TimeSpan; + waitForActiveShards?: string; + scrollSize?: number; + waitForCompletion?: boolean; + requestsPerSecond?: number; + index?: string; + type?: string; +} - export interface DeleteDocumentByQueryResponse { - took: number; - timed_out: boolean; - deleted: number; - batches: number; - version_conflicts: number; - noops: number; - retries: { - bulk: number; - search: number; - }; - throttled_millis: number; - requests_per_second: number; - throttled_until_millis: number; - total: number; - failures: any[]; - } +export interface DeleteDocumentByQueryResponse { + took: number; + timed_out: boolean; + deleted: number; + batches: number; + version_conflicts: number; + noops: number; + retries: { + bulk: number; + search: number; + }; + throttled_millis: number; + requests_per_second: number; + throttled_until_millis: number; + total: number; + failures: any[]; +} - export interface DeleteScriptParams extends GenericParams { - id: string; - lang: string; - } +export interface DeleteScriptParams extends GenericParams { + id: string; + lang: string; +} - export interface DeleteTemplateParams extends GenericParams { - id: string; - } +export interface DeleteTemplateParams extends GenericParams { + id: string; +} - export interface ExistsParams extends GenericParams { - parent?: string; - preference?: string; - realtime?: boolean; - refresh?: boolean; - routing?: string; - id: string; - index: string; - type: string; - } +export interface ExistsParams extends GenericParams { + parent?: string; + preference?: string; + realtime?: boolean; + refresh?: boolean; + routing?: string; + id: string; + index: string; + type: string; +} - export interface ExplainParams extends GenericParams { - analyzeWildcard?: boolean; - analyzer?: string; - defaultOperator?: DefaultOperator; - df?: string; - storedFields?: NameList; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - parent?: string; - preference?: string; - q?: string; - routing?: string; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - id?: string; - index?: string; - type?: string; - } +export interface ExplainParams extends GenericParams { + analyzeWildcard?: boolean; + analyzer?: string; + defaultOperator?: DefaultOperator; + df?: string; + storedFields?: NameList; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + parent?: string; + preference?: string; + q?: string; + routing?: string; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + id?: string; + index?: string; + type?: string; +} - export interface ExplainResponse { - _index: string; - _type: string; - _id: string; - matched: boolean; - explanation: ExplainResponseDetails; - } +export interface ExplainResponse { + _index: string; + _type: string; + _id: string; + matched: boolean; + explanation: ExplainResponseDetails; +} - export interface ExplainResponseDetails { - value: number; - description: string; - details: ExplainResponseDetails[]; - } +export interface ExplainResponseDetails { + value: number; + description: string; + details: ExplainResponseDetails[]; +} - export interface FieldStatsParams extends GenericParams { - fields?: NameList; - level?: "indices" | "cluster"; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index?: NameList; - } +export interface FieldStatsParams extends GenericParams { + fields?: NameList; + level?: "indices" | "cluster"; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index?: NameList; +} - export interface FieldStatsResponse { - _shards: ShardsResponse; - indices: { [indexName: string]: FieldStatsResponseIndex }; - conflicts?: { [fieldName: string]: string }; - } +export interface FieldStatsResponse { + _shards: ShardsResponse; + indices: { [indexName: string]: FieldStatsResponseIndex }; + conflicts?: { [fieldName: string]: string }; +} - export interface FieldStatsResponseIndex { - fields: { [fieldName: string]: FieldStatsResponseField }; - } +export interface FieldStatsResponseIndex { + fields: { [fieldName: string]: FieldStatsResponseField }; +} - export interface FieldStatsResponseField { - max_doc: number; - doc_count: number; - density: number; - sum_doc_freq: number; - sum_total_term_freq: number; - min_value: any; - max_value: any; - is_searchable: string; - is_aggregatable: string; - } +export interface FieldStatsResponseField { + max_doc: number; + doc_count: number; + density: number; + sum_doc_freq: number; + sum_total_term_freq: number; + min_value: any; + max_value: any; + is_searchable: string; + is_aggregatable: string; +} - export interface GetParams extends GenericParams { - storedFields?: NameList; - parent?: string; - preference?: string; - realtime?: boolean; - refresh?: boolean; - routing?: string; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - version?: number; - versionType?: VersionType; - id: string; - index: string; - type: string; - } +export interface GetParams extends GenericParams { + storedFields?: NameList; + parent?: string; + preference?: string; + realtime?: boolean; + refresh?: boolean; + routing?: string; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + version?: number; + versionType?: VersionType; + id: string; + index: string; + type: string; +} - export interface GetResponse { - _index: string; - _type: string; - _id: string; - _version: number; - found: boolean; - _source: T; - } +export interface GetResponse { + _index: string; + _type: string; + _id: string; + _version: number; + found: boolean; + _source: T; +} - export interface GetScriptParams extends GenericParams { - id: string; - lang: string; - } +export interface GetScriptParams extends GenericParams { + id: string; + lang: string; +} - export interface GetSourceParams extends GenericParams { - preference?: string; - realtime?: boolean; - refresh?: boolean; - routing?: string; - _source: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - version?: number; - versionType?: VersionType; - id: string; - index: string; - type: string; - } +export interface GetSourceParams extends GenericParams { + preference?: string; + realtime?: boolean; + refresh?: boolean; + routing?: string; + _source: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + version?: number; + versionType?: VersionType; + id: string; + index: string; + type: string; +} - export interface GetTemplateParams extends GenericParams { - id: string; - } +export interface GetTemplateParams extends GenericParams { + id: string; +} - export interface IndexDocumentParams extends GenericParams { - waitForActiveShards?: string; - opType?: "index" | "create"; - parent?: string; - refresh?: string; - routing?: string; - timeout?: TimeSpan; - timestamp?: Date | number; - ttl?: TimeSpan; - version?: number; - versionType?: VersionType; - pipeline?: string; - id?: string; - index: string; - type: string; - body: T; - } +export interface IndexDocumentParams extends GenericParams { + waitForActiveShards?: string; + opType?: "index" | "create"; + parent?: string; + refresh?: string; + routing?: string; + timeout?: TimeSpan; + timestamp?: Date | number; + ttl?: TimeSpan; + version?: number; + versionType?: VersionType; + pipeline?: string; + id?: string; + index: string; + type: string; + body: T; +} - export interface InfoParams extends GenericParams { - } +export interface InfoParams extends GenericParams { +} - export interface MGetParams extends GenericParams { - storedFields?: NameList; - preference?: string; - realtime?: Boolean; - refresh?: Boolean; - source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - index?: string; - type?: string; - } +export interface MGetParams extends GenericParams { + storedFields?: NameList; + preference?: string; + realtime?: boolean; + refresh?: boolean; + source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + index?: string; + type?: string; +} - export interface MGetResponse { - docs?: GetResponse[]; - } +export interface MGetResponse { + docs?: Array>; +} - export interface MSearchParams extends GenericParams { - search_type?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; - maxConcurrentSearches?: number; - index?: NameList; - type?: NameList; - } +export interface MSearchParams extends GenericParams { + search_type?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; + maxConcurrentSearches?: number; + index?: NameList; + type?: NameList; +} - export interface MSearchResponse { - responses?: SearchResponse[]; - } +export interface MSearchResponse { + responses?: Array>; +} - export interface MSearchTemplateParams extends GenericParams { - search_type?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; - index?: NameList; - type?: NameList; - } +export interface MSearchTemplateParams extends GenericParams { + search_type?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; + index?: NameList; + type?: NameList; +} - export interface MTermVectorsParams extends GenericParams { - ids?: NameList; - termStatistics?: boolean; - fieldStatistics?: boolean; - fields?: NameList; - offsets?: boolean; - positions?: boolean; - payloads?: boolean; - preference?: string; - routing?: string; - parent?: string; - realtime?: boolean; - version?: number; - versionType?: VersionType; - index: string; - type: string; - } +export interface MTermVectorsParams extends GenericParams { + ids?: NameList; + termStatistics?: boolean; + fieldStatistics?: boolean; + fields?: NameList; + offsets?: boolean; + positions?: boolean; + payloads?: boolean; + preference?: string; + routing?: string; + parent?: string; + realtime?: boolean; + version?: number; + versionType?: VersionType; + index: string; + type: string; +} - export interface PingParams extends GenericParams { - } +export interface PingParams extends GenericParams { +} - export interface PutScriptParams extends GenericParams { - id: string; - lang: string; - body: any; - } +export interface PutScriptParams extends GenericParams { + id: string; + lang: string; + body: any; +} - export interface PutTemplateParams extends GenericParams { - id: string; - body: any; - } +export interface PutTemplateParams extends GenericParams { + id: string; + body: any; +} - export interface ReindexParams extends GenericParams { - refresh?: boolean; - timeout?: TimeSpan; - waitForActiveShards?: string; - waitForCompletion?: boolean; - requestsPerSecond?: number; - body: { - conflicts?: string; - source: { - index: string | string[]; - type?: string | string[]; - query?: any; - sort?: any; - size?: number; - remote?: { - host: string; - username?: string; - password?: string; - } - }; - dest: { - index: string; - version_type?: string; - op_type?: string; - routing?: string; - pipeline?: string; - }; - script?: { - inline: string; - lang: string; +export interface ReindexParams extends GenericParams { + refresh?: boolean; + timeout?: TimeSpan; + waitForActiveShards?: string; + waitForCompletion?: boolean; + requestsPerSecond?: number; + body: { + conflicts?: string; + source: { + index: string | string[]; + type?: string | string[]; + query?: any; + sort?: any; + size?: number; + remote?: { + host: string; + username?: string; + password?: string; } }; - } - - export interface ReindexResponse { - took: number; - updated: number; - created: number; - batches: number; - version_conflicts: number; - retries: { - bulk: number; - search: number; - }; - throttled_millis: number; - failures: any[]; - } - - export interface ReindexRethrottleParams extends GenericParams { - requestsPerSecond: number; - taskId: string; - } - - export interface RenderSearchTemplateParams extends GenericParams { - id: string; - } - - export interface ScrollParams extends GenericParams { - scroll: TimeSpan; - scrollId: string; - } - - export interface SearchParams extends GenericParams { - analyzer?: string; - analyzeWildcard?: boolean; - defaultOperator?: DefaultOperator; - df?: string; - explain?: boolean; - storedFields?: NameList; - docvalueFields?: NameList; - fielddataFields?: NameList; - from?: number; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - preference?: string; - q?: string; - routing?: NameList; - scroll?: TimeSpan; - searchType?: "query_then_fetch" | "dfs_query_then_fetch"; - size?: number; - sort?: NameList; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - terminateAfter?: number; - stats?: NameList; - suggestField?: string; - suggestMode?: "missing" | "popular" | "always"; - suggestSize?: number; - suggestText?: string; - timeout?: TimeSpan; - trackScores?: boolean; - version?: boolean; - requestCache?: boolean; - index?: NameList; - type?: NameList; - } - - export interface SearchResponse { - took: number; - timed_out: boolean; - _scroll_id?: string; - _shards: ShardsResponse; - hits: { - total: number; - max_score: number; - hits: { - _index: string; - _type: string; - _id: string; - _score: number; - _source: T; - _version?: number; - _explanation?: Explanation; - fields?: any; - highlight?: any; - inner_hits?: any; - }[]; - }; - aggregations?: any; - } - - export interface SearchShardsParams extends GenericParams { - preference?: string; - routing?: string; - local?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index: NameList; - type: NameList; - } - - export interface SearchShardsResponse { - nodes: any; - shards: SearchShardsResponseShard[][]; - } - - export interface SearchShardsResponseShard { - index: string; - node: string; - primary: boolean; - share: number; - state: string; - allocation_id: { - id: string; - }; - relocating_node: any; - } - - export interface SearchTemplateParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - preference?: string; - routing?: NameList; - scroll?: TimeSpan; - searchType?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; - index: NameList; - type: NameList; - } - - export interface SuggestParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - preference?: string; - routing?: string; - index: NameList; - } - - export interface TermvectorsParams extends GenericParams { - termStatistics?: boolean; - fieldStatistics?: boolean; - fields?: NameList; - offsets?: boolean; - positions?: boolean; - payloads?: boolean; - preference?: string; - routing?: string; - parent?: string; - realtime?: boolean; - version?: number; - versionType?: VersionType; - index: string; - type: string; - id?: string; - } - - export interface UpdateDocumentParams extends GenericParams { - waitForActiveShards?: string; - fields?: NameList; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - lang?: string; - parent?: string; - refresh?: Refresh; - retryOnConflict?: number; - routing?: string; - timeout?: TimeSpan; - timestamp?: Date | number; - ttl?: TimeSpan; - version?: number; - versionType?: "internal" | "force"; - id: string; - index: string; - type: string; - } - - export interface UpdateDocumentByQueryParams extends GenericParams { - analyzer?: string; - analyzeWildcard?: boolean; - defaultOperator?: DefaultOperator; - df?: string; - explain?: boolean; - storedFields?: NameList; - docvalueFields?: NameList; - fielddataFields?: NameList; - from?: number; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - conflicts?: Conflicts; - expandWildcards?: ExpandWildcards; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - pipeline?: string; - preference?: string; - q?: string; - routing?: NameList; - scroll?: TimeSpan; - searchType?: "query_then_fetch" | "dfs_query_then_fetch"; - searchTimeout?: TimeSpan; - size?: number; - sort?: NameList; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - terminateAfter?: number; - stats?: NameList; - suggestField?: string; - suggestMode?: "missing" | "popular" | "always"; - suggestSize?: number; - suggestText?: string; - timeout?: TimeSpan; - trackScores?: boolean; - version?: boolean; - versionType?: boolean; - requestCache?: boolean; - refresh?: boolean; - waitForActiveShards?: string; - scrollSize?: number; - waitForCompletion?: boolean; - requestsPerSecond?: number; - index: NameList; - type: NameList; - } - - export interface Cat { - aliases(params: CatAliasesParams, callback: (error: any, response: any) => void): void; - aliases(params: CatAliasesParams): Promise; - allocation(params: CatAllocationParams, callback: (error: any, response: any) => void): void; - allocation(params: CatAllocationParams): Promise; - count(params: CatCountParams, callback: (error: any, response: any) => void): void; - count(params: CatAllocationParams): Promise; - fielddata(params: CatFielddataParams, callback: (error: any, response: any) => void): void; - fielddata(params: CatFielddataParams): Promise; - health(params: CatHealthParams, callback: (error: any, response: any) => void): void; - health(params: CatHealthParams): Promise; - help(params: CatHelpParams, callback: (error: any, response: any) => void): void; - help(params: CatHelpParams): Promise; - indices(params: CatIndicesParams, callback: (error: any, response: any) => void): void; - indices(params: CatIndicesParams): Promise; - master(params: CatCommonParams, callback: (error: any, response: any) => void): void; - master(params: CatCommonParams): Promise; - nodeattrs(params: CatCommonParams, callback: (error: any, response: any) => void): void; - nodeattrs(params: CatCommonParams): Promise; - nodes(params: CatCommonParams, callback: (error: any, response: any) => void): void; - nodes(params: CatCommonParams): Promise; - pendingTasks(params: CatCommonParams, callback: (error: any, response: any) => void): void; - pendingTasks(params: CatCommonParams): Promise; - plugins(params: CatCommonParams, callback: (error: any, response: any) => void): void; - plugins(params: CatCommonParams): Promise; - recovery(params: CatRecoveryParams, callback: (error: any, response: any) => void): void; - recovery(params: CatRecoveryParams): Promise; - repositories(params: CatCommonParams, callback: (error: any, response: any) => void): void; - repositories(params: CatCommonParams): Promise; - segments(params: CatSegmentsParams, callback: (error: any, response: any) => void): void; - segments(params: CatSegmentsParams): Promise; - shards(params: CatShardsParams, callback: (error: any, response: any) => void): void; - shards(params: CatShardsParams): Promise; - snapshots(params: CatSnapshotsParams, callback: (error: any, response: any) => void): void; - snapshots(params: CatSnapshotsParams): Promise; - tasks(params: CatTasksParams, callback: (error: any, response: any) => void): void; - tasks(params: CatTasksParams): Promise; - threadPool(params: CatThreadPoolParams, callback: (error: any, response: any) => void): void; - threadPool(params: CatThreadPoolParams): Promise; - } - - export type CatBytes = "b" | "k" | "kb" | "m" | "mb" | "g" | "gb" | "t" | "tb" | "p" | "pb"; - - export interface CatCommonParams extends GenericParams { - format: string; - local?: boolean; - masterTimeout?: TimeSpan; - h?: NameList; - help?: boolean; - v?: boolean; - } - - export interface CatAliasesParams extends CatCommonParams { - name?: NameList; - } - - export interface CatAllocationParams extends CatCommonParams { - bytes?: CatBytes; - nodeId?: NameList; - } - - export interface CatCountParams extends CatCommonParams { - index?: NameList; - } - - export interface CatFielddataParams extends CatCommonParams { - bytes?: CatBytes; - fields?: NameList; - } - - export interface CatHealthParams extends CatCommonParams { - ts?: boolean; - } - - export interface CatHelpParams extends GenericParams { - help?: boolean; - } - - export interface CatIndicesParams extends CatCommonParams { - bytes?: CatBytes; - health?: "green" | "yellow" | "red"; - pri?: boolean; - index?: NameList; - } - - export interface CatRecoveryParams extends GenericParams { - format: string; - bytes?: CatBytes; - masterTimeout?: TimeSpan; - h?: NameList; - help?: boolean; - v?: boolean; - } - - export interface CatSegmentsParams extends GenericParams { - format: string; - h?: NameList; - help?: boolean; - v?: boolean; - index?: NameList; - } - - export interface CatShardsParams extends CatCommonParams { - index?: NameList; - } - - export interface CatSnapshotsParams extends GenericParams { - format: string; - ignoreUnavailable?: boolean; - masterTimeout?: TimeSpan; - h?: NameList; - help?: boolean; - v?: boolean; - repository?: NameList; - } - - export interface CatTasksParams extends GenericParams { - format: string; - nodeId?: NameList; - actions?: NameList; - detailed?: boolean; - parentNode?: string; - parentTask?: number; - h?: NameList; - help?: boolean; - v?: boolean; - } - - export interface CatThreadPoolParams extends CatCommonParams { - size?: "" | "k" | "m" | "g" | "t" | "p"; - threadPoolPatterns?: NameList; - } - - export interface Cluster { - allocationExplain(params: ClusterAllocationExplainParams, callback: (error: any, response: any) => void): void; - allocationExplain(params: ClusterAllocationExplainParams): Promise; - getSettings(params: ClusterGetSettingsParams, callback: (error: any, response: any) => void): void; - getSettings(params: ClusterGetSettingsParams): Promise; - health(params: ClusterHealthParams, callback: (error: any, response: any) => void): void; - health(params: ClusterHealthParams): Promise; - pendingTasks(params: ClusterPendingTasksParams, callback: (error: any, response: any) => void): void; - pendingTasks(params: ClusterPendingTasksParams): Promise; - putSettings(params: ClusterPutSettingsParams, callback: (error: any, response: any) => void): void; - putSettings(params: ClusterPutSettingsParams): Promise; - reroute(params: ClusterRerouteParams, callback: (error: any, response: any) => void): void; - reroute(params: ClusterRerouteParams): Promise; - state(params: ClusterStateParams, callback: (error: any, response: any) => void): void; - state(params: ClusterStateParams): Promise; - stats(params: ClusterStatsParams, callback: (error: any, response: any) => void): void; - stats(params: ClusterStatsParams): Promise; - } - - export interface ClusterAllocationExplainParams extends GenericParams { - includeYesDecisions?: boolean; - includeDiskInfo?: boolean; - } - - export interface ClusterGetSettingsParams extends GenericParams { - flatSettings?: boolean; - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - includeDefaults?: boolean; - } - - export interface ClusterHealthParams extends GenericParams { - level?: "cluster" | "indices" | "shards"; - local?: boolean; - masterTimeout?: TimeSpan; - waitForActiveShards?: string; - waitForNodes?: string; - waitForEvents?: "immediate" | "urgent" | "high" | "normal" | "low" | "languid"; - waitForRelocatingShards?: boolean; - waitForStatus?: "green" | "yellow" | "red"; - index?: NameList; - } - - export interface ClusterPendingTasksParams extends GenericParams { - local?: boolean; - masterTimeout?: TimeSpan; - } - - export interface ClusterPutSettingsParams extends GenericParams { - flatSettings?: boolean; - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - } - - export interface ClusterRerouteParams extends GenericParams { - dryRun?: boolean; - explain?: boolean; - retryFailed?: boolean; - metric?: NameList; - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - } - - export interface ClusterStateParams extends GenericParams { - local?: boolean; - masterTimeout?: TimeSpan; - flatSettings?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index?: NameList; - metric?: NameList; - } - - export interface ClusterStatsParams extends GenericParams { - flatSettings?: boolean; - human?: boolean; - timeout?: TimeSpan; - nodeId?: NameList; - } - - export class Indices { - analyze(params: IndicesAnalyzeParams, callback: (error: any, response: any, status: any) => void): void; - analyze(params: IndicesAnalyzeParams): Promise; - clearCache(params: IndicesClearCacheParams, callback: (error: any, response: any, status: any) => void): void; - clearCache(params: IndicesClearCacheParams): Promise; - close(params: IndicesCloseParams, callback: (error: any, response: any, status: any) => void): void; - close(params: IndicesCloseParams): Promise; - create(params: IndicesCreateParams, callback: (error: any, response: any, status: any) => void): void; - create(params: IndicesCreateParams): Promise; - delete(params: IndicesDeleteParams, callback: (error: any, response: any, status: any) => void): void; - delete(params: IndicesDeleteParams): Promise; - deleteAlias(params: IndicesDeleteAliasParams, callback: (error: any, response: any, status: any) => void): void; - deleteAlias(params: IndicesDeleteAliasParams): Promise; - deleteTemplate(params: IndicesDeleteTemplateParams, callback: (error: any, response: any, status: any) => void): void; - deleteTemplate(params: IndicesDeleteTemplateParams): Promise; - exists(params: IndicesExistsParams, callback: (error: any, response: any, status: any) => void): void; - exists(params: IndicesExistsParams): Promise; - existsAlias(params: IndicesExistsAliasParams, callback: (error: any, response: any, status: any) => void): void; - existsAlias(params: IndicesExistsAliasParams): Promise; - existsTemplate(params: IndicesExistsTemplateParams, callback: (error: any, response: any, status: any) => void): void; - existsTemplate(params: IndicesExistsTemplateParams): Promise; - existsType(params: IndicesExistsTypeParams, callback: (error: any, response: any, status: any) => void): void; - existsType(params: IndicesExistsTypeParams): Promise; - flush(params: IndicesFlushParams, callback: (error: any, response: any, status: any) => void): void; - flush(params: IndicesFlushParams): Promise; - flushSynced(params: IndicesFlushSyncedParams, callback: (error: any, response: any, status: any) => void): void; - flushSynced(params: IndicesFlushSyncedParams): Promise; - forcemerge(params: IndicesForcemergeParams, callback: (error: any, response: any, status: any) => void): void; - forcemerge(params: IndicesForcemergeParams): Promise; - get(params: IndicesGetParams, callback: (error: any, response: any, status: any) => void): void; - get(params: IndicesGetParams): Promise; - getAlias(params: IndicesGetAliasParams, callback: (error: any, response: any, status: any) => void): void; - getAlias(params: IndicesGetAliasParams): Promise; - getFieldMapping(params: IndicesGetFieldMappingParams, callback: (error: any, response: any, status: any) => void): void; - getFieldMapping(params: IndicesGetFieldMappingParams): Promise; - getMapping(params: IndicesGetMappingParams, callback: (error: any, response: any, status: any) => void): void; - getMapping(params: IndicesGetMappingParams): Promise; - getSettings(params: IndicesGetSettingsParams, callback: (error: any, response: any, status: any) => void): void; - getSettings(params: IndicesGetSettingsParams): Promise; - getTemplate(params: IndicesGetTemplateParams, callback: (error: any, response: any, status: any) => void): void; - getTemplate(params: IndicesGetTemplateParams): Promise; - getUpgrade(params: IndicesGetUpgradeParams, callback: (error: any, response: any, status: any) => void): void; - getUpgrade(params: IndicesGetUpgradeParams): Promise; - open(params: IndicesOpenParams, callback: (error: any, response: any, status: any) => void): void; - open(params: IndicesOpenParams): Promise; - putAlias(params: IndicesPutAliasParams, callback: (error: any, response: any, status: any) => void): void; - putAlias(params: IndicesPutAliasParams): Promise; - putMapping(params: IndicesPutMappingParams, callback: (error: any, response: any, status: any) => void): void; - putMapping(params: IndicesPutMappingParams): Promise; - putSettings(params: IndicesPutSettingsParams, callback: (error: any, response: any, status: any) => void): void; - putSettings(params: IndicesPutSettingsParams): Promise; - putTemplate(params: IndicesPutTemplateParams, callback: (error: any, response: any) => void): void; - putTemplate(params: IndicesPutTemplateParams): Promise; - recovery(params: IndicesRecoveryParams, callback: (error: any, response: any) => void): void; - recovery(params: IndicesRecoveryParams): Promise; - refresh(params: IndicesRefreshParams, callback: (error: any, response: any) => void): void; - refresh(params: IndicesRefreshParams): Promise; - rollover(params: IndicesRolloverParams, callback: (error: any, response: IndicesRolloverResponse) => void): void; - rollover(params: IndicesRolloverParams): Promise; - segments(params: IndicesSegmentsParams, callback: (error: any, response: any) => void): void; - segments(params: IndicesSegmentsParams): Promise; - shardStores(params: IndicesShardStoresParams, callback: (error: any, response: any) => void): void; - shardStores(params: IndicesShardStoresParams): Promise; - shrink(params: IndicesShrinkParams, callback: (error: any, response: any) => void): void; - shrink(params: IndicesShrinkParams): Promise; - stats(params: IndicesStatsParams, callback: (error: any, response: any) => void): void; - stats(params: IndicesStatsParams): Promise; - updateAliases(params: IndicesUpdateAliasesParams, callback: (error: any, response: any) => void): void; - updateAliases(params: IndicesUpdateAliasesParams): Promise; - upgrade(params: IndicesUpgradeParams, callback: (error: any, response: any) => void): void; - upgrade(params: IndicesUpgradeParams): Promise; - validateQuery(params: IndicesValidateQueryParams, callback: (error: any, response: any) => void): void; - validateQuery(params: IndicesValidateQueryParams): Promise; - } - - export interface IndicesAnalyzeParams extends GenericParams { - analyzer?: string; - charFilter?: NameList; - field?: string; - filter?: NameList; - index?: string; - perferLocal?: boolean; - text?: NameList; - tokenizer?: string; - explain?: boolean; - attributes?: NameList; - format?: ""; - } - - export interface IndicesClearCacheParams extends GenericParams { - fieldData?: boolean; - fielddata?: boolean; // yes the docs really have both - fields?: NameList; - query?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index?: NameList; - recycler?: boolean; - request?: boolean; - } - - export interface IndicesCloseParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index: NameList; - } - - export interface IndicesCreateParams extends GenericParams { - waitForActiveShards?: string; - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - updateAllTypes?: boolean; - index: string; - } - - export interface IndicesDeleteParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - index: NameList; - } - - export interface IndicesDeleteAliasParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - index: NameList; - name: NameList; - } - - export interface IndicesDeleteTemplateParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - name: string; - } - - export interface IndicesExistsParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - local?: boolean; - index: NameList; - } - - export interface IndicesExistsAliasParams extends IndicesExistsParams { - name: NameList; - } - - export interface IndicesExistsTemplateParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - name: NameList; - } - - export interface IndicesExistsTypeParams extends IndicesExistsParams { - type: NameList; - } - - export interface IndicesFlushParams extends GenericParams { - force?: boolean; - waitIfOngoing?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index: NameList; - } - - export interface IndicesFlushSyncedParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index: NameList; - } - - export interface IndicesForcemergeParams extends GenericParams { - flush?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - maxNumSegments?: number; - onlyExpungeDeletes?: boolean; - operationThreading?: any; // even the docs don't know what this does - waitForMerge?: boolean; - index: NameList; - } - - export interface IndicesGetParams extends GenericParams { - local?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - flatSettings?: boolean; - human?: boolean; - includeDefaults?: boolean; - index?: NameList; - feature?: NameList; - } - - export interface IndicesGetAliasParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - local?: boolean; - index?: NameList; - name?: NameList; - } - - export interface IndicesGetFieldMappingParams extends GenericParams { - includeDefaults?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - local?: boolean; - index?: NameList; - type?: NameList; - fields?: NameList; - } - - export interface IndicesGetMappingParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - local?: boolean; - index?: NameList; - type?: NameList; - } - - export interface IndicesGetSettingsParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - flatSettings?: boolean; - local?: boolean; - human?: boolean; - includeDefaults?: boolean; - index?: NameList; - name?: NameList; - } - - export interface IndicesGetTemplateParams extends GenericParams { - flatSettings?: boolean; - masterTimeout?: TimeSpan; - local?: boolean; - name?: NameList; - } - - export interface IndicesGetUpgradeParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - human?: boolean; - index?: NameList; - } - - export interface IndicesOpenParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index?: NameList; - } - - export interface IndicesPutAliasParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - index?: NameList; - name: NameList; - } - - export interface IndicesPutMappingParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - updateAllTypes?: boolean; - index: NameList; - type: string; - body: any; - } - - export interface IndicesPutSettingsParams extends GenericParams { - masterTimeout?: TimeSpan; - preserveExisting?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - flatSettings?: boolean; - index: NameList; - body: any; - } - - export interface IndicesPutTemplateParams extends GenericParams { - order?: number; - create?: boolean; - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - flatSettings?: boolean; - name: string; - body: any; - } - - export interface IndicesRecoveryParams extends GenericParams { - detailed?: boolean; - activeOnly?: boolean; - human?: boolean; - index: NameList; - } - - export interface IndicesRefreshParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - force?: boolean; - operationThreading?: any; // even the docs don't know what this does - index: NameList; - } - - export interface IndicesRolloverParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - waitForActiveShards?: number | string; - alias?: string; - newIndex?: string; - } - - export interface IndicesRolloverResponse { - acknowledged: boolean; - shards_acknowledged: boolean; - old_index: string; - new_index: string; - rolled_over: boolean; - dry_run: boolean; - conditions: { [condition: string]: boolean }; - } - - export interface IndicesSegmentsParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - human?: boolean; - operationThreading?: any; // even the docs don't know what this does - verbose?: boolean; - index: NameList; - } - - export interface IndicesShardStoresParams extends GenericParams { - status?: NameList; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - operationThreading?: any; // even the docs don't know what this does - index: NameList; - } - - export interface IndicesShrinkParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - waitForActiveShards?: string | number; - index: string; - target: string; - } - - export interface IndicesStatsParams extends GenericParams { - completionFields?: NameList; - fielddataFields?: NameList; - fields?: NameList; - groups?: NameList; - human?: boolean; - level?: "cluster" | "indices" | "shards"; - types?: NameList; - index: NameList; - metric?: NameList; - } - - export interface IndicesUpdateAliasesParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - body: { - actions: IndicesUpdateAliasesParamsAction[]; - }; - } - - export interface IndicesUpdateAliasesParamsAction { - add?: { - index?: string; - indices?: string[]; - alias: string; - }; - remove?: { - index?: string; - indices?: string[]; - alias: string; - }; - remove_index?: { + dest: { index: string; + version_type?: string; + op_type?: string; + routing?: string; + pipeline?: string; }; - } - - export interface IndicesUpgradeParams extends GenericParams { - expandWildcards?: ExpandWildcards; - ignoreUnavailable?: boolean; - waitForCompletion?: boolean; - onlyAncientSegments?: boolean; - index: NameList; - } - - export interface IndicesValidateQueryParams extends GenericParams { - explain?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - operationThreading?: any; // even the docs don't know what this does - q?: string; - analyzer?: string; - analyzeWildcard?: boolean; - defaultOperator?: DefaultOperator; - df?: string; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - rewrite?: boolean; - index: NameList; - type?: NameList; - } - - export class Ingest { - deletePipeline(params: IngestDeletePipelineParams, callback: (error: any, response: any, status: any) => void): void; - deletePipeline(params: IngestDeletePipelineParams): Promise; - getPipeline(params: IngestGetPipelineParams, callback: (error: any, response: any, status: any) => void): void; - getPipeline(params: IngestGetPipelineParams): Promise; - putPipeline(params: IngestPutPipelineParams, callback: (error: any, response: any, status: any) => void): void; - putPipeline(params: IngestPutPipelineParams): Promise; - simulate(params: IngestSimulateParams, callback: (error: any, response: any, status: any) => void): void; - simulate(params: IngestSimulateParams): Promise; - } - - export interface IngestDeletePipelineParams extends GenericParams { - masterTimeout?: number; - timeout?: number; - id: string; - } - - export interface IngestGetPipelineParams extends GenericParams { - masterTimeout?: number; - id: string; - } - - export interface IngestPutPipelineParams extends GenericParams { - masterTimeout?: number; - timeout?: number; - id: string; - body: any; - } - - export interface IngestSimulateParams extends GenericParams { - verbose?: boolean; - id: string; - } - - export class Nodes { - hotThreads(params: NodesHotThreadsParams, callback: (error: any, response: any, status: any) => void): void; - hotThreads(params: NodesHotThreadsParams): Promise; - info(params: NodesInfoParams, callback: (error: any, response: any, status: any) => void): void; - info(params: NodesInfoParams): Promise; - stats(params: NodesStatsParams, callback: (error: any, response: any, status: any) => void): void; - stats(params: NodesStatsParams): Promise; - } - - export interface NodesHotThreadsParams extends GenericParams { - interval?: TimeSpan; - snapshots?: number; - threads?: number; - ignoreIdleThreads?: boolean; - type?: "cpu" | "wait" | "blocked"; - timeout?: TimeSpan; - nodeId: NameList; - } - - export interface NodesInfoParams extends GenericParams { - flatSettings?: boolean; - human?: boolean; - timeout?: TimeSpan; - nodeId: NameList; - metric?: NameList; - } - - export interface NodesStatsParams extends GenericParams { - completionFields?: NameList; - fielddataFields?: NameList; - fields?: NameList; - groups?: boolean; - human?: boolean; - level?: "indices" | "node" | "shards"; - types?: NameList; - timeout?: TimeSpan; - metric?: NameList; - indexMetric?: NameList; - nodeId?: NameList; - } - - export class Snapshot { - create(params: SnapshotCreateParams, callback: (error: any, response: any, status: any) => void): void; - create(params: SnapshotCreateParams): Promise; - createRepository(params: SnapshotCreateRepositoryParams, callback: (error: any, response: any, status: any) => void): void; - createRepository(params: SnapshotCreateRepositoryParams): Promise; - delete(params: SnapshotDeleteParams, callback: (error: any, response: any, status: any) => void): void; - delete(params: SnapshotDeleteParams): Promise; - deleteRepository(params: SnapshotDeleteRepositoryParams, callback: (error: any, response: any, status: any) => void): void; - deleteRepository(params: SnapshotDeleteRepositoryParams): Promise; - get(params: SnapshotGetParams, callback: (error: any, response: any, status: any) => void): void; - get(params: SnapshotGetParams): Promise; - getRepository(params: SnapshotGetRepositoryParams, callback: (error: any, response: any, status: any) => void): void; - getRepository(params: SnapshotGetRepositoryParams): Promise; - restore(params: SnapshotRestoreParams, callback: (error: any, response: any, status: any) => void): void; - restore(params: SnapshotRestoreParams): Promise; - status(params: SnapshotStatusParams, callback: (error: any, response: any, status: any) => void): void; - status(params: SnapshotStatusParams): Promise; - verifyRepository(params: SnapshotVerifyRepositoryParams, callback: (error: any, response: any, status: any) => void): void; - verifyRepository(params: SnapshotVerifyRepositoryParams): Promise; - } - - export interface SnapshotCreateParams extends GenericParams { - masterTimeout?: TimeSpan; - waitForCompletion?: boolean; - repository: string; - snapshot: string; - } - - export interface SnapshotCreateRepositoryParams extends GenericParams { - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - verify?: boolean; - repository: string; - } - - export interface SnapshotDeleteParams extends GenericParams { - masterTimeout?: TimeSpan; - repository: string; - snapshot: string; - } - - export interface SnapshotDeleteRepositoryParams extends GenericParams { - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - repository: string; - } - - export interface SnapshotGetParams extends GenericParams { - masterTimeout?: TimeSpan; - ignoreUnavailable?: boolean; - repository: string; - snapshot: NameList; - } - - export interface SnapshotGetRepositoryParams extends GenericParams { - masterTimeout?: TimeSpan; - local?: boolean; - repository: NameList; - } - - export interface SnapshotRestoreParams extends GenericParams { - masterTimeout?: TimeSpan; - waitForCompletion?: boolean; - repository: string; - snapshot: string; - } - - export interface SnapshotStatusParams extends GenericParams { - masterTimeout?: TimeSpan; - ignoreUnavailable?: boolean; - repository: string; - snapshot: NameList; - } - - export interface SnapshotVerifyRepositoryParams extends GenericParams { - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - repository: string; - } - - export class Tasks { - cancel(params: TasksCancelParams, callback: (error: any, response: any, status: any) => void): void; - cancel(params: TasksCancelParams): Promise; - get(params: TasksGetParams, callback: (error: any, response: any, status: any) => void): void; - get(params: TasksGetParams): Promise; - list(params: TasksListParams, callback: (error: any, response: any, status: any) => void): void; - list(params: TasksListParams): Promise; - } - - export interface TasksCancelParams extends GenericParams { - nodeId?: NameList; - actions?: NameList; - parentNode?: string; - parentTask?: string; - taskId?: string; - } - - export interface TasksGetParams extends GenericParams { - waitForCompletion?: boolean; - taskId?: string; - } - - export interface TasksListParams extends GenericParams { - nodeId?: NameList; - actions?: NameList; - detailed?: boolean; - parentNode?: string; - parentTask?: string; - waitForCompletion?: boolean; - groupBy?: "nodes" | "parents"; - } + script?: { + inline: string; + lang: string; + } + }; } -declare module "elasticsearch" { - export = Elasticsearch; +export interface ReindexResponse { + took: number; + updated: number; + created: number; + batches: number; + version_conflicts: number; + retries: { + bulk: number; + search: number; + }; + throttled_millis: number; + failures: any[]; +} + +export interface ReindexRethrottleParams extends GenericParams { + requestsPerSecond: number; + taskId: string; +} + +export interface RenderSearchTemplateParams extends GenericParams { + id: string; +} + +export interface ScrollParams extends GenericParams { + scroll: TimeSpan; + scrollId: string; +} + +export interface SearchParams extends GenericParams { + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + explain?: boolean; + storedFields?: NameList; + docvalueFields?: NameList; + fielddataFields?: NameList; + from?: number; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + preference?: string; + q?: string; + routing?: NameList; + scroll?: TimeSpan; + searchType?: "query_then_fetch" | "dfs_query_then_fetch"; + size?: number; + sort?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + terminateAfter?: number; + stats?: NameList; + suggestField?: string; + suggestMode?: "missing" | "popular" | "always"; + suggestSize?: number; + suggestText?: string; + timeout?: TimeSpan; + trackScores?: boolean; + version?: boolean; + requestCache?: boolean; + index?: NameList; + type?: NameList; +} + +export interface SearchResponse { + took: number; + timed_out: boolean; + _scroll_id?: string; + _shards: ShardsResponse; + hits: { + total: number; + max_score: number; + hits: Array<{ + _index: string; + _type: string; + _id: string; + _score: number; + _source: T; + _version?: number; + _explanation?: Explanation; + fields?: any; + highlight?: any; + inner_hits?: any; + }>; + }; + aggregations?: any; +} + +export interface SearchShardsParams extends GenericParams { + preference?: string; + routing?: string; + local?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index: NameList; + type: NameList; +} + +export interface SearchShardsResponse { + nodes: any; + shards: SearchShardsResponseShard[][]; +} + +export interface SearchShardsResponseShard { + index: string; + node: string; + primary: boolean; + share: number; + state: string; + allocation_id: { + id: string; + }; + relocating_node: any; +} + +export interface SearchTemplateParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + preference?: string; + routing?: NameList; + scroll?: TimeSpan; + searchType?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; + index: NameList; + type: NameList; +} + +export interface SuggestParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + preference?: string; + routing?: string; + index: NameList; +} + +export interface TermvectorsParams extends GenericParams { + termStatistics?: boolean; + fieldStatistics?: boolean; + fields?: NameList; + offsets?: boolean; + positions?: boolean; + payloads?: boolean; + preference?: string; + routing?: string; + parent?: string; + realtime?: boolean; + version?: number; + versionType?: VersionType; + index: string; + type: string; + id?: string; +} + +export interface UpdateDocumentParams extends GenericParams { + waitForActiveShards?: string; + fields?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + lang?: string; + parent?: string; + refresh?: Refresh; + retryOnConflict?: number; + routing?: string; + timeout?: TimeSpan; + timestamp?: Date | number; + ttl?: TimeSpan; + version?: number; + versionType?: "internal" | "force"; + id: string; + index: string; + type: string; +} + +export interface UpdateDocumentByQueryParams extends GenericParams { + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + explain?: boolean; + storedFields?: NameList; + docvalueFields?: NameList; + fielddataFields?: NameList; + from?: number; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + conflicts?: Conflicts; + expandWildcards?: ExpandWildcards; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + pipeline?: string; + preference?: string; + q?: string; + routing?: NameList; + scroll?: TimeSpan; + searchType?: "query_then_fetch" | "dfs_query_then_fetch"; + searchTimeout?: TimeSpan; + size?: number; + sort?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + terminateAfter?: number; + stats?: NameList; + suggestField?: string; + suggestMode?: "missing" | "popular" | "always"; + suggestSize?: number; + suggestText?: string; + timeout?: TimeSpan; + trackScores?: boolean; + version?: boolean; + versionType?: boolean; + requestCache?: boolean; + refresh?: boolean; + waitForActiveShards?: string; + scrollSize?: number; + waitForCompletion?: boolean; + requestsPerSecond?: number; + index: NameList; + type: NameList; +} + +export interface Cat { + aliases(params: CatAliasesParams, callback: (error: any, response: any) => void): void; + aliases(params: CatAliasesParams): Promise; + allocation(params: CatAllocationParams, callback: (error: any, response: any) => void): void; + allocation(params: CatAllocationParams): Promise; + count(params: CatCountParams, callback: (error: any, response: any) => void): void; + count(params: CatAllocationParams): Promise; + fielddata(params: CatFielddataParams, callback: (error: any, response: any) => void): void; + fielddata(params: CatFielddataParams): Promise; + health(params: CatHealthParams, callback: (error: any, response: any) => void): void; + health(params: CatHealthParams): Promise; + help(params: CatHelpParams, callback: (error: any, response: any) => void): void; + help(params: CatHelpParams): Promise; + indices(params: CatIndicesParams, callback: (error: any, response: any) => void): void; + indices(params: CatIndicesParams): Promise; + master(params: CatCommonParams, callback: (error: any, response: any) => void): void; + master(params: CatCommonParams): Promise; + nodeattrs(params: CatCommonParams, callback: (error: any, response: any) => void): void; + nodeattrs(params: CatCommonParams): Promise; + nodes(params: CatCommonParams, callback: (error: any, response: any) => void): void; + nodes(params: CatCommonParams): Promise; + pendingTasks(params: CatCommonParams, callback: (error: any, response: any) => void): void; + pendingTasks(params: CatCommonParams): Promise; + plugins(params: CatCommonParams, callback: (error: any, response: any) => void): void; + plugins(params: CatCommonParams): Promise; + recovery(params: CatRecoveryParams, callback: (error: any, response: any) => void): void; + recovery(params: CatRecoveryParams): Promise; + repositories(params: CatCommonParams, callback: (error: any, response: any) => void): void; + repositories(params: CatCommonParams): Promise; + segments(params: CatSegmentsParams, callback: (error: any, response: any) => void): void; + segments(params: CatSegmentsParams): Promise; + shards(params: CatShardsParams, callback: (error: any, response: any) => void): void; + shards(params: CatShardsParams): Promise; + snapshots(params: CatSnapshotsParams, callback: (error: any, response: any) => void): void; + snapshots(params: CatSnapshotsParams): Promise; + tasks(params: CatTasksParams, callback: (error: any, response: any) => void): void; + tasks(params: CatTasksParams): Promise; + threadPool(params: CatThreadPoolParams, callback: (error: any, response: any) => void): void; + threadPool(params: CatThreadPoolParams): Promise; +} + +export type CatBytes = "b" | "k" | "kb" | "m" | "mb" | "g" | "gb" | "t" | "tb" | "p" | "pb"; + +export interface CatCommonParams extends GenericParams { + format: string; + local?: boolean; + masterTimeout?: TimeSpan; + h?: NameList; + help?: boolean; + v?: boolean; +} + +export interface CatAliasesParams extends CatCommonParams { + name?: NameList; +} + +export interface CatAllocationParams extends CatCommonParams { + bytes?: CatBytes; + nodeId?: NameList; +} + +export interface CatCountParams extends CatCommonParams { + index?: NameList; +} + +export interface CatFielddataParams extends CatCommonParams { + bytes?: CatBytes; + fields?: NameList; +} + +export interface CatHealthParams extends CatCommonParams { + ts?: boolean; +} + +export interface CatHelpParams extends GenericParams { + help?: boolean; +} + +export interface CatIndicesParams extends CatCommonParams { + bytes?: CatBytes; + health?: "green" | "yellow" | "red"; + pri?: boolean; + index?: NameList; +} + +export interface CatRecoveryParams extends GenericParams { + format: string; + bytes?: CatBytes; + masterTimeout?: TimeSpan; + h?: NameList; + help?: boolean; + v?: boolean; +} + +export interface CatSegmentsParams extends GenericParams { + format: string; + h?: NameList; + help?: boolean; + v?: boolean; + index?: NameList; +} + +export interface CatShardsParams extends CatCommonParams { + index?: NameList; +} + +export interface CatSnapshotsParams extends GenericParams { + format: string; + ignoreUnavailable?: boolean; + masterTimeout?: TimeSpan; + h?: NameList; + help?: boolean; + v?: boolean; + repository?: NameList; +} + +export interface CatTasksParams extends GenericParams { + format: string; + nodeId?: NameList; + actions?: NameList; + detailed?: boolean; + parentNode?: string; + parentTask?: number; + h?: NameList; + help?: boolean; + v?: boolean; +} + +export interface CatThreadPoolParams extends CatCommonParams { + size?: "" | "k" | "m" | "g" | "t" | "p"; + threadPoolPatterns?: NameList; +} + +export interface Cluster { + allocationExplain(params: ClusterAllocationExplainParams, callback: (error: any, response: any) => void): void; + allocationExplain(params: ClusterAllocationExplainParams): Promise; + getSettings(params: ClusterGetSettingsParams, callback: (error: any, response: any) => void): void; + getSettings(params: ClusterGetSettingsParams): Promise; + health(params: ClusterHealthParams, callback: (error: any, response: any) => void): void; + health(params: ClusterHealthParams): Promise; + pendingTasks(params: ClusterPendingTasksParams, callback: (error: any, response: any) => void): void; + pendingTasks(params: ClusterPendingTasksParams): Promise; + putSettings(params: ClusterPutSettingsParams, callback: (error: any, response: any) => void): void; + putSettings(params: ClusterPutSettingsParams): Promise; + reroute(params: ClusterRerouteParams, callback: (error: any, response: any) => void): void; + reroute(params: ClusterRerouteParams): Promise; + state(params: ClusterStateParams, callback: (error: any, response: any) => void): void; + state(params: ClusterStateParams): Promise; + stats(params: ClusterStatsParams, callback: (error: any, response: any) => void): void; + stats(params: ClusterStatsParams): Promise; +} + +export interface ClusterAllocationExplainParams extends GenericParams { + includeYesDecisions?: boolean; + includeDiskInfo?: boolean; +} + +export interface ClusterGetSettingsParams extends GenericParams { + flatSettings?: boolean; + masterTimeout?: TimeSpan; + timeout?: TimeSpan; + includeDefaults?: boolean; +} + +export interface ClusterHealthParams extends GenericParams { + level?: "cluster" | "indices" | "shards"; + local?: boolean; + masterTimeout?: TimeSpan; + waitForActiveShards?: string; + waitForNodes?: string; + waitForEvents?: "immediate" | "urgent" | "high" | "normal" | "low" | "languid"; + waitForRelocatingShards?: boolean; + waitForStatus?: "green" | "yellow" | "red"; + index?: NameList; +} + +export interface ClusterPendingTasksParams extends GenericParams { + local?: boolean; + masterTimeout?: TimeSpan; +} + +export interface ClusterPutSettingsParams extends GenericParams { + flatSettings?: boolean; + masterTimeout?: TimeSpan; + timeout?: TimeSpan; +} + +export interface ClusterRerouteParams extends GenericParams { + dryRun?: boolean; + explain?: boolean; + retryFailed?: boolean; + metric?: NameList; + masterTimeout?: TimeSpan; + timeout?: TimeSpan; +} + +export interface ClusterStateParams extends GenericParams { + local?: boolean; + masterTimeout?: TimeSpan; + flatSettings?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index?: NameList; + metric?: NameList; +} + +export interface ClusterStatsParams extends GenericParams { + flatSettings?: boolean; + human?: boolean; + timeout?: TimeSpan; + nodeId?: NameList; +} + +export class Indices { + analyze(params: IndicesAnalyzeParams, callback: (error: any, response: any, status: any) => void): void; + analyze(params: IndicesAnalyzeParams): Promise; + clearCache(params: IndicesClearCacheParams, callback: (error: any, response: any, status: any) => void): void; + clearCache(params: IndicesClearCacheParams): Promise; + close(params: IndicesCloseParams, callback: (error: any, response: any, status: any) => void): void; + close(params: IndicesCloseParams): Promise; + create(params: IndicesCreateParams, callback: (error: any, response: any, status: any) => void): void; + create(params: IndicesCreateParams): Promise; + delete(params: IndicesDeleteParams, callback: (error: any, response: any, status: any) => void): void; + delete(params: IndicesDeleteParams): Promise; + deleteAlias(params: IndicesDeleteAliasParams, callback: (error: any, response: any, status: any) => void): void; + deleteAlias(params: IndicesDeleteAliasParams): Promise; + deleteTemplate(params: IndicesDeleteTemplateParams, callback: (error: any, response: any, status: any) => void): void; + deleteTemplate(params: IndicesDeleteTemplateParams): Promise; + exists(params: IndicesExistsParams, callback: (error: any, response: any, status: any) => void): void; + exists(params: IndicesExistsParams): Promise; + existsAlias(params: IndicesExistsAliasParams, callback: (error: any, response: any, status: any) => void): void; + existsAlias(params: IndicesExistsAliasParams): Promise; + existsTemplate(params: IndicesExistsTemplateParams, callback: (error: any, response: any, status: any) => void): void; + existsTemplate(params: IndicesExistsTemplateParams): Promise; + existsType(params: IndicesExistsTypeParams, callback: (error: any, response: any, status: any) => void): void; + existsType(params: IndicesExistsTypeParams): Promise; + flush(params: IndicesFlushParams, callback: (error: any, response: any, status: any) => void): void; + flush(params: IndicesFlushParams): Promise; + flushSynced(params: IndicesFlushSyncedParams, callback: (error: any, response: any, status: any) => void): void; + flushSynced(params: IndicesFlushSyncedParams): Promise; + forcemerge(params: IndicesForcemergeParams, callback: (error: any, response: any, status: any) => void): void; + forcemerge(params: IndicesForcemergeParams): Promise; + get(params: IndicesGetParams, callback: (error: any, response: any, status: any) => void): void; + get(params: IndicesGetParams): Promise; + getAlias(params: IndicesGetAliasParams, callback: (error: any, response: any, status: any) => void): void; + getAlias(params: IndicesGetAliasParams): Promise; + getFieldMapping(params: IndicesGetFieldMappingParams, callback: (error: any, response: any, status: any) => void): void; + getFieldMapping(params: IndicesGetFieldMappingParams): Promise; + getMapping(params: IndicesGetMappingParams, callback: (error: any, response: any, status: any) => void): void; + getMapping(params: IndicesGetMappingParams): Promise; + getSettings(params: IndicesGetSettingsParams, callback: (error: any, response: any, status: any) => void): void; + getSettings(params: IndicesGetSettingsParams): Promise; + getTemplate(params: IndicesGetTemplateParams, callback: (error: any, response: any, status: any) => void): void; + getTemplate(params: IndicesGetTemplateParams): Promise; + getUpgrade(params: IndicesGetUpgradeParams, callback: (error: any, response: any, status: any) => void): void; + getUpgrade(params: IndicesGetUpgradeParams): Promise; + open(params: IndicesOpenParams, callback: (error: any, response: any, status: any) => void): void; + open(params: IndicesOpenParams): Promise; + putAlias(params: IndicesPutAliasParams, callback: (error: any, response: any, status: any) => void): void; + putAlias(params: IndicesPutAliasParams): Promise; + putMapping(params: IndicesPutMappingParams, callback: (error: any, response: any, status: any) => void): void; + putMapping(params: IndicesPutMappingParams): Promise; + putSettings(params: IndicesPutSettingsParams, callback: (error: any, response: any, status: any) => void): void; + putSettings(params: IndicesPutSettingsParams): Promise; + putTemplate(params: IndicesPutTemplateParams, callback: (error: any, response: any) => void): void; + putTemplate(params: IndicesPutTemplateParams): Promise; + recovery(params: IndicesRecoveryParams, callback: (error: any, response: any) => void): void; + recovery(params: IndicesRecoveryParams): Promise; + refresh(params: IndicesRefreshParams, callback: (error: any, response: any) => void): void; + refresh(params: IndicesRefreshParams): Promise; + rollover(params: IndicesRolloverParams, callback: (error: any, response: IndicesRolloverResponse) => void): void; + rollover(params: IndicesRolloverParams): Promise; + segments(params: IndicesSegmentsParams, callback: (error: any, response: any) => void): void; + segments(params: IndicesSegmentsParams): Promise; + shardStores(params: IndicesShardStoresParams, callback: (error: any, response: any) => void): void; + shardStores(params: IndicesShardStoresParams): Promise; + shrink(params: IndicesShrinkParams, callback: (error: any, response: any) => void): void; + shrink(params: IndicesShrinkParams): Promise; + stats(params: IndicesStatsParams, callback: (error: any, response: any) => void): void; + stats(params: IndicesStatsParams): Promise; + updateAliases(params: IndicesUpdateAliasesParams, callback: (error: any, response: any) => void): void; + updateAliases(params: IndicesUpdateAliasesParams): Promise; + upgrade(params: IndicesUpgradeParams, callback: (error: any, response: any) => void): void; + upgrade(params: IndicesUpgradeParams): Promise; + validateQuery(params: IndicesValidateQueryParams, callback: (error: any, response: any) => void): void; + validateQuery(params: IndicesValidateQueryParams): Promise; +} + +export interface IndicesAnalyzeParams extends GenericParams { + analyzer?: string; + charFilter?: NameList; + field?: string; + filter?: NameList; + index?: string; + perferLocal?: boolean; + text?: NameList; + tokenizer?: string; + explain?: boolean; + attributes?: NameList; + format?: ""; +} + +export interface IndicesClearCacheParams extends GenericParams { + fieldData?: boolean; + fielddata?: boolean; // yes the docs really have both + fields?: NameList; + query?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index?: NameList; + recycler?: boolean; + request?: boolean; +} + +export interface IndicesCloseParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index: NameList; +} + +export interface IndicesCreateParams extends GenericParams { + waitForActiveShards?: string; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + updateAllTypes?: boolean; + index: string; +} + +export interface IndicesDeleteParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + index: NameList; +} + +export interface IndicesDeleteAliasParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + index: NameList; + name: NameList; +} + +export interface IndicesDeleteTemplateParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + name: string; +} + +export interface IndicesExistsParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + local?: boolean; + index: NameList; +} + +export interface IndicesExistsAliasParams extends IndicesExistsParams { + name: NameList; +} + +export interface IndicesExistsTemplateParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + name: NameList; +} + +export interface IndicesExistsTypeParams extends IndicesExistsParams { + type: NameList; +} + +export interface IndicesFlushParams extends GenericParams { + force?: boolean; + waitIfOngoing?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index: NameList; +} + +export interface IndicesFlushSyncedParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index: NameList; +} + +export interface IndicesForcemergeParams extends GenericParams { + flush?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + maxNumSegments?: number; + onlyExpungeDeletes?: boolean; + operationThreading?: any; // even the docs don't know what this does + waitForMerge?: boolean; + index: NameList; +} + +export interface IndicesGetParams extends GenericParams { + local?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + flatSettings?: boolean; + human?: boolean; + includeDefaults?: boolean; + index?: NameList; + feature?: NameList; +} + +export interface IndicesGetAliasParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + local?: boolean; + index?: NameList; + name?: NameList; +} + +export interface IndicesGetFieldMappingParams extends GenericParams { + includeDefaults?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + local?: boolean; + index?: NameList; + type?: NameList; + fields?: NameList; +} + +export interface IndicesGetMappingParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + local?: boolean; + index?: NameList; + type?: NameList; +} + +export interface IndicesGetSettingsParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + flatSettings?: boolean; + local?: boolean; + human?: boolean; + includeDefaults?: boolean; + index?: NameList; + name?: NameList; +} + +export interface IndicesGetTemplateParams extends GenericParams { + flatSettings?: boolean; + masterTimeout?: TimeSpan; + local?: boolean; + name?: NameList; +} + +export interface IndicesGetUpgradeParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + human?: boolean; + index?: NameList; +} + +export interface IndicesOpenParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index?: NameList; +} + +export interface IndicesPutAliasParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + index?: NameList; + name: NameList; +} + +export interface IndicesPutMappingParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + updateAllTypes?: boolean; + index: NameList; + type: string; + body: any; +} + +export interface IndicesPutSettingsParams extends GenericParams { + masterTimeout?: TimeSpan; + preserveExisting?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + flatSettings?: boolean; + index: NameList; + body: any; +} + +export interface IndicesPutTemplateParams extends GenericParams { + order?: number; + create?: boolean; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + flatSettings?: boolean; + name: string; + body: any; +} + +export interface IndicesRecoveryParams extends GenericParams { + detailed?: boolean; + activeOnly?: boolean; + human?: boolean; + index: NameList; +} + +export interface IndicesRefreshParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + force?: boolean; + operationThreading?: any; // even the docs don't know what this does + index: NameList; +} + +export interface IndicesRolloverParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + waitForActiveShards?: number | string; + alias?: string; + newIndex?: string; +} + +export interface IndicesRolloverResponse { + acknowledged: boolean; + shards_acknowledged: boolean; + old_index: string; + new_index: string; + rolled_over: boolean; + dry_run: boolean; + conditions: { [condition: string]: boolean }; +} + +export interface IndicesSegmentsParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + human?: boolean; + operationThreading?: any; // even the docs don't know what this does + verbose?: boolean; + index: NameList; +} + +export interface IndicesShardStoresParams extends GenericParams { + status?: NameList; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + operationThreading?: any; // even the docs don't know what this does + index: NameList; +} + +export interface IndicesShrinkParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + waitForActiveShards?: string | number; + index: string; + target: string; +} + +export interface IndicesStatsParams extends GenericParams { + completionFields?: NameList; + fielddataFields?: NameList; + fields?: NameList; + groups?: NameList; + human?: boolean; + level?: "cluster" | "indices" | "shards"; + types?: NameList; + index: NameList; + metric?: NameList; +} + +export interface IndicesUpdateAliasesParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + body: { + actions: IndicesUpdateAliasesParamsAction[]; + }; +} + +export interface IndicesUpdateAliasesParamsAction { + add?: { + index?: string; + indices?: string[]; + alias: string; + }; + remove?: { + index?: string; + indices?: string[]; + alias: string; + }; + remove_index?: { + index: string; + }; +} + +export interface IndicesUpgradeParams extends GenericParams { + expandWildcards?: ExpandWildcards; + ignoreUnavailable?: boolean; + waitForCompletion?: boolean; + onlyAncientSegments?: boolean; + index: NameList; +} + +export interface IndicesValidateQueryParams extends GenericParams { + explain?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + operationThreading?: any; // even the docs don't know what this does + q?: string; + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + rewrite?: boolean; + index: NameList; + type?: NameList; +} + +export class Ingest { + deletePipeline(params: IngestDeletePipelineParams, callback: (error: any, response: any, status: any) => void): void; + deletePipeline(params: IngestDeletePipelineParams): Promise; + getPipeline(params: IngestGetPipelineParams, callback: (error: any, response: any, status: any) => void): void; + getPipeline(params: IngestGetPipelineParams): Promise; + putPipeline(params: IngestPutPipelineParams, callback: (error: any, response: any, status: any) => void): void; + putPipeline(params: IngestPutPipelineParams): Promise; + simulate(params: IngestSimulateParams, callback: (error: any, response: any, status: any) => void): void; + simulate(params: IngestSimulateParams): Promise; +} + +export interface IngestDeletePipelineParams extends GenericParams { + masterTimeout?: number; + timeout?: number; + id: string; +} + +export interface IngestGetPipelineParams extends GenericParams { + masterTimeout?: number; + id: string; +} + +export interface IngestPutPipelineParams extends GenericParams { + masterTimeout?: number; + timeout?: number; + id: string; + body: any; +} + +export interface IngestSimulateParams extends GenericParams { + verbose?: boolean; + id: string; +} + +export class Nodes { + hotThreads(params: NodesHotThreadsParams, callback: (error: any, response: any, status: any) => void): void; + hotThreads(params: NodesHotThreadsParams): Promise; + info(params: NodesInfoParams, callback: (error: any, response: any, status: any) => void): void; + info(params: NodesInfoParams): Promise; + stats(params: NodesStatsParams, callback: (error: any, response: any, status: any) => void): void; + stats(params: NodesStatsParams): Promise; +} + +export interface NodesHotThreadsParams extends GenericParams { + interval?: TimeSpan; + snapshots?: number; + threads?: number; + ignoreIdleThreads?: boolean; + type?: "cpu" | "wait" | "blocked"; + timeout?: TimeSpan; + nodeId: NameList; +} + +export interface NodesInfoParams extends GenericParams { + flatSettings?: boolean; + human?: boolean; + timeout?: TimeSpan; + nodeId: NameList; + metric?: NameList; +} + +export interface NodesStatsParams extends GenericParams { + completionFields?: NameList; + fielddataFields?: NameList; + fields?: NameList; + groups?: boolean; + human?: boolean; + level?: "indices" | "node" | "shards"; + types?: NameList; + timeout?: TimeSpan; + metric?: NameList; + indexMetric?: NameList; + nodeId?: NameList; +} + +export class Snapshot { + create(params: SnapshotCreateParams, callback: (error: any, response: any, status: any) => void): void; + create(params: SnapshotCreateParams): Promise; + createRepository(params: SnapshotCreateRepositoryParams, callback: (error: any, response: any, status: any) => void): void; + createRepository(params: SnapshotCreateRepositoryParams): Promise; + delete(params: SnapshotDeleteParams, callback: (error: any, response: any, status: any) => void): void; + delete(params: SnapshotDeleteParams): Promise; + deleteRepository(params: SnapshotDeleteRepositoryParams, callback: (error: any, response: any, status: any) => void): void; + deleteRepository(params: SnapshotDeleteRepositoryParams): Promise; + get(params: SnapshotGetParams, callback: (error: any, response: any, status: any) => void): void; + get(params: SnapshotGetParams): Promise; + getRepository(params: SnapshotGetRepositoryParams, callback: (error: any, response: any, status: any) => void): void; + getRepository(params: SnapshotGetRepositoryParams): Promise; + restore(params: SnapshotRestoreParams, callback: (error: any, response: any, status: any) => void): void; + restore(params: SnapshotRestoreParams): Promise; + status(params: SnapshotStatusParams, callback: (error: any, response: any, status: any) => void): void; + status(params: SnapshotStatusParams): Promise; + verifyRepository(params: SnapshotVerifyRepositoryParams, callback: (error: any, response: any, status: any) => void): void; + verifyRepository(params: SnapshotVerifyRepositoryParams): Promise; +} + +export interface SnapshotCreateParams extends GenericParams { + masterTimeout?: TimeSpan; + waitForCompletion?: boolean; + repository: string; + snapshot: string; +} + +export interface SnapshotCreateRepositoryParams extends GenericParams { + masterTimeout?: TimeSpan; + timeout?: TimeSpan; + verify?: boolean; + repository: string; +} + +export interface SnapshotDeleteParams extends GenericParams { + masterTimeout?: TimeSpan; + repository: string; + snapshot: string; +} + +export interface SnapshotDeleteRepositoryParams extends GenericParams { + masterTimeout?: TimeSpan; + timeout?: TimeSpan; + repository: string; +} + +export interface SnapshotGetParams extends GenericParams { + masterTimeout?: TimeSpan; + ignoreUnavailable?: boolean; + repository: string; + snapshot: NameList; +} + +export interface SnapshotGetRepositoryParams extends GenericParams { + masterTimeout?: TimeSpan; + local?: boolean; + repository: NameList; +} + +export interface SnapshotRestoreParams extends GenericParams { + masterTimeout?: TimeSpan; + waitForCompletion?: boolean; + repository: string; + snapshot: string; +} + +export interface SnapshotStatusParams extends GenericParams { + masterTimeout?: TimeSpan; + ignoreUnavailable?: boolean; + repository: string; + snapshot: NameList; +} + +export interface SnapshotVerifyRepositoryParams extends GenericParams { + masterTimeout?: TimeSpan; + timeout?: TimeSpan; + repository: string; +} + +export class Tasks { + cancel(params: TasksCancelParams, callback: (error: any, response: any, status: any) => void): void; + cancel(params: TasksCancelParams): Promise; + get(params: TasksGetParams, callback: (error: any, response: any, status: any) => void): void; + get(params: TasksGetParams): Promise; + list(params: TasksListParams, callback: (error: any, response: any, status: any) => void): void; + list(params: TasksListParams): Promise; +} + +export interface TasksCancelParams extends GenericParams { + nodeId?: NameList; + actions?: NameList; + parentNode?: string; + parentTask?: string; + taskId?: string; +} + +export interface TasksGetParams extends GenericParams { + waitForCompletion?: boolean; + taskId?: string; +} + +export interface TasksListParams extends GenericParams { + nodeId?: NameList; + actions?: NameList; + detailed?: boolean; + parentNode?: string; + parentTask?: string; + waitForCompletion?: boolean; + groupBy?: "nodes" | "parents"; +} + +export namespace errors { + class _Abstract extends Error {} + class Generic extends _Abstract {} + class ConnectionFault extends _Abstract {} + class NoConnections extends _Abstract {} + class Serialization extends _Abstract {} + class RequestTypeError extends _Abstract {} + + class AuthenticationException extends _Abstract {} + class AuthorizationException extends _Abstract {} + class BadGateway extends _Abstract {} + class BadRequest extends _Abstract {} + class BlockedByWindowsParentalControls extends _Abstract {} + class ClientClosedRequest extends _Abstract {} + class Conflict extends _Abstract {} + class ExpectationFailed extends _Abstract {} + class GatewayTimeout extends _Abstract {} + class HTTPToHTTPS extends _Abstract {} + class HTTPVersionNotSupported extends _Abstract {} + class ImATeapot extends _Abstract {} + class InternalServerError extends _Abstract {} + class LengthRequired extends _Abstract {} + class MethodNotAllowed extends _Abstract {} + class MovedPermanently extends _Abstract {} + class MultipleChoices extends _Abstract {} + class NotAcceptable extends _Abstract {} + class NotExtended extends _Abstract {} + class NotFound extends _Abstract {} + class NotImplemented extends _Abstract {} + class NotModified extends _Abstract {} + class PaymentRequired extends _Abstract {} + class PermanentRedirect extends _Abstract {} + class PreconditionFailed extends _Abstract {} + class ProxyAuthenticationRequired extends _Abstract {} + class RequestedRangeNotSatisfiable extends _Abstract {} + class RequestEntityTooLarge extends _Abstract {} + class RequestHeaderTooLarge extends _Abstract {} + class RequestTimeout extends _Abstract {} + class RequestURITooLong extends _Abstract {} + class SeeOther extends _Abstract {} + class ServiceUnavailable extends _Abstract {} + class TemporaryRedirect extends _Abstract {} + class TooManyConnectionsFromThisIP extends _Abstract {} + class TooManyRequests extends _Abstract {} + class UnsupportedMediaType extends _Abstract {} + class UpgradeRequired extends _Abstract {} + class UseProxy extends _Abstract {} + class VariantAlsoNegotiates extends _Abstract {} } diff --git a/types/elasticsearch/tsconfig.json b/types/elasticsearch/tsconfig.json index 2d62eac43d..21ac20d7e9 100644 --- a/types/elasticsearch/tsconfig.json +++ b/types/elasticsearch/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +21,4 @@ "index.d.ts", "elasticsearch-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/elasticsearch/tslint.json b/types/elasticsearch/tslint.json index a41bf5d19a..e9003e412b 100644 --- a/types/elasticsearch/tslint.json +++ b/types/elasticsearch/tslint.json @@ -1,79 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + "no-empty-interface": false } } diff --git a/types/ember-data/index.d.ts b/types/ember-data/index.d.ts new file mode 100644 index 0000000000..0e0678e7d7 --- /dev/null +++ b/types/ember-data/index.d.ts @@ -0,0 +1,1693 @@ +// Type definitions for ember-data 2.14 +// Project: https://github.com/emberjs/data +// Definitions by: Derek Wickern +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import Ember from 'ember'; + +declare namespace DS { + /** + * Convert an hash of errors into an array with errors in JSON-API format. + */ + function errorsHashToArray(errors: {}): any[]; + /** + * Convert an array of errors in JSON-API format into an object. + */ + function errorsArrayToHash(errors: any[]): {}; + /** + * `DS.belongsTo` is used to define One-To-One and One-To-Many + * relationships on a [DS.Model](/api/data/classes/DS.Model.html). + */ + function belongsTo(modelName: string, options: { + async: false, + inverse?: string | null, + polymorphic?: boolean + }): Ember.ComputedProperty; + function belongsTo(modelName: string, options?: { + async?: true, + inverse?: string | null, + polymorphic?: boolean + }): Ember.ComputedProperty>; + /** + * `DS.hasMany` is used to define One-To-Many and Many-To-Many + * relationships on a [DS.Model](/api/data/classes/DS.Model.html). + */ + function hasMany(type: string, options: { + async: false, + inverse?: string | null, + polymorphic?: boolean + }): Ember.ComputedProperty>; + function hasMany(type: string, options?: { + async?: true, + inverse?: string | null, + polymorphic?: boolean + }): Ember.ComputedProperty>; + /** + * This method normalizes a modelName into the format Ember Data uses + * internally. + */ + function normalizeModelName(modelName: string): string; + const VERSION: string; + + interface AttrOptions { + defaultValue?: T | (() => T); + } + + /** + * `DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html). + * By default, attributes are passed through as-is, however you can specify an + * optional type to have the value automatically transformed. + * Ember Data ships with four basic transform types: `string`, `number`, + * `boolean` and `date`. You can define your own transforms by subclassing + * [DS.Transform](/api/data/classes/DS.Transform.html). + */ + function attr(type: 'string', options?: AttrOptions): Ember.ComputedProperty; + function attr(type: 'boolean', options?: AttrOptions): Ember.ComputedProperty; + function attr(type: 'number', options?: AttrOptions): Ember.ComputedProperty; + function attr(type: 'date', options?: AttrOptions): Ember.ComputedProperty; + function attr(type: string, options?: AttrOptions): Ember.ComputedProperty; + function attr(options?: AttrOptions): Ember.ComputedProperty; + /** + * WARNING: This interface is likely to change in order to accomodate https://github.com/emberjs/rfcs/pull/4 + * ## Using BuildURLMixin + * To use url building, include the mixin when extending an adapter, and call `buildURL` where needed. + * The default behaviour is designed for RESTAdapter. + * ### Example + * ```javascript + * export default DS.Adapter.extend(BuildURLMixin, { + * findRecord: function(store, type, id, snapshot) { + * var url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); + * return this.ajax(url, 'GET'); + * } + * }); + * ``` + * ### Attributes + * The `host` and `namespace` attributes will be used if defined, and are optional. + */ + class BuildURLMixin { + /** + * Builds a URL for a given type and optional ID. + */ + buildURL(modelName: string, id: string|any[]|{}, snapshot: Snapshot|any[], requestType: string, query: {}): string; + /** + * Builds a URL for a `store.findRecord(type, id)` call. + */ + urlForFindRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `store.findAll(type)` call. + */ + urlForFindAll(modelName: string, snapshot: SnapshotRecordArray): string; + /** + * Builds a URL for a `store.query(type, query)` call. + */ + urlForQuery(query: {}, modelName: string): string; + /** + * Builds a URL for a `store.queryRecord(type, query)` call. + */ + urlForQueryRecord(query: {}, modelName: string): string; + /** + * Builds a URL for coalesceing multiple `store.findRecord(type, id)` + * records into 1 request when the adapter's `coalesceFindRequests` + * property is true. + */ + urlForFindMany(ids: any[], modelName: string, snapshots: any[]): string; + /** + * Builds a URL for fetching a async hasMany relationship when a url + * is not provided by the server. + */ + urlForFindHasMany(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for fetching a async belongsTo relationship when a url + * is not provided by the server. + */ + urlForFindBelongsTo(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record was created + * locally using `store.createRecord()`. + */ + urlForCreateRecord(modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been update locally. + */ + urlForUpdateRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been deleted locally. + */ + urlForDeleteRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Determines the pathname for a given type. + */ + pathForType(modelName: string): string; + } + /** + * A `DS.AdapterError` is used by an adapter to signal that an error occurred + * during a request to an external API. It indicates a generic error, and + * subclasses are used to indicate specific error states. The following + * subclasses are provided: + */ + class AdapterError { + } + /** + * A `DS.InvalidError` is used by an adapter to signal the external API + * was unable to process a request because the content was not + * semantically correct or meaningful per the API. Usually this means a + * record failed some form of server side validation. When a promise + * from an adapter is rejected with a `DS.InvalidError` the record will + * transition to the `invalid` state and the errors will be set to the + * `errors` property on the record. + */ + class InvalidError { + } + /** + * A `DS.TimeoutError` is used by an adapter to signal that a request + * to the external API has timed out. I.e. no response was received from + * the external API within an allowed time period. + */ + class TimeoutError { + } + /** + * A `DS.AbortError` is used by an adapter to signal that a request to + * the external API was aborted. For example, this can occur if the user + * navigates away from the current page after a request to the external API + * has been initiated but before a response has been received. + */ + class AbortError { + } + /** + * A `DS.UnauthorizedError` equates to a HTTP `401 Unauthorized` response + * status. It is used by an adapter to signal that a request to the external + * API was rejected because authorization is required and has failed or has not + * yet been provided. + */ + class UnauthorizedError { + } + /** + * A `DS.ForbiddenError` equates to a HTTP `403 Forbidden` response status. + * It is used by an adapter to signal that a request to the external API was + * valid but the server is refusing to respond to it. If authorization was + * provided and is valid, then the authenticated user does not have the + * necessary permissions for the request. + */ + class ForbiddenError { + } + /** + * A `DS.NotFoundError` equates to a HTTP `404 Not Found` response status. + * It is used by an adapter to signal that a request to the external API + * was rejected because the resource could not be found on the API. + */ + class NotFoundError { + } + /** + * A `DS.ConflictError` equates to a HTTP `409 Conflict` response status. + * It is used by an adapter to indicate that the request could not be processed + * because of a conflict in the request. An example scenario would be when + * creating a record with a client generated id but that id is already known + * to the external API. + */ + class ConflictError { + } + /** + * A `DS.ServerError` equates to a HTTP `500 Internal Server Error` response + * status. It is used by the adapter to indicate that a request has failed + * because of an error in the external API. + */ + class ServerError { + } + /** + * Holds validation errors for a given record, organized by attribute names. + */ + interface Errors extends Ember.Enumerable, Ember.Evented {} + class Errors extends Ember.Object { + /** + * DEPRECATED: + * Register with target handler + */ + registerHandlers(target: {}, becameInvalid: Function, becameValid: Function): any; + /** + * Returns errors for a given attribute + */ + errorsFor(attribute: string): any[]; + /** + * An array containing all of the error messages for this + * record. This is useful for displaying all errors to the user. + */ + messages: Ember.ComputedProperty; + /** + * Total number of errors. + */ + length: Ember.ComputedProperty; + isEmpty: Ember.ComputedProperty; + /** + * DEPRECATED: + * Adds error messages to a given attribute and sends + * `becameInvalid` event to the record. + */ + add(attribute: string, messages: any[]|string): any; + /** + * DEPRECATED: + * Removes all error messages from the given attribute and sends + * `becameValid` event to the record if there no more errors left. + */ + remove(attribute: string): any; + /** + * DEPRECATED: + * Removes all error messages and sends `becameValid` event + * to the record. + */ + clear(): any; + /** + * Checks if there is error messages for the given attribute. + */ + has(attribute: string): boolean; + } + /** + * The model class that all Ember Data records descend from. + * This is the public API of Ember Data models. If you are using Ember Data + * in your application, this is the class you should use. + * If you are working on Ember Data internals, you most likely want to be dealing + * with `InternalModel` + */ + class Model extends Ember.Object { + /** + * If this property is `true` the record is in the `empty` + * state. Empty is the first state all records enter after they have + * been created. Most records created by the store will quickly + * transition to the `loading` state if data needs to be fetched from + * the server or the `created` state if the record is created on the + * client. A record can also enter the empty state if the adapter is + * unable to locate the record. + */ + isEmpty: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `loading` state. A + * record enters this state when the store asks the adapter for its + * data. It remains in this state until the adapter provides the + * requested data. + */ + isLoading: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `loaded` state. A + * record enters this state when its data is populated. Most of a + * record's lifecycle is spent inside substates of the `loaded` + * state. + */ + isLoaded: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `dirty` state. The + * record has local changes that have not yet been saved by the + * adapter. This includes records that have been created (but not yet + * saved) or deleted. + */ + hasDirtyAttributes: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `saving` state. A + * record enters the saving state when `save` is called, but the + * adapter has not yet acknowledged that the changes have been + * persisted to the backend. + */ + isSaving: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `deleted` state + * and has been marked for deletion. When `isDeleted` is true and + * `hasDirtyAttributes` is true, the record is deleted locally but the deletion + * was not yet persisted. When `isSaving` is true, the change is + * in-flight. When both `hasDirtyAttributes` and `isSaving` are false, the + * change has persisted. + */ + isDeleted: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `new` state. A + * record will be in the `new` state when it has been created on the + * client and the adapter has not yet report that it was successfully + * saved. + */ + isNew: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `valid` state. + */ + isValid: Ember.ComputedProperty; + /** + * If the record is in the dirty state this property will report what + * kind of change has caused it to move into the dirty + * state. Possible values are: + */ + dirtyType: Ember.ComputedProperty; + /** + * If `true` the adapter reported that it was unable to save local + * changes to the backend for any reason other than a server-side + * validation error. + */ + isError: boolean; + /** + * If `true` the store is attempting to reload the record from the adapter. + */ + isReloading: boolean; + /** + * All ember models have an id property. This is an identifier + * managed by an external source. These are always coerced to be + * strings before being used internally. Note when declaring the + * attributes for a model it is an error to declare an id + * attribute. + */ + id: string; + /** + * When the record is in the `invalid` state this object will contain + * any errors returned by the adapter. When present the errors hash + * contains keys corresponding to the invalid property names + * and values which are arrays of Javascript objects with two keys: + */ + errors: Ember.ComputedProperty; + /** + * This property holds the `DS.AdapterError` object with which + * last adapter operation was rejected. + */ + adapterError: AdapterError; + /** + * Create a JSON representation of the record, using the serialization + * strategy of the store's adapter. + */ + serialize(options: {}): {}; + /** + * Use [DS.JSONSerializer](DS.JSONSerializer.html) to + * get the JSON representation of a record. + */ + toJSON(options: {}): {}; + /** + * Fired when the record is ready to be interacted with, + * that is either loaded from the server or created locally. + */ + ready(): void; + /** + * Fired when the record is loaded from the server. + */ + didLoad(): void; + /** + * Fired when the record is updated. + */ + didUpdate(): void; + /** + * Fired when a new record is commited to the server. + */ + didCreate(): void; + /** + * Fired when the record is deleted. + */ + didDelete(): void; + /** + * Fired when the record becomes invalid. + */ + becameInvalid(): void; + /** + * Fired when the record enters the error state. + */ + becameError(): void; + /** + * Fired when the record is rolled back. + */ + rolledBack(): void; + /** + * Marks the record as deleted but does not save it. You must call + * `save` afterwards if you want to persist it. You might use this + * method if you want to allow the user to still `rollbackAttributes()` + * after a delete was made. + */ + deleteRecord(): any; + /** + * Same as `deleteRecord`, but saves the record immediately. + */ + destroyRecord(options: {}): Promise; + /** + * Unloads the record from the store. This will cause the record to be destroyed and freed up for garbage collection. + */ + unloadRecord(): any; + /** + * Returns an object, whose keys are changed properties, and value is + * an [oldProp, newProp] array. + */ + changedAttributes(): {}; + /** + * If the model `hasDirtyAttributes` this function will discard any unsaved + * changes. If the model `isNew` it will be removed from the store. + */ + rollbackAttributes(): any; + /** + * Save the record and persist any changes to the record to an + * external source via the adapter. + */ + save(options?: {}): Promise; + /** + * Reload the record from the adapter. + */ + reload(): Promise; + /** + * Get the reference for the specified belongsTo relationship. + */ + belongsTo(name: string): BelongsToReference; + /** + * Get the reference for the specified hasMany relationship. + */ + hasMany(name: string): HasManyReference; + /** + * Given a callback, iterates over each of the relationships in the model, + * invoking the callback with the name of each relationship and its relationship + * descriptor. + */ + eachRelationship(callback: Function, binding: any): any; + /** + * Represents the model's class name as a string. This can be used to look up the model's class name through + * `DS.Store`'s modelFor method. + */ + static modelName: string; + /** + * For a given relationship name, returns the model type of the relationship. + */ + static typeForRelationship(name: string, store: Store): Model; + /** + * Find the relationship which is the inverse of the one asked for. + */ + static inverseFor(name: string, store: Store): {}; + /** + * The model's relationships as a map, keyed on the type of the + * relationship. The value of each entry is an array containing a descriptor + * for each relationship with that type, describing the name of the relationship + * as well as the type. + */ + static relationships: Ember.ComputedProperty; + /** + * A hash containing lists of the model's relationships, grouped + * by the relationship kind. For example, given a model with this + * definition: + */ + static relationshipNames: Ember.ComputedProperty<{}>; + /** + * An array of types directly related to a model. Each type will be + * included once, regardless of the number of relationships it has with + * the model. + */ + static relatedTypes: Ember.ComputedProperty>; + /** + * A map whose keys are the relationships of a model and whose values are + * relationship descriptors. + */ + static relationshipsByName: Ember.ComputedProperty; + /** + * A map whose keys are the fields of the model and whose values are strings + * describing the kind of the field. A model's fields are the union of all of its + * attributes and relationships. + */ + static fields: Ember.ComputedProperty; + /** + * Given a callback, iterates over each of the relationships in the model, + * invoking the callback with the name of each relationship and its relationship + * descriptor. + */ + static eachRelationship(callback: Function, binding: any): any; + /** + * Given a callback, iterates over each of the types related to a model, + * invoking the callback with the related type's class. Each type will be + * returned just once, regardless of how many different relationships it has + * with a model. + */ + static eachRelatedType(callback: Function, binding: any): any; + /** + * A map whose keys are the attributes of the model (properties + * described by DS.attr) and whose values are the meta object for the + * property. + */ + static attributes: Ember.ComputedProperty; + /** + * A map whose keys are the attributes of the model (properties + * described by DS.attr) and whose values are type of transformation + * applied to each attribute. This map does not include any + * attributes that do not have an transformation type. + */ + static transformedAttributes: Ember.ComputedProperty; + /** + * Iterates through the attributes of the model, calling the passed function on each + * attribute. + */ + static eachAttribute(callback: Function, binding: {}): any; + /** + * Iterates through the transformedAttributes of the model, calling + * the passed function on each attribute. Note the callback will not be + * called for any attributes that do not have an transformation type. + */ + static eachTransformedAttribute(callback: Function, binding: {}): any; + /** + * Discards any unsaved changes to the given attribute. This feature is not enabled by default. You must enable `ds-rollback-attribute` and be running a canary build. + */ + rollbackAttribute(): any; + /** + * This Ember.js hook allows an object to be notified when a property + * is defined. + */ + didDefineProperty(proto: {}, key: string, value: Ember.ComputedProperty): any; + } + /** + * ### State + */ + class RootState { + } + /** + * Represents an ordered list of records whose order and membership is + * determined by the adapter. For example, a query sent to the adapter + * may trigger a search on the server, whose results would be loaded + * into an instance of the `AdapterPopulatedRecordArray`. + */ + class AdapterPopulatedRecordArray extends RecordArray { + } + /** + * Represents a list of records whose membership is determined by the + * store. As records are created, loaded, or modified, the store + * evaluates them to determine if they should be part of the record + * array. + */ + class FilteredRecordArray extends RecordArray { + /** + * The filterFunction is a function used to test records from the store to + * determine if they should be part of the record array. + */ + filterFunction(record: Model): boolean; + } + /** + * A record array is an array that contains records of a certain modelName. The record + * array materializes records as needed when they are retrieved for the first + * time. You should not create record arrays yourself. Instead, an instance of + * `DS.RecordArray` or its subclasses will be returned by your application's store + * in response to queries. + */ + interface RecordArray extends Ember.ArrayProxy, Ember.Evented {} + class RecordArray { + /** + * The flag to signal a `RecordArray` is finished loading data. + */ + isLoaded: boolean; + /** + * The flag to signal a `RecordArray` is currently loading data. + */ + isUpdating: boolean; + /** + * The modelClass represented by this record array. + */ + type: Ember.ComputedProperty; + /** + * Used to get the latest version of all of the records in this array + * from the adapter. + */ + update(): any; + /** + * Saves all of the records in the `RecordArray`. + */ + save(): PromiseArray; + } + /** + * A BelongsToReference is a low level API that allows users and + * addon author to perform meta-operations on a belongs-to + * relationship. + */ + class BelongsToReference { + /** + * This returns a string that represents how the reference will be + * looked up when it is loaded. If the relationship has a link it will + * use the "link" otherwise it defaults to "id". + */ + remoteType(): string; + /** + * The `id` of the record that this reference refers to. Together, the + * `type()` and `id()` methods form a composite key for the identity + * map. This can be used to access the id of an async relationship + * without triggering a fetch that would normally happen if you + * attempted to use `record.get('relationship.id')`. + */ + id(): string; + /** + * The link Ember Data will use to fetch or reload this belongs-to + * relationship. + */ + link(): string; + /** + * The meta data for the belongs-to relationship. + */ + meta(): {}; + /** + * `push` can be used to update the data in the relationship and Ember + * Data will treat the new data as the conanical value of this + * relationship on the backend. + */ + push(objectOrPromise: {}|Promise): Promise; + /** + * `value()` synchronously returns the current value of the belongs-to + * relationship. Unlike `record.get('relationshipName')`, calling + * `value()` on a reference does not trigger a fetch if the async + * relationship is not yet loaded. If the relationship is not loaded + * it will always return `null`. + */ + value(objectOrPromise: {}|Promise): Model; + /** + * Loads a record in a belongs to relationship if it is not already + * loaded. If the relationship is already loaded this method does not + * trigger a new load. + */ + load(): Promise; + /** + * Triggers a reload of the value in this relationship. If the + * remoteType is `"link"` Ember Data will use the relationship link to + * reload the relationship. Otherwise it will reload the record by its + * id. + */ + reload(): Promise; + } + /** + * A HasManyReference is a low level API that allows users and addon + * author to perform meta-operations on a has-many relationship. + */ + class HasManyReference { + /** + * This returns a string that represents how the reference will be + * looked up when it is loaded. If the relationship has a link it will + * use the "link" otherwise it defaults to "id". + */ + remoteType(): string; + /** + * The link Ember Data will use to fetch or reload this has-many + * relationship. + */ + link(): string; + /** + * `ids()` returns an array of the record ids in this relationship. + */ + ids(): any[]; + /** + * The meta data for the has-many relationship. + */ + meta(): {}; + /** + * `push` can be used to update the data in the relationship and Ember + * Data will treat the new data as the canonical value of this + * relationship on the backend. + */ + push(objectOrPromise: T[] | Promise): ManyArray; + /** + * `value()` synchronously returns the current value of the has-many + * relationship. Unlike `record.get('relationshipName')`, calling + * `value()` on a reference does not trigger a fetch if the async + * relationship is not yet loaded. If the relationship is not loaded + * it will always return `null`. + */ + value(): ManyArray; + /** + * Loads the relationship if it is not already loaded. If the + * relationship is already loaded this method does not trigger a new + * load. + */ + load(): Promise; + /** + * Reloads this has-many relationship. + */ + reload(): Promise; + } + /** + * An RecordReference is a low level API that allows users and + * addon author to perform meta-operations on a record. + */ + class RecordReference { + /** + * The `id` of the record that this reference refers to. + */ + id(): string; + /** + * How the reference will be looked up when it is loaded: Currently + * this always return `identity` to signifying that a record will be + * loaded by the `type` and `id`. + */ + remoteType(): string; + /** + * This API allows you to provide a reference with new data. The + * simplest usage of this API is similar to `store.push`: you provide a + * normalized hash of data and the object represented by the reference + * will update. + */ + push(payload: Promise|{}): PromiseObject & T; + /** + * If the entity referred to by the reference is already loaded, it is + * present as `reference.value`. Otherwise the value returned by this function + * is `null`. + */ + value(): T | null; + /** + * Triggers a fetch for the backing entity based on its `remoteType` + * (see `remoteType` definitions per reference type). + */ + load(): PromiseObject & T; + /** + * Reloads the record if it is already loaded. If the record is not + * loaded it will load the record via `store.findRecord` + */ + reload(): PromiseObject & T; + } + /** + * A `ManyArray` is a `MutableArray` that represents the contents of a has-many + * relationship. + */ + interface ManyArray extends Ember.MutableArray {} + class ManyArray extends Ember.Object.extend(Ember.MutableArray as {}, Ember.Evented) { + /** + * The loading state of this array + */ + isLoaded: boolean; + /** + * Metadata associated with the request for async hasMany relationships. + */ + meta: {}; + /** + * Reloads all of the records in the manyArray. If the manyArray + * holds a relationship that was originally fetched using a links url + * Ember Data will revisit the original links url to repopulate the + * relationship. + */ + reload(): PromiseArray; + /** + * Saves all of the records in the `ManyArray`. + */ + save(): PromiseArray; + /** + * Create a child record within the owner + */ + createRecord(inputProperties?: {}): T; + } + /** + * A `PromiseArray` is an object that acts like both an `Ember.Array` + * and a promise. When the promise is resolved the resulting value + * will be set to the `PromiseArray`'s `content` property. This makes + * it easy to create data bindings with the `PromiseArray` that will be + * updated when the promise resolves. + */ + interface PromiseArray extends Ember.ArrayProxy, Ember.PromiseProxyMixin> {} + class PromiseArray { + } + /** + * A `PromiseObject` is an object that acts like both an `Ember.Object` + * and a promise. When the promise is resolved, then the resulting value + * will be set to the `PromiseObject`'s `content` property. This makes + * it easy to create data bindings with the `PromiseObject` that will + * be updated when the promise resolves. + */ + interface PromiseObject extends Ember.ObjectProxy, Ember.PromiseProxyMixin> {} + class PromiseObject { + } + /** + * A PromiseManyArray is a PromiseArray that also proxies certain method calls + * to the underlying manyArray. + * Right now we proxy: + */ + class PromiseManyArray extends PromiseArray { + /** + * Reloads all of the records in the manyArray. If the manyArray + * holds a relationship that was originally fetched using a links url + * Ember Data will revisit the original links url to repopulate the + * relationship. + */ + reload(): PromiseManyArray; + /** + * Create a child record within the owner + */ + createRecord(inputProperties?: {}): T; + } + class SnapshotRecordArray { + /** + * Number of records in the array + */ + length: number; + /** + * Meta objects for the record array. + */ + meta: {}; + /** + * A hash of adapter options passed into the store method for this request. + */ + adapterOptions: {}; + /** + * The relationships to include for this request. + */ + include: string|any[]; + /** + * The type of the underlying records for the snapshots in the array, as a DS.Model + */ + type: Model; + /** + * Get snapshots of the underlying record array + */ + snapshots(): any[]; + } + class Snapshot { + /** + * The underlying record for this snapshot. Can be used to access methods and + * properties defined on the record. + */ + record: Model; + /** + * The id of the snapshot's underlying record + */ + id: string; + /** + * A hash of adapter options + */ + adapterOptions: {}; + /** + * The name of the type of the underlying record for this snapshot, as a string. + */ + modelName: string; + /** + * The type of the underlying record for this snapshot, as a DS.Model. + */ + type: Model; + /** + * Returns the value of an attribute. + */ + attr(keyName: string): {}; + /** + * Returns all attributes and their corresponding values. + */ + attributes(): {}; + /** + * Returns all changed attributes and their old and new values. + */ + changedAttributes(): {}; + /** + * Returns the current value of a belongsTo relationship. + */ + belongsTo(keyName: string, options: {}): Snapshot|string|null|undefined; + /** + * Returns the current value of a hasMany relationship. + */ + hasMany(keyName: string, options: {}): any[]|undefined; + /** + * Iterates through all the attributes of the model, calling the passed + * function on each attribute. + */ + eachAttribute(callback: Function, binding: {}): any; + /** + * Iterates through all the relationships of the model, calling the passed + * function on each relationship. + */ + eachRelationship(callback: Function, binding: {}): any; + /** + * Serializes the snapshot using the serializer for the model. + */ + serialize(options: {}): {}; + } + /** + * The store contains all of the data for records loaded from the server. + * It is also responsible for creating instances of `DS.Model` that wrap + * the individual data for a record, so that they can be bound to in your + * Handlebars templates. + */ + class Store { + /** + * The default adapter to use to communicate to a backend server or + * other persistence layer. This will be overridden by an application + * adapter if present. + */ + adapter: string; + /** + * Create a new record in the current store. The properties passed + * to this method are set on the newly created record. + */ + createRecord(modelName: string, inputProperties?: {}): T; + /** + * For symmetry, a record can be deleted via the store. + */ + deleteRecord(record: Model): void; + /** + * For symmetry, a record can be unloaded via the store. + * This will cause the record to be destroyed and freed up for garbage collection. + */ + unloadRecord(record: Model): void; + /** + * This method returns a record for a given type and id combination. + */ + findRecord(modelName: string, id: string|number, options?: {}): PromiseObject & T; + /** + * Get the reference for the specified record. + */ + getReference(modelName: string, id: string|number): RecordReference; + /** + * Get a record by a given type and ID without triggering a fetch. + */ + peekRecord(modelName: string, id: string|number): T|null; + /** + * This method returns true if a record for a given modelName and id is already + * loaded in the store. Use this function to know beforehand if a findRecord() + * will result in a request or that it will be a cache hit. + */ + hasRecordForId(modelName: string, id: string|number): boolean; + /** + * This method delegates a query to the adapter. This is the one place where + * adapter-level semantics are exposed to the application. + */ + query(modelName: string, query: any): AdapterPopulatedRecordArray & PromiseArray; + /** + * This method makes a request for one record, where the `id` is not known + * beforehand (if the `id` is known, use [`findRecord`](#method_findRecord) + * instead). + */ + queryRecord(modelName: string, query: any): Promise; + /** + * `findAll` asks the adapter's `findAll` method to find the records for the + * given type, and returns a promise which will resolve with all records of + * this type present in the store, even if the adapter only returns a subset + * of them. + */ + findAll(modelName: string, options?: { + reload?: boolean, + backgroundReload?: boolean, + include?: string, + adapterOptions?: any + }): PromiseArray; + /** + * This method returns a filtered array that contains all of the + * known records for a given type in the store. + */ + peekAll(modelName: string): RecordArray; + /** + * This method unloads all records in the store. + * It schedules unloading to happen during the next run loop. + */ + unloadAll(modelName: string): void; + /** + * DEPRECATED: + * This method has been deprecated and is an alias for store.hasRecordForId, which should + * be used instead. + */ + recordIsLoaded(modelName: string, id: string): boolean; + /** + * Returns the model class for the particular `modelName`. + */ + modelFor(modelName: string): Model; + /** + * Push some data for a given type into the store. + */ + push(data: {}): Model|any[]; + /** + * Push some raw data into the store. + */ + pushPayload(modelName: string, inputPayload: {}): any; + pushPayload(inputPayload: {}): any; + /** + * `normalize` converts a json payload into the normalized form that + * [push](#method_push) expects. + */ + normalize(modelName: string, payload: {}): {}; + /** + * Returns an instance of the adapter for a given type. For + * example, `adapterFor('person')` will return an instance of + * `App.PersonAdapter`. + */ + adapterFor(modelName: string): Adapter; + /** + * Returns an instance of the serializer for a given type. For + * example, `serializerFor('person')` will return an instance of + * `App.PersonSerializer`. + */ + serializerFor(modelName: string): Serializer; + } + /** + * The `JSONAPIAdapter` is the default adapter used by Ember Data. It + * is responsible for transforming the store's requests into HTTP + * requests that follow the [JSON API](http://jsonapi.org/format/) + * format. + */ + class JSONAPIAdapter extends RESTAdapter { + /** + * By default the JSONAPIAdapter will send each find request coming from a `store.find` + * or from accessing a relationship separately to the server. If your server supports passing + * ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests + * within a single runloop. + */ + coalesceFindRequests: boolean; + } + /** + * The REST adapter allows your store to communicate with an HTTP server by + * transmitting JSON via XHR. Most Ember.js apps that consume a JSON API + * should use the REST adapter. + */ + class RESTAdapter extends Adapter implements BuildURLMixin { + /** + * Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. + */ + ajax(url: string, type: string, options?: object): Promise; + /** + * Generate ajax options + */ + ajaxOptions(url: string, type: string, options?: object): object; + /** + * By default, the RESTAdapter will send the query params sorted alphabetically to the + * server. + */ + sortQueryParams(obj: {}): {}; + /** + * By default the RESTAdapter will send each find request coming from a `store.find` + * or from accessing a relationship separately to the server. If your server supports passing + * ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests + * within a single runloop. + */ + coalesceFindRequests: boolean; + /** + * Endpoint paths can be prefixed with a `namespace` by setting the namespace + * property on the adapter: + */ + namespace: string; + /** + * An adapter can target other hosts by setting the `host` property. + */ + host: string; + /** + * Some APIs require HTTP headers, e.g. to provide an API + * key. Arbitrary headers can be set as key/value pairs on the + * `RESTAdapter`'s `headers` object and Ember Data will send them + * along with each ajax request. For dynamic headers see [headers + * customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization). + */ + headers: {}; + /** + * Called by the store in order to fetch the JSON for a given + * type and ID. + */ + findRecord(store: Store, type: Model, id: string, snapshot: Snapshot): Promise; + /** + * Called by the store in order to fetch a JSON array for all + * of the records for a given type. + */ + findAll(store: Store, type: Model, sinceToken: string, snapshotRecordArray: SnapshotRecordArray): Promise; + /** + * Called by the store in order to fetch a JSON array for + * the records that match a particular query. + */ + query(store: Store, type: Model, query: {}): Promise; + /** + * Called by the store in order to fetch a JSON object for + * the record that matches a particular query. + */ + queryRecord(store: Store, type: Model, query: {}): Promise; + /** + * Called by the store in order to fetch several records together if `coalesceFindRequests` is true + */ + findMany(store: Store, type: Model, ids: any[], snapshots: any[]): Promise; + /** + * Called by the store in order to fetch a JSON array for + * the unloaded records in a has-many relationship that were originally + * specified as a URL (inside of `links`). + */ + findHasMany(store: Store, snapshot: Snapshot, url: string, relationship: {}): Promise; + /** + * Called by the store in order to fetch the JSON for the unloaded record in a + * belongs-to relationship that was originally specified as a URL (inside of + * `links`). + */ + findBelongsTo(store: Store, snapshot: Snapshot, url: string): Promise; + /** + * Called by the store when a newly created record is + * saved via the `save` method on a model record instance. + */ + createRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Called by the store when an existing record is saved + * via the `save` method on a model record instance. + */ + updateRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Called by the store when a record is deleted. + */ + deleteRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Organize records into groups, each of which is to be passed to separate + * calls to `findMany`. + */ + groupRecordsForFindMany(store: Store, snapshots: any[]): any[]; + /** + * Takes an ajax response, and returns the json payload or an error. + */ + handleResponse(status: number, headers: {}, payload: {}, requestData: {}): {}; + /** + * Default `handleResponse` implementation uses this hook to decide if the + * response is a success. + */ + isSuccess(status: number, headers: {}, payload: {}): boolean; + /** + * Default `handleResponse` implementation uses this hook to decide if the + * response is an invalid error. + */ + isInvalid(status: number, headers: {}, payload: {}): boolean; + /** + * Get the data (body or query params) for a request. + */ + dataForRequest(params: {}): {}; + /** + * Get the HTTP method for a request. + */ + methodForRequest(params: {}): string; + /** + * Get the URL for a request. + */ + urlForRequest(params: {}): string; + /** + * Get the headers for a request. + */ + headersForRequest(params: {}): {}; + /** + * Builds a URL for a given type and optional ID. + */ + buildURL(modelName: string, id: string|any[]|{}, snapshot: Snapshot|any[], requestType: string, query: {}): string; + /** + * Builds a URL for a `store.findRecord(type, id)` call. + */ + urlForFindRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `store.findAll(type)` call. + */ + urlForFindAll(modelName: string, snapshot: SnapshotRecordArray): string; + /** + * Builds a URL for a `store.query(type, query)` call. + */ + urlForQuery(query: {}, modelName: string): string; + /** + * Builds a URL for a `store.queryRecord(type, query)` call. + */ + urlForQueryRecord(query: {}, modelName: string): string; + /** + * Builds a URL for coalesceing multiple `store.findRecord(type, id)` + * records into 1 request when the adapter's `coalesceFindRequests` + * property is true. + */ + urlForFindMany(ids: any[], modelName: string, snapshots: any[]): string; + /** + * Builds a URL for fetching a async hasMany relationship when a url + * is not provided by the server. + */ + urlForFindHasMany(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for fetching a async belongsTo relationship when a url + * is not provided by the server. + */ + urlForFindBelongsTo(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record was created + * locally using `store.createRecord()`. + */ + urlForCreateRecord(modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been update locally. + */ + urlForUpdateRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been deleted locally. + */ + urlForDeleteRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Determines the pathname for a given type. + */ + pathForType(modelName: string): string; + } + /** + * ## Using Embedded Records + */ + class EmbeddedRecordsMixin { + /** + * Normalize the record and recursively normalize/extract all the embedded records + * while pushing them into the store as they are encountered + */ + normalize(typeClass: Model, hash: {}, prop: string): {}; + /** + * Serialize `belongsTo` relationship when it is configured as an embedded object. + */ + serializeBelongsTo(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * Serializes `hasMany` relationships when it is configured as embedded objects. + */ + serializeHasMany(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * When serializing an embedded record, modify the property (in the json payload) + * that refers to the parent record (foreign key for relationship). + */ + removeEmbeddedForeignKey(snapshot: Snapshot, embeddedSnapshot: Snapshot, relationship: {}, json: {}): any; + } + /** + * Ember Data 2.0 Serializer: + */ + class JSONAPISerializer extends JSONSerializer { + pushPayload(store: Store, payload: {}): any; + /** + * Dasherizes and singularizes the model name in the payload to match + * the format Ember Data uses internally for the model name. + */ + modelNameFromPayloadKey(key: string): string; + /** + * Converts the model name to a pluralized version of the model name. + */ + payloadKeyFromModelName(modelName: string): string; + /** + * `keyForAttribute` can be used to define rules for how to convert an + * attribute name in your model to a key in your JSON. + * By default `JSONAPISerializer` follows the format used on the examples of + * http://jsonapi.org/format and uses dashes as the word separator in the JSON + * attribute keys. + */ + keyForAttribute(key: string, method: string): string; + /** + * `keyForRelationship` can be used to define a custom key when + * serializing and deserializing relationship properties. + * By default `JSONAPISerializer` follows the format used on the examples of + * http://jsonapi.org/format and uses dashes as word separators in + * relationship properties. + */ + keyForRelationship(key: string, typeClass: string, method: string): string; + /** + * `modelNameFromPayloadType` can be used to change the mapping for a DS model + * name, taken from the value in the payload. + */ + modelNameFromPayloadType(payloadType: string): string; + /** + * `payloadTypeFromModelName` can be used to change the mapping for the type in + * the payload, taken from the model name. + */ + payloadTypeFromModelName(modelname: string): string; + } + /** + * Ember Data 2.0 Serializer: + */ + class JSONSerializer extends Serializer { + /** + * The `primaryKey` is used when serializing and deserializing + * data. Ember Data always uses the `id` property to store the id of + * the record. The external source may not always follow this + * convention. In these cases it is useful to override the + * `primaryKey` property to match the `primaryKey` of your external + * store. + */ + primaryKey: string; + /** + * The `attrs` object can be used to declare a simple mapping between + * property names on `DS.Model` records and payload keys in the + * serialized JSON object representing the record. An object with the + * property `key` can also be used to designate the attribute's key on + * the response payload. + */ + attrs: {}; + /** + * The `normalizeResponse` method is used to normalize a payload from the + * server to a JSON-API Document. + */ + normalizeResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeQueryRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindAllResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindBelongsToResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindHasManyResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindManyResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeQueryResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeCreateRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeDeleteRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeUpdateRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeSaveResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeSingleResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeArrayResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + /** + * Normalizes a part of the JSON payload returned by + * the server. You should override this method, munge the hash + * and call super if you have generic normalization to do. + */ + normalize(typeClass: Model, hash: {}): {}; + /** + * Returns the resource's ID. + */ + extractId(modelClass: {}, resourceHash: {}): string; + /** + * Returns the resource's attributes formatted as a JSON-API "attributes object". + */ + extractAttributes(modelClass: {}, resourceHash: {}): {}; + /** + * Returns a relationship formatted as a JSON-API "relationship object". + */ + extractRelationship(relationshipModelName: {}, relationshipHash: {}): {}; + /** + * Returns a polymorphic relationship formatted as a JSON-API "relationship object". + */ + extractPolymorphicRelationship(relationshipModelName: {}, relationshipHash: {}, relationshipOptions: {}): {}; + /** + * Returns the resource's relationships formatted as a JSON-API "relationships object". + */ + extractRelationships(modelClass: {}, resourceHash: {}): {}; + modelNameFromPayloadKey(key: string): string; + /** + * Check if the given hasMany relationship should be serialized + */ + shouldSerializeHasMany(snapshot: Snapshot, key: string, relationshipType: string): boolean; + /** + * Called when a record is saved in order to convert the + * record into JSON. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * You can use this method to customize how a serialized record is added to the complete + * JSON hash to be sent to the server. By default the JSON Serializer does not namespace + * the payload and just sends the raw serialized JSON object. + * If your server expects namespaced keys, you should consider using the RESTSerializer. + * Otherwise you can override this method to customize how the record is added to the hash. + * The hash property should be modified by reference. + */ + serializeIntoHash(hash: {}, typeClass: Model, snapshot: Snapshot, options: {}): any; + /** + * `serializeAttribute` can be used to customize how `DS.attr` + * properties are serialized + */ + serializeAttribute(snapshot: Snapshot, json: {}, key: string, attribute: {}): any; + /** + * `serializeBelongsTo` can be used to customize how `DS.belongsTo` + * properties are serialized. + */ + serializeBelongsTo(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * `serializeHasMany` can be used to customize how `DS.hasMany` + * properties are serialized. + */ + serializeHasMany(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * You can use this method to customize how polymorphic objects are + * serialized. Objects are considered to be polymorphic if + * `{ polymorphic: true }` is pass as the second argument to the + * `DS.belongsTo` function. + */ + serializePolymorphicType(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * `extractMeta` is used to deserialize any meta information in the + * adapter payload. By default Ember Data expects meta information to + * be located on the `meta` property of the payload object. + */ + extractMeta(store: Store, modelClass: Model, payload: {}): any; + /** + * `extractErrors` is used to extract model errors when a call + * to `DS.Model#save` fails with an `InvalidError`. By default + * Ember Data expects error information to be located on the `errors` + * property of the payload object. + */ + extractErrors(store: Store, typeClass: Model, payload: {}, id: string|number): {}; + /** + * `keyForAttribute` can be used to define rules for how to convert an + * attribute name in your model to a key in your JSON. + */ + keyForAttribute(key: string, method: string): string; + /** + * `keyForRelationship` can be used to define a custom key when + * serializing and deserializing relationship properties. By default + * `JSONSerializer` does not provide an implementation of this method. + */ + keyForRelationship(key: string, typeClass: string, method: string): string; + /** + * `keyForLink` can be used to define a custom key when deserializing link + * properties. + */ + keyForLink(key: string, kind: string): string; + modelNameFromPayloadType(type: string): string; + /** + * serializeId can be used to customize how id is serialized + * For example, your server may expect integer datatype of id + */ + serializeId(snapshot: Snapshot, json: {}, primaryKey: string): any; + } + /** + * Normally, applications will use the `RESTSerializer` by implementing + * the `normalize` method. + */ + class RESTSerializer extends JSONSerializer { + /** + * `keyForPolymorphicType` can be used to define a custom key when + * serializing and deserializing a polymorphic type. By default, the + * returned key is `${key}Type`. + */ + keyForPolymorphicType(key: string, typeClass: string, method: string): string; + /** + * Normalizes a part of the JSON payload returned by + * the server. You should override this method, munge the hash + * and call super if you have generic normalization to do. + */ + normalize(modelClass: Model, resourceHash: {}, prop?: string): {}; + /** + * This method allows you to push a payload containing top-level + * collections of records organized per type. + */ + pushPayload(store: Store, payload: {}): any; + /** + * This method is used to convert each JSON root key in the payload + * into a modelName that it can use to look up the appropriate model for + * that part of the payload. + */ + modelNameFromPayloadKey(key: string): string; + /** + * Called when a record is saved in order to convert the + * record into JSON. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * You can use this method to customize the root keys serialized into the JSON. + * The hash property should be modified by reference (possibly using something like _.extend) + * By default the REST Serializer sends the modelName of a model, which is a camelized + * version of the name. + */ + serializeIntoHash(hash: {}, typeClass: Model, snapshot: Snapshot, options: {}): any; + /** + * You can use `payloadKeyFromModelName` to override the root key for an outgoing + * request. By default, the RESTSerializer returns a camelized version of the + * model's name. + */ + payloadKeyFromModelName(modelName: string): string; + /** + * You can use this method to customize how polymorphic objects are serialized. + * By default the REST Serializer creates the key by appending `Type` to + * the attribute and value from the model's camelcased model name. + */ + serializePolymorphicType(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * You can use this method to customize how a polymorphic relationship should + * be extracted. + */ + extractPolymorphicRelationship(relationshipType: {}, relationshipHash: {}, relationshipOptions: {}): {}; + /** + * `modelNameFromPayloadType` can be used to change the mapping for a DS model + * name, taken from the value in the payload. + */ + modelNameFromPayloadType(payloadType: string): string; + /** + * `payloadTypeFromModelName` can be used to change the mapping for the type in + * the payload, taken from the model name. + */ + payloadTypeFromModelName(modelName: string): string; + } + /** + * The `DS.BooleanTransform` class is used to serialize and deserialize + * boolean attributes on Ember Data record objects. This transform is + * used when `boolean` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. + */ + class BooleanTransform extends Transform { + } + /** + * The `DS.DateTransform` class is used to serialize and deserialize + * date attributes on Ember Data record objects. This transform is used + * when `date` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. It uses the [`ISO 8601`](https://en.wikipedia.org/wiki/ISO_8601) + * standard. + */ + class DateTransform extends Transform { + } + /** + * The `DS.NumberTransform` class is used to serialize and deserialize + * numeric attributes on Ember Data record objects. This transform is + * used when `number` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. + */ + class NumberTransform extends Transform { + } + /** + * The `DS.StringTransform` class is used to serialize and deserialize + * string attributes on Ember Data record objects. This transform is + * used when `string` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. + */ + class StringTransform extends Transform { + } + /** + * The `DS.Transform` class is used to serialize and deserialize model + * attributes when they are saved or loaded from an + * adapter. Subclassing `DS.Transform` is useful for creating custom + * attributes. All subclasses of `DS.Transform` must implement a + * `serialize` and a `deserialize` method. + */ + class Transform extends Ember.Object { + /** + * When given a deserialized value from a record attribute this + * method must return the serialized value. + */ + serialize(deserialized: any, options: AttrOptions): any; + /** + * When given a serialize value from a JSON object this method must + * return the deserialized value for the record attribute. + */ + deserialize(serialized: any, options: AttrOptions): any; + } + /** + * An adapter is an object that receives requests from a store and + * translates them into the appropriate action to take against your + * persistence layer. The persistence layer is usually an HTTP API, but + * may be anything, such as the browser's local storage. Typically the + * adapter is not invoked directly instead its functionality is accessed + * through the `store`. + */ + class Adapter extends Ember.Object { + /** + * If you would like your adapter to use a custom serializer you can + * set the `defaultSerializer` property to be the name of the custom + * serializer. + */ + defaultSerializer: string; + /** + * The `findRecord()` method is invoked when the store is asked for a record that + * has not previously been loaded. In response to `findRecord()` being called, you + * should query your persistence layer for a record with the given ID. The `findRecord` + * method should return a promise that will resolve to a JavaScript object that will be + * normalized by the serializer. + */ + findRecord(store: Store, type: Model, id: string, snapshot: Snapshot): Promise; + /** + * The `findAll()` method is used to retrieve all records for a given type. + */ + findAll(store: Store, type: Model, sinceToken: string, snapshotRecordArray: SnapshotRecordArray): Promise; + /** + * This method is called when you call `query` on the store. + */ + query(store: Store, type: Model, query: {}, recordArray: AdapterPopulatedRecordArray): Promise; + /** + * The `queryRecord()` method is invoked when the store is asked for a single + * record through a query object. + */ + queryRecord(store: Store, type: Model, query: {}): Promise; + /** + * If the globally unique IDs for your records should be generated on the client, + * implement the `generateIdForRecord()` method. This method will be invoked + * each time you create a new record, and the value returned from it will be + * assigned to the record's `primaryKey`. + */ + generateIdForRecord(store: Store, type: Model, inputProperties: {}): string|number; + /** + * Proxies to the serializer's `serialize` method. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * Implement this method in a subclass to handle the creation of + * new records. + */ + createRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Implement this method in a subclass to handle the updating of + * a record. + */ + updateRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Implement this method in a subclass to handle the deletion of + * a record. + */ + deleteRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * By default the store will try to coalesce all `fetchRecord` calls within the same runloop + * into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call. + * You can opt out of this behaviour by either not implementing the findMany hook or by setting + * coalesceFindRequests to false. + */ + coalesceFindRequests: boolean; + /** + * The store will call `findMany` instead of multiple `findRecord` + * requests to find multiple records at once if coalesceFindRequests + * is true. + */ + findMany(store: Store, type: Model, ids: any[], snapshots: any[]): Promise; + /** + * Organize records into groups, each of which is to be passed to separate + * calls to `findMany`. + */ + groupRecordsForFindMany(store: Store, snapshots: any[]): any[]; + /** + * This method is used by the store to determine if the store should + * reload a record from the adapter when a record is requested by + * `store.findRecord`. + */ + shouldReloadRecord(store: Store, snapshot: Snapshot): boolean; + /** + * This method is used by the store to determine if the store should + * reload all records from the adapter when records are requested by + * `store.findAll`. + */ + shouldReloadAll(store: Store, snapshotRecordArray: SnapshotRecordArray): boolean; + /** + * This method is used by the store to determine if the store should + * reload a record after the `store.findRecord` method resolves a + * cached record. + */ + shouldBackgroundReloadRecord(store: Store, snapshot: Snapshot): boolean; + /** + * This method is used by the store to determine if the store should + * reload a record array after the `store.findAll` method resolves + * with a cached record array. + */ + shouldBackgroundReloadAll(store: Store, snapshotRecordArray: SnapshotRecordArray): boolean; + } + /** + * `DS.Serializer` is an abstract base class that you should override in your + * application to customize it for your backend. The minimum set of methods + * that you should implement is: + */ + class Serializer extends Ember.Object { + /** + * The `store` property is the application's `store` that contains + * all records. It can be used to look up serializers for other model + * types that may be nested inside the payload response. + */ + store: Store; + /** + * The `normalizeResponse` method is used to normalize a payload from the + * server to a JSON-API Document. + */ + normalizeResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + /** + * The `serialize` method is used when a record is saved in order to convert + * the record into the form that your external data source expects. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * The `normalize` method is used to convert a payload received from your + * external data source into the normalized form `store.push()` expects. You + * should override this method, munge the hash and return the normalized + * payload. + */ + normalize(typeClass: Model, hash: {}): {}; + } +} +export default DS; + +declare module 'ember' { + namespace Ember { + /* + * The store is automatically injected into these objects + * + * https://github.com/emberjs/data/blob/05e95280e11c411177f2fbcb65fd83488d6a9d89/addon/setup-container.js#L71-L78 + */ + interface Route { + store: DS.Store; + } + interface Controller { + store: DS.Store; + } + interface DataAdapter { + store: DS.Store; + } + } +} diff --git a/types/ember-data/test/adapter.ts b/types/ember-data/test/adapter.ts new file mode 100644 index 0000000000..5d9d45fd4b --- /dev/null +++ b/types/ember-data/test/adapter.ts @@ -0,0 +1,56 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +const JsonApi = DS.JSONAPIAdapter.extend({ + // Application specific overrides go here +}); + +const Customized = DS.JSONAPIAdapter.extend({ + host: 'https://api.example.com', + namespace: 'api/v1', + headers: { + 'API_KEY': 'secret key', + 'ANOTHER_HEADER': 'Some header value' + } +}); + +const AuthTokenHeader = DS.JSONAPIAdapter.extend({ + session: Ember.inject.service('session'), + headers: Ember.computed('session.authToken', function() { + return { + 'API_KEY': this.get('session.authToken'), + 'ANOTHER_HEADER': 'Some header value' + }; + }) +}); + +const UseAjax = DS.JSONAPIAdapter.extend({ + query(store: DS.Store, type: string, query: object) { + const url = 'https://api.example.com/my-api'; + return this.ajax(url, 'POST', { + param: 'foo' + }); + } +}); + +const UseAjaxOptions = DS.JSONAPIAdapter.extend({ + query(store: DS.Store, type: string, query: object) { + const url = 'https://api.example.com/my-api'; + const options = this.ajaxOptions(url, 'DELETE', { + foo: 'bar' + }); + return Ember.$.ajax(url, { + ...options + }); + } +}); + +const UseAjaxOptionsWithOptionalThirdParams = DS.JSONAPIAdapter.extend({ + query(store: DS.Store, type: string, query: object) { + const url = 'https://api.example.com/my-api'; + const options = this.ajaxOptions(url, 'DELETE'); + return Ember.$.ajax(url, { + ...options + }); + } +}); diff --git a/types/ember-data/test/belongs-to.ts b/types/ember-data/test/belongs-to.ts new file mode 100644 index 0000000000..9e59aa6128 --- /dev/null +++ b/types/ember-data/test/belongs-to.ts @@ -0,0 +1,16 @@ +import DS from 'ember-data'; +import { assertType } from './lib/assert'; + +class Folder extends DS.Model { + name = DS.attr('string'); + children = DS.hasMany('folder', { inverse: 'parent' }); + parent = DS.belongsTo('folder', { inverse: 'children' }); +} + +const folder = Folder.create(); +assertType(folder.get('parent')); +assertType(folder.get('parent').get('name')); +folder.get('parent').then(parent => { + assertType(parent); + assertType(parent.get('name')); +}); diff --git a/types/ember-data/test/has-many.ts b/types/ember-data/test/has-many.ts new file mode 100644 index 0000000000..7fb586ff4a --- /dev/null +++ b/types/ember-data/test/has-many.ts @@ -0,0 +1,43 @@ +import DS from 'ember-data'; +import { assertType } from './lib/assert'; + +class Comment extends DS.Model { + text = DS.attr('string'); +} + +class BlogPost extends DS.Model { + title = DS.attr('string'); + commentsAsync = DS.hasMany('comment'); + commentsSync = DS.hasMany('comment', { async: false }); +} + +const post = BlogPost.create(); + +assertType>(post.get('commentsSync').reload()); +assertType(post.get('commentsSync').createRecord()); + +const comment = post.get('commentsSync').get('firstObject'); +assertType(comment); +if (comment) { + assertType(comment.get('text')); +} + +assertType>(post.get('commentsAsync').reload()); +assertType(post.get('commentsAsync').createRecord()); +assertType(post.get('commentsAsync').get('firstObject')); + +const commentAsync = post.get('commentsAsync').get('firstObject'); +assertType(commentAsync); +if (commentAsync) { + assertType(commentAsync.get('text')); +} +assertType(post.get('commentsAsync').get('isFulfilled')); + +post.get('commentsAsync').then(comments => { + assertType(comments.get('firstObject')); + assertType(comments.get('firstObject')!.get('text')); +}); + +class Polymorphic extends DS.Model { + paymentMethods = DS.hasMany('payment-method', { polymorphic: true }); +} diff --git a/types/ember-data/test/injections.ts b/types/ember-data/test/injections.ts new file mode 100644 index 0000000000..4c0a6e4e6b --- /dev/null +++ b/types/ember-data/test/injections.ts @@ -0,0 +1,22 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +Ember.Route.extend({ + model(): any { + return this.store.findAll('my-model'); + } +}); + +Ember.Controller.extend({ + actions: { + create(): any { + return this.store.createRecord('my-model'); + } + } +}); + +Ember.DataAdapter.extend({ + test() { + this.store.findRecord('my-model', 123); + } +}); diff --git a/types/ember-data/test/lib/assert.ts b/types/ember-data/test/lib/assert.ts new file mode 100644 index 0000000000..10094b9616 --- /dev/null +++ b/types/ember-data/test/lib/assert.ts @@ -0,0 +1,2 @@ +/** Static assertion that `value` has type `T` */ +export declare function assertType(value: T): void; diff --git a/types/ember-data/test/model.ts b/types/ember-data/test/model.ts new file mode 100644 index 0000000000..b3fa04e086 --- /dev/null +++ b/types/ember-data/test/model.ts @@ -0,0 +1,29 @@ +import Ember from 'ember'; +import DS from 'ember-data'; +import { assertType } from "./lib/assert"; + +const Person = DS.Model.extend({ + firstName: DS.attr(), + lastName: DS.attr(), + title: DS.attr({ defaultValue: "The default" }), + title2: DS.attr({ defaultValue: () => "The default" }), + + fullName: Ember.computed('firstName', 'lastName', function() { + return `${this.get('firstName')} ${this.get('lastName')}`; + }) +}); + +const User = DS.Model.extend({ + username: DS.attr('string'), + email: DS.attr('string'), + verified: DS.attr('boolean', { defaultValue: false }), + createdAt: DS.attr('date', { + defaultValue() { return new Date(); } + }) +}); + +const user = User.create({ username: 'dwickern' }); +assertType(user.get('id')); +assertType(user.get('username')); +assertType(user.get('verified')); +assertType(user.get('createdAt')); diff --git a/types/ember-data/test/record-reference.ts b/types/ember-data/test/record-reference.ts new file mode 100644 index 0000000000..bb4fda42d4 --- /dev/null +++ b/types/ember-data/test/record-reference.ts @@ -0,0 +1,38 @@ +import DS from 'ember-data'; +import { assertType } from "./lib/assert"; + +declare const store: DS.Store; + +class User extends DS.Model { + username = DS.attr('string'); +} + +let userRef = store.getReference('user', 1); + +// get the record of the reference (null if not yet available) +let user = userRef.value(); +if (user !== null) { + assertType(user); +} + +// get the identifier of the reference +if (userRef.remoteType() === 'id') { + let id = userRef.id(); + assertType(id); +} + +// load user (via store.find) +userRef.load().then(user => { + assertType(user); +}); + +// or trigger a reload +userRef.reload().then(user => { + assertType(user); +}); + +// provide data for reference +userRef.push({ id: 1, username: '@user' }).then(function(user) { + assertType(user); + userRef.value() === user; +}); diff --git a/types/ember-data/test/relationships.ts b/types/ember-data/test/relationships.ts new file mode 100644 index 0000000000..a878428bc4 --- /dev/null +++ b/types/ember-data/test/relationships.ts @@ -0,0 +1,30 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +declare const store: DS.Store; + +const Person = DS.Model.extend({ + children: DS.hasMany('folder', { inverse: 'parent' }), + parent: DS.belongsTo('folder', { inverse: 'children' }) +}); + +const Polymorphic = DS.Model.extend({ + paymentMethods: DS.hasMany('payment-method', { polymorphic: true }) +}); + +class Comment extends DS.Model { + author = DS.attr('string'); +} + +class BlogPost extends DS.Model { + title = DS.attr('string'); + tag = DS.attr('string'); + comments = DS.hasMany('comment', { async: true }); + relatedPosts = DS.hasMany('post'); +} + +let blogPost = store.peekRecord('blog-post', 1); +blogPost!.get('comments').then((comments) => { + // now we can work with the comments + let author: string = comments.get('firstObject')!.get('author'); +}); diff --git a/types/ember-data/test/serializer.ts b/types/ember-data/test/serializer.ts new file mode 100644 index 0000000000..986020144f --- /dev/null +++ b/types/ember-data/test/serializer.ts @@ -0,0 +1,38 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +const JsonApi = DS.JSONAPISerializer.extend({}); + +const Customized = DS.JSONAPISerializer.extend({ + serialize(snapshot: DS.Snapshot, options: {}) { + let json: any = this._super(...Array.from(arguments)); + + json.data.attributes.cost = { + amount: json.data.attributes.amount, + currency: json.data.attributes.currency + }; + + return json; + }, + normalizeResponse(store: DS.Store, primaryModelClass: DS.Model, payload: any, id: string|number, requestType: string) { + payload.data.attributes.amount = payload.data.attributes.cost.amount; + payload.data.attributes.currency = payload.data.attributes.cost.currency; + + delete payload.data.attributes.cost; + + return this._super(...Array.from(arguments)); + } +}); + +const EmbeddedRecordMixin = DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin, { + attrs: { + author: { + serialize: false, + deserialize: 'records' + }, + comments: { + deserialize: 'records', + serialize: 'ids' + } + } +}); diff --git a/types/ember-data/test/store.ts b/types/ember-data/test/store.ts new file mode 100644 index 0000000000..f7560a231f --- /dev/null +++ b/types/ember-data/test/store.ts @@ -0,0 +1,119 @@ +import Ember from 'ember'; +import DS from 'ember-data'; +import { assertType } from "./lib/assert"; + +declare const store: DS.Store; + +class Post extends DS.Model { + title = DS.attr('string'); +} + +let post = store.createRecord('post', { + title: 'Rails is Omakase', + body: 'Lorem ipsum' +}); + +post.save(); // => POST to '/posts' +post.save().then((saved) => { + assertType(saved); +}); + +store.findRecord('post', 1).then(function(post) { + post.get('title'); // => "Rails is Omakase" + post.set('title', 'A new post'); + post.save(); // => PATCH to '/posts/1' +}); + +class User extends DS.Model { + username = DS.attr('string'); +} + +store.queryRecord('user', {}).then(function(user) { + let username = user.get('username'); + console.log(`Currently logged in as ${username}`); +}); + +store.findAll('blog-post'); // => GET /blog-posts +store.findAll('author', { reload: true }).then(function(authors) { + authors.getEach('id'); // ['first', 'second'] +}); +store.findAll('post', { + adapterOptions: { subscribe: false } +}); +store.findAll('post', { include: 'comments,comments.author' }); + +store.peekAll('blog-post'); // => no network request + +if (store.hasRecordForId('post', 1)) { + let maybePost = store.peekRecord('post', 1); + if (maybePost) { + maybePost.get('id'); // 1 + } +} + +class Message extends DS.Model { + hasBeenSeen = DS.attr('boolean'); +} + +const messages = store.peekAll('message'); +messages.forEach(function(message) { + message.set('hasBeenSeen', true); +}); +messages.save(); + +const people = store.peekAll('person'); +people.get('isUpdating'); // false +people.update().then(function() { + people.get('isUpdating'); // false +}); +people.get('isUpdating'); // true + +const MyRoute = Ember.Route.extend({ + model(params: any): any { + return this.store.findRecord('post', params.post_id, {include: 'comments,comments.author'}); + } +}); + +// GET to /users?filter[email]=tomster@example.com +const tom = store.query('user', { + filter: { + email: 'tomster@example.com' + } +}).then(function(users) { + return users.get("firstObject"); +}); + +// GET /users?isAdmin=true +const admins = store.query('user', { isAdmin: true }); +admins.then(function() { + console.log(admins.get("length")); // 42 +}); +admins.update().then(function() { + admins.get('isUpdating'); // false + console.log(admins.get("length")); // 123 +}); + +store.push({ + data: [{ + id: 1, + type: 'album', + attributes: { + title: 'Fewer Moving Parts', + artist: 'David Bazan', + songCount: 10 + }, + relationships: {} + }, { + id: 2, + type: 'album', + attributes: { + title: 'Calgary b/w I Can\'t Make You Love Me/Nick Of Time', + artist: 'Bon Iver', + songCount: 2 + }, + relationships: {} + }] +}); + +assertType(store.adapterFor('person')); +assertType(store.serializerFor('person')); diff --git a/types/ember-data/test/transform.ts b/types/ember-data/test/transform.ts new file mode 100644 index 0000000000..b76d40a73f --- /dev/null +++ b/types/ember-data/test/transform.ts @@ -0,0 +1,16 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +class Point extends Ember.Object { + x: number; + y: number; +} + +const PointTransform = DS.Transform.extend({ + serialize(value: Point): number[] { + return [value.get('x'), value.get('y')]; + }, + deserialize(value: [ number, number ]): Point { + return Point.create({ x: value[0], y: value[1] }); + } +}); diff --git a/types/ember-data/tsconfig.json b/types/ember-data/tsconfig.json new file mode 100644 index 0000000000..155515ac6b --- /dev/null +++ b/types/ember-data/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "test/lib/assert.ts", + "test/model.ts", + "test/adapter.ts", + "test/serializer.ts", + "test/transform.ts", + "test/relationships.ts", + "test/store.ts", + "test/has-many.ts", + "test/belongs-to.ts", + "test/record-reference.ts", + "test/injections.ts" + ] +} diff --git a/types/ember-data/tslint.json b/types/ember-data/tslint.json new file mode 100644 index 0000000000..dd3a7f529c --- /dev/null +++ b/types/ember-data/tslint.json @@ -0,0 +1,16 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // Heavy use of Function type in this older package. + "ban-types": false, + "jsdoc-format": false, + "no-misused-new": false, + // not sure what this means + "no-single-declare-module": false, + "object-literal-key-quotes": false, + "only-arrow-functions": false, + "no-empty-interface": false, + "prefer-const": false, + "no-unnecessary-generics": false + } +} diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index bb6cce8b36..adef4e70c2 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -558,6 +558,8 @@ declare module 'ember' { **/ interface ArrayProxy extends MutableArray {} class ArrayProxy extends Object.extend(MutableArray as {}) { + content: NativeArray; + /** * Should actually retrieve the object at the specified index from the * content. You can override this method in subclasses to transform the @@ -1837,7 +1839,7 @@ declare module 'ember' { * A hook you can implement to convert the URL into the model for * this route. */ - model(params: {}, transition: Transition): T | Rsvp.Promise; + model(params: {}, transition: Transition): any; /** * Returns the model of a parent (or any ancestor) route diff --git a/types/ember/test/array-proxy.ts b/types/ember/test/array-proxy.ts old mode 100755 new mode 100644 index 763034bbd0..dceea7b847 --- a/types/ember/test/array-proxy.ts +++ b/types/ember/test/array-proxy.ts @@ -21,7 +21,6 @@ class MyNewProxy extends Ember.ArrayProxy { isNew = true; } -let x = MyNewProxy.create({ content: Ember.A([1, 2, 3]) }); -// TODO: type inference can't infer 'number', just '{}' -// x.get('firstObject'); // $ExpectType number | undefined -x.isNew; // $ExpectType boolean +let x = MyNewProxy.create({ content: Ember.A([1, 2, 3]) }) as MyNewProxy; +assertType(x.get('firstObject')); +assertType(x.isNew); diff --git a/types/enigma.js/enigma.js-tests.ts b/types/enigma.js/enigma.js-tests.ts new file mode 100644 index 0000000000..10f6aae226 --- /dev/null +++ b/types/enigma.js/enigma.js-tests.ts @@ -0,0 +1,10 @@ +import * as enigma from "enigma.js"; +// import enigma = require("enigma.js"); + +const config: enigmaJS.IConfig = { + url: "http://127.0.0.1:4848/", + schema: {} + }; +enigma.create(config).open().then((global) => { + console.log("connect fine"); +}); diff --git a/types/enigma.js/index.d.ts b/types/enigma.js/index.d.ts new file mode 100644 index 0000000000..38fc18da16 --- /dev/null +++ b/types/enigma.js/index.d.ts @@ -0,0 +1,194 @@ +// Type definitions for enigma.js 2.2 +// Project: https://github.com/qlik-oss/enigma.js/ +// Definitions by: Konrad Mattheis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +declare module "enigma.js" { + const e: IEnigmaClass; + export = e; +} + +// declare const enigmaJS: IEnigmaClass; +// export = enigmaJS; +// export as namespace enigmaJS; + +interface IEnigmaClass { + /** + * Create a session object. + * @returns - Returns a session. + * Note: See Configuration for the configuration options. + */ + create(config: enigmaJS.IConfig): enigmaJS.ISession; +} + +declare namespace enigmaJS { + type MixinType = "Doc"| "GenericObject"| "GenericBookmark" | string; + + interface IMixin { + /** + * QIX Engine types like for example GenericObject, Doc, GenericBookmark, are supported but also custom GenericObject + * types such as barchart, story and myCustomType. + * An API will get both their generic type as well as custom type mixins applied. + */ + types: MixinType[]; + + init(args: {config: any, api: IGeneratedAPI}): void; + + /** + * mixin.extend is an object containing methods to extend the generated API with. These method names cannot already exist or enigma.js will throw an error. + */ + extend?: [any]; + + /** + * mixin.override is an object containing methods that overrides existing API methods. + * These method names needs to exist already* or engima.js will throw an error. + * Be careful when overriding, you may break expected behaviors in other mixins or your application. + * base is a reference to the previous mixin method, can be used to invoke the mixin chain before this mixin method. + */ + override?: [any]; + } + + interface IProtocol { + // Set to false to disable the use of the bandwidth-reducing delta protocol. + delta?: boolean; + } + + /** + * This section describes the configuration object that is sent into enigma.create(config). + */ + interface IConfig { + /** + * Object containing the specification for the API to generate. Corresponds to a specific version of the QIX Engine API. + */ + schema: object; + /** + * String containing a proper websocket URL to QIX Engine. + */ + url: string; + /** + * A function to use when instantiating the WebSocket, mandatory for Node.js. + */ + createSocket?: any; + /** + * ES6-compatible Promise library. + */ + Promise?: any; + /** + * Set to true if the session should be suspended instead of closed when the websocket is closed. + */ + suspendOnClose?: boolean; + /** + * Mixins to extend/augment the QIX Engine API. + * See Mixins section for more information how each entry in this array should look like. + * Mixins are applied in the array order. + */ + mixins?: [any]; + /** + * Interceptors for augmenting responses before they are passed into mixins and end-users. + * See Interceptors section for more information how each entry in this array should look like. + * Interceptors are applied in the array order. + */ + interceptors?: [any]; + /** + * An object containing additional JSON-RPC request parameters. + * protocol.delta : Set to false to disable the use of the bandwidth-reducing delta protocol. + */ + protocol?: any; + } + + interface ISession { + /** + * Establishes the websocket against the configured URL. Eventually resolved with the QIX global interface when the connection has been established. + * @return Promise. + */ + open(): Promise; + + /** + * Closes the websocket and cleans up internal caches, also triggers the closed event on all generated APIs. + * Eventually resolved when the websocket has been closed. + * + * Note: you need to manually invoke this when you want to close a session and config.suspendOnClose is true. + * @return Promise. + */ + close(): Promise; + + /** + * Suspends the enigma.js session by closing the websocket and rejecting all method calls until it has been resumed again. + * @return Promise. + */ + suspend(): Promise; + + /** + * Resume a previously suspended enigma.js session by re-creating the websocket and, if possible, re-open the document + * as well as refreshing the internal caches. If successful, changed events will be triggered on all generated APIs, + * and on the ones it was unable to restore, the closed event will be triggered. + * @param onlyIfAttached onlyIfAttached can be used to only allow resuming if the QIX Engine session was reattached properly. + * @return Promise. + * Note: Eventually resolved when the websocket (and potentially the previously opened document, and generated APIs) has been restored, + * rejected when it fails any of those steps, or when onlyIfAttached is true and a new QIX Engine session was created. + */ + resume(onlyIfAttached?: boolean): Promise; + + /** + * Handle opened state. This event is triggered whenever the websocket is connected and ready for communication. + * + * Handle closed state. This event is triggered when the underlying websocket is closed and config.suspendOnClose is false. + * + * Handle suspended state. This event is triggered in two cases (listed below). It is useful in scenarios where you for example + * want to block interaction in your application until you are resumed again. + * If config.suspendOnClose is true and there was a network disconnect (socked closed) + * If you ran session.suspend() + * The evt.initiator value is a string indicating what triggered the suspended state. Possible values: network, manual. + * + * Handle resumed state. This event is triggered when the session was properly resumed. + * It is useful in scenarios where you for example can close blocking modal dialogs and allow the user to interact with your application again. + * + * notification:* + * @param event - Event that triggers the function + * @param func - Called function + */ + on(event: "opened" | "close" | "suspended" | "resumed" | string, func: any): void; + } + + interface IGeneratedAPI { + /** + * This property contains the unique identifier for this API. + */ + id: string; + + /** + * This property contains the schema class name for this API. + */ + type: string; + + /** + * Despite the name, this property corresponds to the qInfo.qType property on your generic object's properties object. + */ + genericType: string; + + /** + * This property contains a reference to the session that this API belongs to. + */ + session: ISession; + + /** + * This property contains the handle QIX Engine assigned to the API. + * Used internally in enigma.js for caches and JSON-RPC + */ + handle: number; + + /** + * register a function for events + * @param event - function called if this event occures + * @param func - function that is called + */ + on(event: "changed" | "closed", func: () => void): void; + + /** + * manual emit an events + * @param event - event that occures + */ + emit(event: "changed" | "closed"): void; + } +} diff --git a/types/enigma.js/tsconfig.json b/types/enigma.js/tsconfig.json new file mode 100644 index 0000000000..b3b93456f0 --- /dev/null +++ b/types/enigma.js/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "enigma.js-tests.ts" + ] +} \ No newline at end of file diff --git a/types/enigma.js/tslint.json b/types/enigma.js/tslint.json new file mode 100644 index 0000000000..84cbb5f289 --- /dev/null +++ b/types/enigma.js/tslint.json @@ -0,0 +1,13 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "ban-types": false, + "no-empty-interface": false, + "no-mergeable-namespace": false, + "no-unnecessary-generics": false, + "no-single-declare-module": false, + "no-declare-current-package": false, + "interface-name": false + } +} diff --git a/types/enzyme/enzyme-tests.tsx b/types/enzyme/enzyme-tests.tsx index 63e716c50b..c48c050357 100644 --- a/types/enzyme/enzyme-tests.tsx +++ b/types/enzyme/enzyme-tests.tsx @@ -1,5 +1,14 @@ import * as React from "react"; -import { shallow, mount, render, ShallowWrapper, ReactWrapper } from "enzyme"; +import { + shallow, + mount, + render, + ShallowWrapper, + ReactWrapper, + configure, + EnzymeAdapter, + ShallowRendererProps, +} from "enzyme"; import { Component, ReactElement, HTMLAttributes, ComponentClass, StatelessComponent } from "react"; // Help classes/interfaces @@ -24,6 +33,18 @@ class MyComponent extends Component { const MyStatelessComponent = (props: StatelessProps) => ; +// Enzyme.configure +function configureTest() { + const configureAdapter: { adapter: EnzymeAdapter } = { adapter: {} }; + configure(configureAdapter); + + const configureAdapterAndDisableLifecycle: typeof configureAdapter & Pick = { + adapter: {}, + disableLifecycleMethods: true, + }; + configure(configureAdapterAndDisableLifecycle); +} + // ShallowWrapper function ShallowWrapperTest() { let shallowWrapper: ShallowWrapper = @@ -50,7 +71,8 @@ function ShallowWrapperTest() { context: { test: "a", }, - lifecycleExperimental: true + lifecycleExperimental: true, + disableLifecycleMethods: true }); } diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index bfd714fd22..3a8ea149f9 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -551,6 +551,12 @@ export class ReactWrapper

{ } export interface ShallowRendererProps { + // See https://github.com/airbnb/enzyme/blob/enzyme@3.1.1/docs/api/shallow.md#arguments + /** + * If set to true, componentDidMount is not called on the component, and componentDidUpdate is not called after + * setProps and setContext. Default to false. + */ + disableLifecycleMethods?: boolean; /** * Enable experimental support for full react lifecycle methods */ @@ -602,4 +608,14 @@ export class EnzymeAdapter { * Configure enzyme to use the correct adapter for the react verstion * This is enabling the Enzyme configuration with adapters in TS */ -export function configure(options: { adapter: EnzymeAdapter }): void; +export function configure(options: { + adapter: EnzymeAdapter, + // See https://github.com/airbnb/enzyme/blob/enzyme@3.1.1/docs/guides/migration-from-2-to-3.md#lifecycle-methods + // Actually, `{adapter:} & Pick` is more precise. However, + // in that case jsdoc won't be shown + /** + * If set to true, componentDidMount is not called on the component, and componentDidUpdate is not called after + * setProps and setContext. Default to false. + */ + disableLifecycleMethods?: boolean; +}): void; diff --git a/types/epilogue/epilogue-tests.ts b/types/epilogue/epilogue-tests.ts new file mode 100644 index 0000000000..0cf40fd1e9 --- /dev/null +++ b/types/epilogue/epilogue-tests.ts @@ -0,0 +1,33 @@ +import * as epilogue from 'epilogue'; +import * as express from 'express'; +import * as Sequelize from 'sequelize'; + +const database = new Sequelize({ }); + +epilogue.initialize({ + app: express(), + sequelize: database +}); + +epilogue.initialize({ + app: express(), + sequelize: database, + base: '' +}); + +epilogue.initialize({ + app: express(), + sequelize: database, + base: '', + updateMethod: '' +}); + +const User = database.define('User', { + username: Sequelize.STRING, + birthday: Sequelize.DATE +}); + +epilogue.resource({ + model: User, + endpoints: ['/users', '/users/:id'] +}); diff --git a/types/epilogue/index.d.ts b/types/epilogue/index.d.ts new file mode 100644 index 0000000000..3fe56b9e9f --- /dev/null +++ b/types/epilogue/index.d.ts @@ -0,0 +1,199 @@ +// Type definitions for epilogue 0.7 +// Project: https://github.com/dchester/epilogue +// Definitions by: Satana Charuwichitratana +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { + Sequelize, + AssociationOptions, + DataTypeAbstract, + DataTypeString, + DataTypeChar, + DataTypeText, + DataTypeNumber, + DataTypeInteger, + DataTypeBigInt, + DataTypeFloat, + DataTypeTime, + DataTypeDate, + DataTypeDateOnly, + DataTypeBoolean, + DataTypeNow, + DataTypeBlob, + DataTypeDecimal, + DataTypeUUID, + DataTypeUUIDv1, + DataTypeUUIDv4, + DataTypeHStore, + DataTypeJSONType, + DataTypeJSONB, + DataTypeVirtual, + DataTypeArray, + DataTypeEnum, + DataTypeRange, + DataTypeReal, + DataTypeDouble, + DataTypeGeometry +} from 'sequelize'; + +import { Express, Request, Response } from 'express'; + +export class Endpoint { + constructor(endpoint: string); + string: string; + attributes: string[]; +} + +export class Resource { + constructor(options: ResourceOptions); + app: Express; + sequelize: Sequelize; + model: any; + include: Array<{ model: any } | string>; + associationOptions: ResourceAssociationOptions; + readOnlyAttributes: string[]; + excludeAttributes: string[]; + attributes: string[]; + actions: string[]; + endpoints: { + singular: string; + plural: string; + }; + updateMethod: string; + pagination: boolean; + search: ResourceSearchOption; + sort: ResourceSortOption; + reloadInstances: boolean; + controllers: Controllers; +} + +export interface Controllers { + base: BaseController; + create: CreateController; + read: ReadController; + update: UpdateController; + delete: DeleteController; + list: ListController; +} + +export namespace Errors { + class EpilogueError extends Error { + constructor(status: number | EpilogueError, message?: string, errors?: string[], cause?: Error); + + name: string; + message: string; + errors: string[]; + status: number | EpilogueError; + cause: Error; + } + + class NotFoundError extends EpilogueError { + constructor(message?: string, errors?: string[], cause?: Error); + } + + class BadRequestError extends EpilogueError { + constructor(message?: string, errors?: string[], cause?: Error); + } + + class ForbiddenError extends EpilogueError { + constructor(message?: string, errors?: string[], cause?: Error); + } + + class RequestCompleted extends Error { + constructor(); + } +} + +export interface ResourceAssociationOptions extends AssociationOptions { + removeForeignKeys: boolean; +} + +export interface ResourceSearchOption { + param: string; + operator: string; + attributes: string[]; +} + +export interface ResourceSortOption { + param: string; + default: string; +} + +export interface InitializeOptions { + app: Express; + sequelize: Sequelize; + base?: string; + updateMethod?: string; +} + +export interface BaseContollerOptions { + endpoint: string; + model: any; + app: Express; + resource: Resource; + include: Array<{ model: any } | string>; +} + +export interface Context { + instance: Resource; + criteria: any; + attributes: any; + options: any; + continue: () => void; + skip: () => void; + stop: () => void; + error: (status: number | Errors.EpilogueError, message?: string, errorList?: string[], cause?: Error) => void; +} + +export class BaseController { + constructor(options: BaseContollerOptions); + endpoint: Endpoint; + model: any; +} + +export class CreateController extends BaseController { + write: (req: Request, res: Response, context: Context) => Promise<() => void>; +} + +export class ReadController extends BaseController { + fetch: (req: Request, res: Response, context: Context) => Promise<() => void>; +} + +export class UpdateController extends BaseController { + fetch: (req: Request, res: Response, context: Context) => Promise<() => void>; + write: (req: Request, res: Response, context: Context) => Promise<() => void>; +} + +export class DeleteController extends BaseController { + fetch: (req: Request, res: Response, context: Context) => Promise<() => void>; + write: (req: Request, res: Response, context: Context) => Promise<() => void>; +} + +export class ListController extends BaseController { + fetch: (req: Request, res: Response, context: Context) => Promise<() => void>; + _safeishParse: (value: any, type: DataTypeAbstract | DataTypeString | DataTypeChar | DataTypeText | DataTypeNumber | + DataTypeInteger | DataTypeBigInt | DataTypeFloat | DataTypeTime | DataTypeDate | DataTypeDateOnly | + DataTypeBoolean | DataTypeNow | DataTypeBlob | DataTypeDecimal | DataTypeUUID | DataTypeUUIDv1 | + DataTypeUUIDv4 | DataTypeHStore | DataTypeJSONType | DataTypeJSONB | DataTypeVirtual | + DataTypeArray | DataTypeEnum | DataTypeRange | DataTypeReal | DataTypeDouble | DataTypeGeometry, + sequelize: Sequelize) => any; +} + +export interface ResourceOptions { + model: any; + endpoints: string[]; + actions?: string[]; + include?: Array<{ model: any } | string>; + pagination?: boolean; + search?: ResourceSearchOption; + sort?: ResourceSortOption; + reloadInstances?: boolean; + associations?: AssociationOptions; + excludeAttributes?: string[]; + readOnlyAttributes?: string[]; + updateMethod?: string; +} + +export function initialize(options?: InitializeOptions): void; +export function resource(options?: ResourceOptions): Resource; diff --git a/types/epilogue/tsconfig.json b/types/epilogue/tsconfig.json new file mode 100644 index 0000000000..593077c6bc --- /dev/null +++ b/types/epilogue/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "epilogue-tests.ts" + ] +} diff --git a/types/epilogue/tslint.json b/types/epilogue/tslint.json new file mode 100644 index 0000000000..10d875b8db --- /dev/null +++ b/types/epilogue/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/error-stack-parser/error-stack-parser-tests.ts b/types/error-stack-parser/error-stack-parser-tests.ts deleted file mode 100644 index c8b9198261..0000000000 --- a/types/error-stack-parser/error-stack-parser-tests.ts +++ /dev/null @@ -1,3 +0,0 @@ - - -ErrorStackParser.parse(new Error('Boom')); diff --git a/types/error-stack-parser/index.d.ts b/types/error-stack-parser/index.d.ts deleted file mode 100644 index ad722b0f2b..0000000000 --- a/types/error-stack-parser/index.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Type definitions for ErrorStackParser v1.3.3 -// Project: https://github.com/stacktracejs/error-stack-parser -// Definitions by: Eric Wendelin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module ErrorStackParser { - export interface StackFrame { - constructor(functionName: string, args: any, fileName: string, lineNumber: number, columnNumber: number, source: string): StackFrame; - - functionName?: string; - args?: any[]; - fileName?: string; - lineNumber?: number; - columnNumber?: number; - source?: string; - toString(): string; - } - - /** - * Given an Error object, extract the most information from it. - * - * @param {Error} error object - * @return {Array} of StackFrames - */ - export function parse(error: Error): StackFrame[]; -} diff --git a/types/error-stack-parser/tslint.json b/types/error-stack-parser/tslint.json deleted file mode 100644 index a41bf5d19a..0000000000 --- a/types/error-stack-parser/tslint.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} diff --git a/types/execa/index.d.ts b/types/execa/index.d.ts index 84c6939798..ee33bea59e 100644 --- a/types/execa/index.d.ts +++ b/types/execa/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for execa 0.7 +// Type definitions for execa 0.8 // Project: https://github.com/sindresorhus/execa#readme // Definitions by: Douglas Duteil // BendingBender +// Borek Bernard // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -10,46 +11,46 @@ 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; - code: number; - failed: boolean; - killed: boolean; - signal: string | null; - stderr: string; - stdout: string; - timedOut: boolean; -} - -type ExecaError = Error & ExecaReturns; - -interface ExecaChildPromise { - catch(onrejected?: ((reason: ExecaError) => TResult | PromiseLike) | null): Promise; -} -type ExecaChildProcess = ChildProcess & ExecaChildPromise & Promise; - -declare function execa(file: string, options?: Partial): ExecaChildProcess; -declare function execa(file: string, args?: string[], options?: Partial): ExecaChildProcess; +declare function execa(file: string, options?: Partial): execa.ExecaChildProcess; +declare function execa(file: string, args?: string[], options?: Partial): execa.ExecaChildProcess; declare namespace execa { + 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; + code: number; + failed: boolean; + killed: boolean; + signal: string | null; + stderr: string; + stdout: string; + timedOut: boolean; + } + + type ExecaError = Error & ExecaReturns; + + interface ExecaChildPromise { + catch(onrejected?: ((reason: ExecaError) => TResult | PromiseLike) | null): Promise; + } + type ExecaChildProcess = ChildProcess & ExecaChildPromise & Promise; + function stdout(file: string, options?: Partial): Promise; function stdout(file: string, args?: string[], options?: Partial): Promise; function stderr(file: string, options?: Partial): Promise; diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx new file mode 100644 index 0000000000..333b9d3e3c --- /dev/null +++ b/types/expo/expo-tests.tsx @@ -0,0 +1,203 @@ +import * as React from 'react'; + +import { + Accelerometer, + Amplitude, + Asset, + AuthSession, + Audio, + AppLoading, + BarCodeScanner, + BlurViewProps, + BlurView, + Brightness, + Camera, + DocumentPicker, + Facebook, + FacebookAds, + FileSystem +} from 'expo'; + +Accelerometer.addListener((obj) => { + obj.x; + obj.y; + obj.z; +}); +Accelerometer.removeAllListeners(); +Accelerometer.setUpdateInterval(1000); + +Amplitude.initialize('key'); +Amplitude.setUserId('userId'); +Amplitude.setUserProperties({key: 1}); +Amplitude.clearUserProperties(); +Amplitude.logEvent('name'); +Amplitude.logEventWithProperties('event', {key: 'value'}); +Amplitude.setGroup('type', {key: 'value'}); + +const asset = Asset.fromModule(1); +asset.downloadAsync(); +Asset.loadAsync(1); +Asset.loadAsync([1, 2, 3]); +const asset1 = new Asset({ + uri: 'uri', + type: 'type', + name: 'name', + hash: 'hash', + width: 122, + height: 122 +}); + +const url = AuthSession.getRedirectUrl(); +AuthSession.dismiss(); +AuthSession.startAsync({ + authUrl: 'url1', + returnUrl: 'url2' +}).then(result => { + switch (result.type) { + case 'success': + result.event; + result.params; + break; + case 'error': + result.errorCode; + result.params; + result.event; + break; + case 'dismissed': + case 'cancel': + result.type; + break; + } +}); + +Audio.setAudioModeAsync({ + shouldDuckAndroid: false, + playsInSilentModeIOS: true, + interruptionModeIOS: 2, + interruptionModeAndroid: 1, + allowsRecordingIOS: true +}); +Audio.setIsEnabledAsync(true); +async () => { + const result = await Audio.Sound.create('uri', { + volume: 0.5, + rate: 0.6 + }, null, true); + + const sound = result.sound; + const status = result.status; + + if (!status.isLoaded) { + status.error; + } else { + status.didJustFinish; + // etc. + } + + const _status = await sound.getStatusAsync(); + await sound.loadAsync('uri'); +}; + +() => ( + Promise.resolve()} + onFinish={() => {}} + onError={(error) => console.log(error)} /> +); +() => ( + +); + +const barcodeReadCallback = () => {}; +() => ( + +); + +() => ( + +); + +async () => { + await Brightness.setBrightnessAsync(.6); + await Brightness.setSystemBrightnessAsync(.7); + const br1 = await Brightness.getBrightnessAsync(); + const br2 = await Brightness.getSystemBrightnessAsync(); +}; + +Camera.Constants.AutoFocus; +Camera.Constants.Type; +Camera.Constants.FlashMode; +Camera.Constants.WhiteBalance; +Camera.Constants.VideoQuality; +Camera.Constants.BarCodeType; +() => { + return( { + if (component) { + component.recordAsync(); + } + }} />); +}; + +async () => { + const result = await DocumentPicker.getDocumentAsync(); + + if (result.type === 'success') { + result.name; + result.uri; + result.size; + } +}; + +async () => { + const result = await Facebook.logInWithReadPermissionsAsync('appId'); + + if (result.type === 'success') { + result.expires; + result.token; + } +}; + +() => ( + {}} + onError={() => {}} /> +); + +async () => { + const info = await FileSystem.getInfoAsync('file'); + + info.exists; + info.isDirectory; + + if (info.exists) { + info.md5; + info.uri; + info.size; + info.modificationTime; + } + + const string: string = await FileSystem.readAsStringAsync('file'); + await FileSystem.writeAsStringAsync('file', 'content'); + await FileSystem.deleteAsync('file'); + await FileSystem.moveAsync({ from: 'from', to: 'to'}); + await FileSystem.copyAsync({ from: 'from', to: 'to' }); + await FileSystem.makeDirectoryAsync('dir'); + const dirs: string[] = await FileSystem.readDirectoryAsync('dir'); + const result = await FileSystem.downloadAsync('from', 'to'); + + result.headers; + result.status; + result.uri; + result.md5; +}; diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts new file mode 100644 index 0000000000..04d500ab6b --- /dev/null +++ b/types/expo/index.d.ts @@ -0,0 +1,1481 @@ +// Type definitions for expo 23.0 +// Project: https://github.com/expo/expo-sdk +// Definitions by: Konstantin Kai +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { EventSubscription } from 'fbemitter'; +import { Component, Ref } from 'react'; +import { + ViewStyle, + ViewProperties, + ColorPropType, + ImageURISource, + NativeEventEmitter, + ImageRequireSource +} from 'react-native'; + +export type URISource = ImageURISource; +export type RequireSource = ImageRequireSource; +export type ResizeModeContain = 'contain'; +export type ResizeModeCover = 'cover'; +export type ResizeModeStretch = 'stretch'; +export type Orientation = 'portrait' | 'landscape'; +export type Axis = number; +export interface HashMap { [key: string]: any; } +export type FloatFromZeroToOne = 0 | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1; +export type BarCodeReadCallback = (params: { type: string; data: string; }) => void; +export type Md5 = string; + +/** + * Accelerometer + */ +export namespace Accelerometer { + interface AccelerometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: AccelerometerObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Amplitude + */ +export namespace Amplitude { + function initialize(apiKey: string): void; + function setUserId(userId: string): void; + function setUserProperties(userProperties: HashMap): void; + function clearUserProperties(): void; + function logEvent(eventName: string): void; + function logEventWithProperties(eventName: string, properties: HashMap): void; + function setGroup(groupType: string, groupNames: HashMap): void; +} + +/** + * Asset + */ +export class Asset { + constructor({ name, type, hash, uri, width, height }: { + name: string; + type: string; + hash: string; + uri: string; + width?: number; + height?: number; + }); + name: string; + type: string; + hash: string; + uri: string; + localUri: string; + width?: number; + height?: number; + + downloading: boolean; + downloaded: boolean; + downloadCallbacks: Array<{ resolve: () => any, reject: (e?: any) => any }>; + + downloadAsync(): Promise; + + static fromModule(module: RequireSource): Asset; + static loadAsync(module: RequireSource[] | RequireSource): Promise; +} + +/** + * AuthSession + */ +export namespace AuthSession { + function startAsync(options: { authUrl: string; returnUrl: string; }): Promise<{ + type: 'cancel'; + } | { + type: 'dismissed'; + } | { + type: 'success'; + params: HashMap; + event: HashMap; + } | { + type: 'error'; + params: HashMap; + errorCode: string; + event: HashMap; + }>; + function dismiss(): void; + function getRedirectUrl(): string; +} + +/** + * AV + */ +export type PlaybackStatus = { + isLoaded: false; + androidImplementation?: string; + error?: string; +} | { + isLoaded: true; + androidImplementation?: string; + uri: string; + progressUpdateIntervalMillis: number; + durationMillis?: number; + positionMillis: number; + playableDurationMillis?: number; + shouldPlay: boolean; + isPlaying: boolean; + isBuffering: boolean; + rate: number; + shouldCorrectPitch: boolean; + volume: number; + isMuted: boolean; + isLooping: boolean; + didJustFinish: boolean; +}; + +export interface PlaybackStatusToSet { + androidImplementation?: string; + progressUpdateIntervalMillis?: number; + positionMillis?: number; + shouldPlay?: boolean; + rate?: FloatFromZeroToOne; + shouldCorrectPitch?: boolean; + volume?: FloatFromZeroToOne; + isMuted?: boolean; + isLooping?: boolean; +} + +export type Source = string | RequireSource | Asset; + +export class PlaybackObject { + loadAsync(source: Source, initialStatus?: PlaybackStatusToSet, downloadFirst?: boolean): Promise; + unloadAsync(): Promise; + getStatusAsync(): Promise; + setOnPlaybackStatusUpdate(onPlaybackStatusUpdate: (status: PlaybackStatus) => void): void; + setStatusAsync(status: PlaybackStatusToSet): Promise; + playAsync(): Promise; + playFromPositionAsync(positionMillis: number): Promise; + pauseAsync(): Promise; + stopAsync(): Promise; + setPositionAsync(positionMillis: number): Promise; + setRateAsync(rate: number, shouldCorrectPitch: boolean): Promise; + setVolumeAsync(volume: number): Promise; + setIsMutedAsync(isMuted: boolean): Promise; + setIsLoopingAsync(isLooping: boolean): Promise; + setProgressUpdateIntervalAsync(progressUpdateIntervalMillis: number): Promise; +} + +export namespace Audio { + enum InterruptionModeIOS { + INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS = 0, + INTERRUPTION_MODE_IOS_DO_NOT_MIX = 1, + INTERRUPTION_MODE_IOS_DUCK_OTHERS = 2 + } + + enum InterruptionModeAndroid { + INTERRUPTION_MODE_ANDROID_DO_NOT_MIX = 1, + INTERRUPTION_MODE_ANDROID_DUCK_OTHERS = 2 + } + + type RecordingStatus = { + canRecord: false, + isDoneRecording: false + } | { + canRecord: true, + isRecording: boolean, + durationMillis: number + } | { + canRecord: false, + isDoneRecording: true, + durationMillis: number + }; + + interface AudioMode { + playsInSilentModeIOS: boolean; + allowsRecordingIOS: boolean; + interruptionModeIOS: InterruptionModeIOS; + shouldDuckAndroid: boolean; + interruptionModeAndroid: InterruptionModeAndroid; + } + + function setIsEnabledAsync(value: boolean): Promise; + function setAudioModeAsync(mode: AudioMode): Promise; + + class Sound extends PlaybackObject { + constructor(); + + static create( + source: Source, + initialStatus?: PlaybackStatusToSet, + onPlaybackStatusUpdate?: ((status: PlaybackStatus) => void) | null, + downloadFirst?: boolean + ): Promise<{ sound: Sound, status: PlaybackStatus }>; + } + + interface RecordingOptions { + android: { + extension: string; + outputFormat: number; + audioEncoder: number; + sampleRate?: number; + numberOfChannels?: number; + bitRate?: number; + maxFileSize?: number; + }; + ios: { + extension: string; + outputFormat?: string | number; + audioQuality: number; + sampleRate: number; + numberOfChannels: number; + bitRate: number; + bitRateStrategy?: number; + bitDepthHint?: number; + linearPCMBitDepth?: number; + linearPCMIsBigEndian?: boolean; + linearPCMIsFloat?: boolean; + }; + } + + class Recording { + constructor(); + + getStatusAsync(): Promise; + setOnRecordingStatusUpdate(onRecordingStatusUpdate: (status: RecordingStatus) => void): void; + setProgressUpdateInterval(miliss: number): void; + prepareToRecordAsync(options: Recording): Promise; + isPreparedToRecord(): boolean; + startAsync(): Promise; + pauseAsync(): Promise; + stopAndUnloadAsync(): Promise; + getURI(): string | undefined; + createNewLoadedSound(initialStatus: PlaybackStatusToSet, onPlaybackStatusUpdate: (status: PlaybackStatus) => void): Promise<{ sound: Sound, status: PlaybackStatus }>; + } +} + +/** + * Expo Video + */ +export interface NaturalSize { + width: number; + height: number; + orientation: Orientation; +} + +export interface ReadyForDisplayEvent { + naturalSize: NaturalSize; + status: PlaybackStatus; +} + +export enum FullscreenUpdateVariants { + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT = 0, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT = 1, + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS = 2, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS = 3 +} + +export interface FullscreenUpdateEvent { + fullscreenUpdate: FullscreenUpdateVariants; + status: PlaybackStatus; +} + +export interface VideoProps { + source?: Source | null; + posterSource?: URISource | RequireSource; + + resizeMode?: ResizeModeContain | ResizeModeCover | ResizeModeStretch; + useNativeControls?: boolean; + usePoster?: boolean; + + onPlaybackStatusUpdate?: (status: PlaybackStatus) => void; + onReadyForDisplay?: (event: ReadyForDisplayEvent) => void; + onIOSFullscreenUpdate?: (event: FullscreenUpdateEvent) => void; + + onLoadStart?: () => void; + onLoad?: (status: PlaybackStatus) => void; + onError?: (error: string) => void; + + status?: PlaybackStatusToSet; + progressUpdateIntervalMillis?: number; + positionMillis?: number; + shouldPlay?: boolean; + rate?: number; + shouldCorrectPitch?: boolean; + volume?: number; + isMuted?: boolean; + isLooping?: boolean; + + scaleX?: number; + scaleY?: number; + translateX?: number; + translateY?: number; + rotation?: number; + ref?: Ref; +} + +export interface VideoState { + showPoster: boolean; +} + +export class Video extends Component { + static RESIZE_MODE_CONTAIN: ResizeModeContain; + static RESIZE_MODE_COVER: ResizeModeCover; + static RESIZE_MODE_STRETCH: ResizeModeStretch; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS; +} + +/** + * AppLoading + */ +export type AppLoadingProperties = { + startAsync: () => Promise; + onFinish: () => void; + onError?: (error: Error) => void; +} | { + startAsync: null; + onFinish: null; + onError?: null; +}; +export class AppLoading extends Component { } + +/** + * BarCodeScanner + */ +export interface BarCodeScannerProps extends ViewProperties { + type?: 'front' | 'back'; + torchMode?: 'on' | 'off'; + barCodeTypes?: string[]; + onBarCodeRead?: BarCodeReadCallback; +} + +export class BarCodeScanner extends Component { } + +/** + * BlurView + */ +export interface BlurViewProps extends ViewProperties { + tint: 'light' | 'default' | 'dark'; + intensity: number; +} +export class BlurView extends Component { } + +/** + * Brightness + */ +export namespace Brightness { + function setBrightnessAsync(brightnessValue: FloatFromZeroToOne): Promise; + function getBrightnessAsync(): Promise; + function getSystemBrightnessAsync(): Promise; + function setSystemBrightnessAsync(brightnessValue: FloatFromZeroToOne): Promise; +} + +/** + * Camera + */ +export interface TakePictureOptions { + quality?: number; + base64?: boolean; + exif?: boolean; +} +export interface PictureResponse { + uri: string; + width: number; + height: number; + exif: string; + base64: string; +} +export interface RecordOptions { + quality?: string; + maxDuration?: number; + maxFileSize?: number; + mute?: boolean; +} +export class CameraObject { + takePictureAsync(options: TakePictureOptions): Promise; + recordAsync(options: RecordOptions): Promise<{ uri: string; }>; + stopRecording(): void; + getSupportedRatiosAsync(): Promise; // Android only +} +export interface CameraProperties extends ViewProperties { + flashMode?: string | number; + type?: string | number; + ratio?: string; + autoFocus?: string | number | boolean; + focusDepth?: FloatFromZeroToOne; + zoom?: FloatFromZeroToOne; + whiteBalance?: string | number; + barCodeTypes?: string[]; + onCameraReady?: () => void; + onMountError?: () => void; + onBarCodeRead?: BarCodeReadCallback; + ref?: Ref; +} +export interface CameraConstants { + readonly Type: string; + readonly FlashMode: string; + readonly AutoFocus: string; + readonly WhiteBalance: string; + readonly VideoQuality: string; + readonly BarCodeType: string; +} +export class Camera extends Component { + static readonly Constants: CameraConstants; +} + +/** + * Constants + */ +export namespace Constants { + const appOwnership: 'expo' | 'standalone' | 'guest'; + const expoVersion: string; + const deviceId: string; + const deviceName: string; + const deviceYearClass: number; + const isDevice: boolean; + + interface Platform { + ios: { + platform: string; + model: string; + userInterfaceIdiom: string; + }; + } + const platform: Platform; + const sessionId: string; + const statusBarHeight: number; + const systemFonts: string[]; + + interface Manifest { + name: string; + description?: string; + slug?: string; + sdkVersion?: string; + version?: string; + orientation?: Orientation; + primaryColor?: string; + icon?: string; + notification?: { + icon?: string, + color?: string, + androidMode?: 'default' | 'collapse', + androidCollapsedTitle?: string + }; + loading?: { + icon?: string, + exponentIconColor?: 'white' | 'blue', + exponentIconGrayscale?: 1 | 0, + backgroundImage?: string, + backgroundColor?: string, + hideExponentText?: boolean + }; + appKey?: string; + androidStatusBarColor?: string; + androidStatusBar?: { + barStyle?: 'lignt-content' | 'dark-content', + backgroundColor?: string + }; + androidHideExponentNotificationInShellApp?: boolean; + scheme?: string; + extra?: { + [propName: string]: any + }; + rnCliPath?: any; + entryPoint?: string; + packagerOpts?: { + hostType?: string, + dev?: boolean, + strict?: boolean, + minify?: boolean, + urlType?: string, + urlRandomness?: string, + lanType?: string, + [propName: string]: any + }; + ignoreNodeModulesValidation?: any; + nodeModulesPath?: string; + ios?: { + bundleIdentifier?: string, + buildNumber?: string, + config?: { + usesNonExemptEncryption?: boolean, + googleSignIn?: { + reservedClientId: string + } + }, + supportsTablet?: boolean, + infoPlist?: any + }; + android?: { + package?: string, + versionCode?: string, + config?: { + fabric?: { + apiKey: string, + buildSecret: string + }, + googleMaps?: { + apiKey: string + }, + googleSignIn?: { + apiKey: string, + certificateHash: string + } + } + }; + facebookScheme: any; + xde: boolean; + developper?: { + tool?: string, + [propName: string]: any + }; + bundleUrl?: string; + debuggerHost?: string; + mainModuleName?: string; + logUrl?: string; + [propName: string]: any; + } + const manifest: Manifest; + const linkingUri: string; +} + +/** + * Contacts + */ +export namespace Contacts { + type PhoneNumbers = 'phoneNumbers'; + type Emails = 'emails'; + type Addresses = 'addresses'; + type Image = 'image'; + type Thumbnail = 'thumbnail'; + type Note = 'note'; + type Birthday = 'birthday'; + type NonGregorianBirthday = 'nonGregorianBirthday'; + type NamePrefix = 'namePrefix'; + type NameSuffix = 'nameSuffix'; + type PhoneticFirstName = 'phoneticFirstName'; + type PhoneticMiddleName = 'phoneticMiddleName'; + type PhoneticLastName = 'phoneticLastName'; + type SocialProfiles = 'socialProfiles'; + type InstantMessageAddresses = 'instantMessageAddresses'; + type UrlAddresses = 'urlAddresses'; + type Dates = 'dates'; + type Relationships = 'relationships'; + + const PHONE_NUMBERS: PhoneNumbers; + const EMAILS: Emails; + const ADDRESSES: Addresses; + const IMAGE: Image; + const THUMBNAIL: Thumbnail; + const NOTE: Note; + const BIRTHDAY: Birthday; + const NON_GREGORIAN_BIRTHDAY: NonGregorianBirthday; + const NAME_PREFIX: NamePrefix; + const NAME_SUFFIX: NameSuffix; + const PHONETIC_FIRST_NAME: PhoneticFirstName; + const PHONETIC_MIDDLE_NAME: PhoneticMiddleName; + const PHONETIC_LAST_NAME: PhoneticLastName; + const SOCIAL_PROFILES: SocialProfiles; + const IM_ADDRESSES: InstantMessageAddresses; + const URLS: UrlAddresses; + const DATES: Dates; + const RELATIONSHIPS: Relationships; + + type FieldType = PhoneNumbers | Emails | Addresses | Image | Thumbnail | + Note | Birthday | NonGregorianBirthday | NamePrefix | NameSuffix | + PhoneticFirstName | PhoneticMiddleName | PhoneticLastName | SocialProfiles | + InstantMessageAddresses | UrlAddresses | Dates | Relationships; + + interface Options { + pageSize?: number; + pageOffset?: number; + fields?: FieldType[]; + } + + interface Contact { + id: string; + contactType: string; + name: string; + firstName?: string; + middleName?: string; + lastName?: string; + previousLastName?: string; + namePrefix?: string; + nameSuffix?: string; + nickname?: string; + phoneticFirstName?: string; + phoneticMiddleName?: string; + phoneticLastName?: string; + emails?: Array<{ + email?: string; + primary?: boolean; + label: string; + id: string; + }>; + phoneNumbers?: Array<{ + number?: string; + primary?: boolean; + digits?: string; + countryCode?: string; + label: string; + id: string; + }>; + addresses?: Array<{ + street?: string; + city?: string; + country?: string; + region?: string; + neighborhood?: string; + postalCode?: string; + poBox?: string; + isoCountryCode?: string; + label: string; + id: string; + }>; + socialProfiles?: Array<{ + service?: string; + localizedProfile?: string; + url?: string; + username?: string; + userId?: string; + label: string; + id: string; + }>; + instantMessageAddresses?: Array<{ + service?: string; + username?: string; + localizedService?: string; + label: string; + id: string; + }>; + urls?: { + label: string; + url?: string; + id: string; + }; + company?: string; + jobTitle?: string; + department?: string; + imageAvailable?: boolean; + image?: { + uri?: string; + }; + thumbnail?: { + uri?: string; + }; + note?: string; + dates?: Array<{ + day?: number; + month?: number; + year?: number; + id: string; + label: string; + }>; + relationships?: Array<{ + label: string; + name?: string; + id: string; + }>; + } + + interface Response { + data: Contact[]; + total: number; + hasNextPage: boolean; + hasPreviousPage: boolean; + } + + function getContactsAsync(options: Options): Promise; + function getContactByIdAsync(options: { id?: string; fields?: FieldType[] }): Promise; +} + +/** + * DocumentPicker + */ +export namespace DocumentPicker { + interface Options { + type?: string; + } + type Response = { + type: 'success'; + uri: string; + name: string; + size: number; + } | { + type: 'cancel'; + }; + + function getDocumentAsync(options?: Options): Promise; +} + +/** + * ErrorRecovery + */ +export namespace ErrorRecovery { + function setRecoveryProps(props: HashMap): void; +} + +/** + * Facebook + */ +export namespace Facebook { + interface Options { + permissions?: string[]; + behavior?: 'web' | 'native' | 'browser' | 'system'; + } + type Response = { + type: 'success'; + token: string; + expires: number; + } | { + type: 'cancel'; + }; + function logInWithReadPermissionsAsync(appId: string, options?: Options): Promise; +} + +/** + * Facebook Ads + */ +export namespace FacebookAds { + /** + * Interstitial Ads + */ + namespace InterstitialAdManager { + function showAd(placementId: string): Promise; + } + + /** + * Native Ads + */ + type MediaCachePolicy = 'none' | 'icon' | 'image' | 'all'; + class NativeAdsManager { + constructor(placementId: string, numberOfAdsToRequest?: number); + disableAutoRefresh(): void; + setMediaCachePolicy(cachePolicy: MediaCachePolicy): void; + } + + function withNativeAd(component: Component<{ + icon?: string; + coverImage?: string; + title?: string; + subtitle?: string; + description?: string; + callToActionText?: string; + socialContext?: string; + }>): Component<{ adsManager: NativeAdsManager }, { ad: any, canRequestAds: boolean }>; + + /** + * Banner View + */ + type AdType = 'large' | 'rectangle' | 'standard'; + + interface BannerViewProps { + type: AdType; + placementId: string; + onPress: () => void; + onError: () => void; + } + + class BannerView extends Component { } + + /** + * Ad Settings + */ + namespace AdSettings { + const currentDeviceHash: string; + function addTestDevice(device: string): void; + function clearTestDevices(): void; + type SDKLogLevel = 'none' | 'debug' | 'verbose' | 'warning' | 'error' | 'notification'; + function setLogLevel(logLevel: SDKLogLevel): void; + function setIsChildDirected(isDirected: boolean): void; + function setMediationService(mediationService: string): void; + function setUrlPrefix(urlPrefix: string): void; + } +} + +/** + * FileSystem + */ +export namespace FileSystem { + type FileInfo = { + exists: true; + isDirectory: boolean; + uri: string; + size: number; + modificationTime: number; + md5?: Md5; + } | { + exists: false; + isDirectory: false; + }; + + interface DownloadResult { + uri: string; + status: number; + headers: { [name: string]: string }; + md5?: Md5; + } + + const documentDirectory: string; + const cacheDirectory: string; + + function getInfoAsync(fileUri: string, options?: { md5?: string, size?: boolean; }): Promise; + function readAsStringAsync(fileUri: string): Promise; + function writeAsStringAsync(fileUri: string, contents: string): Promise; + function deleteAsync(fileUri: string, options?: { idempotent: boolean; }): Promise; + function moveAsync(options: { from: string, to: string; }): Promise; + function copyAsync(options: { from: string, to: string; }): Promise; + function makeDirectoryAsync(dirUri: string, options?: { intermediates: boolean }): Promise; + function readDirectoryAsync(dirUri: string): Promise; + function downloadAsync(uri: string, fileUri: string, options?: { md5?: boolean; }): Promise; + function createDownloadResumable( + uri: string, + fileUri: string, + options?: DownloadOptions, + callback?: (totalBytesWritten: number, totalBytesExpectedToWrite: number) => void, + resumeData?: string | null + ): DownloadResumable; + + interface PauseResult { + url: string; + fileUri: string; + options: { md5: boolean; }; + resumeData: string; + } + + interface DownloadOptions { + md5?: boolean; + headers?: { [name: string]: string }; + } + + interface DownloadProgressData { + totalBytesWritten: number; + totalBytesExpectedToWrite: number; + } + + type DownloadProgressCallback = (data: DownloadProgressData) => void; + + class DownloadResumable { + constructor( + url: string, + fileUri: string, + options: DownloadOptions, + callback?: DownloadProgressCallback, + resumeData?: string + ); + + downloadAsync(): Promise; + pauseAsync(): Promise; + resumeAsync(): Promise; + savable(): PauseResult; + } +} + +/** + * Fingerprint + */ +export namespace Fingerprint { + type FingerprintAuthenticationResult = { success: true } | { success: false, error: string }; + + function hasHardwareAsync(): Promise; + function isEnrolledAsync(): Promise; + function authenticateAsync(promptMessageIOS?: string): Promise; + function cancelAuthenticate(): void; +} + +/** + * Font + */ +export namespace Font { + interface FontMap { + [name: string]: RequireSource; + } + + function loadAsync(name: string, url: string): Promise; + function loadAsync(map: FontMap): Promise; +} + +/** + * GLView + */ +export interface GLViewProps extends ViewProperties { + onContextCreate(): void; + msaaSamples: number; +} +export class GLView extends Component { } + +/** + * Google + */ +export namespace Google { + interface LogInConfig { + androidClientId?: string; + androidStandaloneAppClientId?: string; + iosClientId?: string; + iosStandaloneAppClientId?: string; + webClientId?: string; + behavior?: 'system' | 'web'; + scopes?: string[]; + } + + type LogInResult = { + type: 'cancel'; + } | { + type: 'success'; + accessToken: string; + idToken?: string; + refreshToken?: string; + serverAuthCode?: string; + user: { + id: string; + name: string; + givenName: string; + familyName: string; + photoUrl?: string; + email?: string; + } + }; + + function logInAsync(config: LogInConfig): Promise; +} + +/** + * Gyroscope + */ +export namespace Gyroscope { + interface GyroscopeObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: GyroscopeObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Image Picker + */ +export namespace ImagePicker { + interface ImageInfo { + uri: string; + width: number; + height: number; + } + + type ImageResult = { cancelled: true } | ({ cancelled: false } & ImageInfo); + + interface ImageLibraryOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + } + + function launchImageLibraryAsync(options?: ImageLibraryOptions): Promise; + + interface CameraOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + } + function launchCameraAsync(options?: CameraOptions): Promise; +} + +/** + * IntentLauncherAndroid + */ +export namespace IntentLauncherAndroid { + const ACTION_ACCESSIBILITY_SETTINGS: string; + const ACTION_APP_NOTIFICATION_REDACTION: string; + const ACTION_CONDITION_PROVIDER_SETTINGS: string; + const ACTION_NOTIFICATION_LISTENER_SETTINGS: string; + const ACTION_PRINT_SETTINGS: string; + const ACTION_ADD_ACCOUNT_SETTINGS: string; + const ACTION_AIRPLANE_MODE_SETTINGS: string; + const ACTION_APN_SETTINGS: string; + const ACTION_APPLICATION_DETAILS_SETTINGS: string; + const ACTION_APPLICATION_DEVELOPMENT_SETTINGS: string; + const ACTION_APPLICATION_SETTINGS: string; + const ACTION_APP_NOTIFICATION_SETTINGS: string; + const ACTION_APP_OPS_SETTINGS: string; + const ACTION_BATTERY_SAVER_SETTINGS: string; + const ACTION_BLUETOOTH_SETTINGS: string; + const ACTION_CAPTIONING_SETTINGS: string; + const ACTION_CAST_SETTINGS: string; + const ACTION_DATA_ROAMING_SETTINGS: string; + const ACTION_DATE_SETTINGS: string; + const ACTION_DEVICE_INFO_SETTINGS: string; + const ACTION_DEVICE_NAME: string; + const ACTION_DISPLAY_SETTINGS: string; + const ACTION_DREAM_SETTINGS: string; + const ACTION_HARD_KEYBOARD_SETTINGS: string; + const ACTION_HOME_SETTINGS: string; + const ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS: string; + const ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS: string; + const ACTION_INPUT_METHOD_SETTINGS: string; + const ACTION_INPUT_METHOD_SUBTYPE_SETTINGS: string; + const ACTION_INTERNAL_STORAGE_SETTINGS: string; + const ACTION_LOCALE_SETTINGS: string; + const ACTION_LOCATION_SOURCE_SETTINGS: string; + const ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS: string; + const ACTION_MANAGE_APPLICATIONS_SETTINGS: string; + const ACTION_MANAGE_DEFAULT_APPS_SETTINGS: string; + const ACTION_MEMORY_CARD_SETTINGS: string; + const ACTION_MONITORING_CERT_INFO: string; + const ACTION_NETWORK_OPERATOR_SETTINGS: string; + const ACTION_NFCSHARING_SETTINGS: string; + const ACTION_NFC_PAYMENT_SETTINGS: string; + const ACTION_NFC_SETTINGS: string; + const ACTION_NIGHT_DISPLAY_SETTINGS: string; + const ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS: string; + const ACTION_NOTIFICATION_SETTINGS: string; + const ACTION_PAIRING_SETTINGS: string; + const ACTION_PRIVACY_SETTINGS: string; + const ACTION_QUICK_LAUNCH_SETTINGS: string; + const ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS: string; + const ACTION_SECURITY_SETTINGS: string; + const ACTION_SETTINGS: string; + const ACTION_SHOW_ADMIN_SUPPORT_DETAILS: string; + const ACTION_SHOW_INPUT_METHOD_PICKER: string; + const ACTION_SHOW_REGULATORY_INFO: string; + const ACTION_SHOW_REMOTE_BUGREPORT_DIALOG: string; + const ACTION_SOUND_SETTINGS: string; + const ACTION_STORAGE_MANAGER_SETTINGS: string; + const ACTION_SYNC_SETTINGS: string; + const ACTION_SYSTEM_UPDATE_SETTINGS: string; + const ACTION_TETHER_PROVISIONING_UI: string; + const ACTION_TRUSTED_CREDENTIALS_USER: string; + const ACTION_USAGE_ACCESS_SETTINGS: string; + const ACTION_USER_DICTIONARY_INSERT: string; + const ACTION_USER_DICTIONARY_SETTINGS: string; + const ACTION_USER_SETTINGS: string; + const ACTION_VOICE_CONTROL_AIRPLANE_MODE: string; + const ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE: string; + const ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE: string; + const ACTION_VOICE_INPUT_SETTINGS: string; + const ACTION_VPN_SETTINGS: string; + const ACTION_VR_LISTENER_SETTINGS: string; + const ACTION_WEBVIEW_SETTINGS: string; + const ACTION_WIFI_IP_SETTINGS: string; + const ACTION_WIFI_SETTINGS: string; + const ACTION_WIRELESS_SETTINGS: string; + const ACTION_ZEN_MODE_AUTOMATION_SETTINGS: string; + const ACTION_ZEN_MODE_EVENT_RULE_SETTINGS: string; + const ACTION_ZEN_MODE_EXTERNAL_RULE_SETTINGS: string; + const ACTION_ZEN_MODE_PRIORITY_SETTINGS: string; + const ACTION_ZEN_MODE_SCHEDULE_RULE_SETTINGS: string; + const ACTION_ZEN_MODE_SETTINGS: string; + + function startActivityAsync(activity: string, data?: HashMap): Promise; +} + +/** + * KeepAwake + */ +export class KeepAwake extends Component { + static activate(): void; + static deactivate(): void; +} + +/** + * LinearGradient + */ +export interface LinearGradientProps { + colors: string[]; + start: [number, number]; + end: [number, number]; + locations: number[]; +} + +export class LinearGradient extends Component { } + +/** + * Location + */ +export namespace Location { + interface LocationOptions { + enableHighAccuracy?: boolean; + timeInterval?: number; + distanceInterval?: number; + } + + interface LocationProps { + latitude: number; + longitude: number; + } + + interface Coords extends LocationProps { + altitude: number; + accuracy: number; + } + + interface LocationData { + coords: { + heading: number; + speed: number + } & Coords; + timestamp: number; + } + + interface ProviderStatus { + locationServicesEnabled: boolean; + gpsAvailable?: boolean; + networkAvailable?: boolean; + passiveAvailable?: boolean; + } + + interface HeadingStatus { + magHeading: number; + trueHeading: number; + accuracy: number; + } + + interface GeocodeData { + city: string; + street: string; + region: string; + postalCode: string; + country: string; + name: string; + } + + type LocationCallback = (data: LocationData) => void; + + function getCurrentPositionAsync(options: LocationOptions): Promise; + function watchPositionAsync(options: LocationOptions, callback: LocationCallback): EventSubscription; + function getProviderStatusAsync(): Promise; + function getHeadingAsync(): Promise; + function watchHeadingAsync(callback: (status: HeadingStatus) => void): EventSubscription; + function geocodeAsync(address: string): Promise; + function reverseGeocodeAsync(location: LocationProps): Promise; + function setApiKey(key: string): void; +} + +/** + * Magnetometer + */ +export namespace Magnetometer { + interface MagnetometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: MagnetometerObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Notifications + */ +export namespace Notifications { + interface Notification { + origin: 'selected' | 'received'; + data: any; + remote: boolean; + isMultiple: boolean; + } + + interface LocalNotification { + title: string; + body?: string; + data?: any; + ios?: { + sound?: boolean + }; + android?: { + sound?: boolean; + icon?: string; + color?: string; + priority?: 'min' | 'low' | 'high' | 'max'; + sticky?: boolean; + vibrate?: boolean | number[]; + link?: string; + }; + } + + type LocalNotificationId = string | number; + + function addListener(listener: (notification: Notification) => any): EventSubscription; + function getExponentPushTokenAsync(): Promise; + function presentLocalNotificationAsync(localNotification: LocalNotification): Promise; + function scheduleLocalNotificationAsync( + localNotification: LocalNotification, + schedulingOptions: { time: Date | number, repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' } + ): Promise; + function dismissNotificationAsync(localNotificationId: LocalNotificationId): Promise; + function dismissAllNotificationsAsync(): Promise; + function cancelScheduledNotificationAsync(localNotificationId: LocalNotificationId): Promise; + function cancelAllScheduledNotificationsAsync(): Promise; + function getBadgeNumberAsync(): Promise; + function setBadgeNumberAsync(number: number): Promise; +} + +/** + * Pedometer + */ +export namespace Pedometer { + function isAvailableAsync(): Promise; + function getStepCountAsync(start: Date, end: Date): Promise<{ steps: number; }>; + function watchStepCount(callback: (params: { steps: number; }) => void): EventSubscription; +} + +/** + * Permissions + */ +export namespace Permissions { + type PermissionType = 'remoteNotifications' | 'location' | + 'camera' | 'contacts' | 'audioRecording'; + type PermissionStatus = 'undetermined' | 'granted' | 'denied'; + type PermissionExpires = 'never'; + interface PermissionDetailsLocationIOS { + scope: 'whenInUse' | 'always'; + } + interface PermissionDetailsLocationAndroid { + scope: 'fine' | 'coarse' | 'none'; + } + interface PermissionResponse { + status: PermissionStatus; + expires: PermissionExpires; + ios?: PermissionDetailsLocationIOS; + android?: PermissionDetailsLocationAndroid; + } + + function getAsync(type: PermissionType): Promise; + function askAsync(type: PermissionType): Promise; + + const CAMERA: string; + const CAMERA_ROLL: string; + const AUDIO_RECORDING: string; + const LOCATION: string; + const REMOTE_NOTIFICATIONS: string; + const NOTIFICATIONS: string; + const CONTACTS: string; +} + +/** + * Register Root Component + */ +export function registerRootComponent(component: Component): Component; + +/** + * ScreenOrientation + */ +export namespace ScreenOrientation { + interface Orientation { + ALL: 'ALL'; + ALL_BUT_UPSIDE_DOWN: 'ALL_BUT_UPSIDE_DOWN'; + PORTRAIT: 'PORTRAIT'; + PORTRAIT_UP: 'PORTRAIT_UP'; + PORTRAIT_DOWN: 'PORTRAIT_DOWN'; + LANDSCAPE: 'LANDSCAPE'; + LANDSCAPE_LEFT: 'LANDSCAPE_LEFT'; + LANDSCAPE_RIGHT: 'LANDSCAPE_RIGHT'; + } + const Orientation: Orientation; + function allow(orientation: string): void; +} + +/** + * SecureStore + */ +export namespace SecureStore { + interface SecureStoreOptions { + keychainService?: string; + keychainAccessible?: number; + } + function setItemAsync(key: string, value: string, options?: SecureStoreOptions): Promise; + function getItemAsync(key: string, options?: SecureStoreOptions): Promise; + function deleteItemAsync(key: string, options?: SecureStoreOptions): Promise; +} + +/** + * Segment + */ +export namespace Segment { + function initialize(keys: { + androidWriteKey: string; + iosWriteKey: string; + }): void; + function identify(userId: string): void; + function identifyWithTraits(userId: string, traits: object): void; + function track(event: string): void; + function reset(): void; + function trackWithProperties(event: string, properties: object): void; + function screen(screenName: string): void; + function screenWithProperties(screenName: string, properties: object): void; + function flush(): void; +} + +/** + * Speech + */ +export namespace Speech { + interface SpeechOptions { + language?: string; + pitch?: number; + rate?: number; + onStart?: () => void; + onStopped?: () => void; + onDone?: () => void; + onError?: (error: string) => void; + } + + function speak(text: string, options?: SpeechOptions): void; + function stop(): void; + function isSpeakingAsync(): Promise; +} + +/** + * SQLite + */ +export namespace SQLite { + type Error = any; + + interface Database { + transaction( + callback: (transaction: Transaction) => any, + error?: (error: Error) => any, // TODO def of error + success?: () => any + ): void; + } + + interface Transaction { + executeSql( + sqlStatement: string, + arguments?: string[] | number[], + success?: (transaction: Transaction, resultSet: ResultSet) => any, + error?: (transaction: Transaction, error: Error) => any + ): void; + } + + interface ResultSet { + insertId: number; + rowAffected: number; + rows: { + length: number; + item: (index: number) => any; + _array: HashMap[]; + }; + } + + function openDatabase( + name: string | { + name: string, + version?: string, + description?: string, + size?: number, + callback?: () => any + }, + version?: string, + description?: string, + size?: number, + callback?: () => any + ): any; +} + +/** + * Svg + */ +export interface SvgCommonProps { + fill?: string; + fillOpacity?: number; + stroke?: string; + strokeWidth?: number; + strokeOpacity?: number; + strokeLinecap?: string; + strokeLineJoin?: string; + strokeDasharray?: any[]; + strokeDashoffset?: any; + x?: Axis; + y?: Axis; + rotate?: number; + scale?: number; + origin?: number | string; + originX?: number; + originY?: number; +} + +export class Svg extends Component<{ width: number, heigth: number }> { } +export class Rect extends Component { } + +export interface CircleProps extends SvgCommonProps { + cx: Axis; + cy: Axis; +} +export class Circle extends Component { } + +export interface EllipseProps extends CircleProps { + rx: Axis; + ry: Axis; +} +export class Ellipse extends Component { } + +export interface LineProps extends SvgCommonProps { + x1: Axis; + y1: Axis; + x2: Axis; + y2: Axis; +} +export class Line extends Component { } + +export interface PolyProps extends SvgCommonProps { + points: string; +} +export class Polygon extends Component { } +export class Polyline extends Component { } + +export interface PathLine extends SvgCommonProps { + d: string; +} +export class Path extends Component { } + +export interface TextProps extends SvgCommonProps { + textAnchor: string; +} +export class Text extends Component { } +export class G extends Component { } +export class Use extends Component<{ href: string, x: number, y: number }> { } +export class Symbol extends Component<{ viewbox: string, widt: number, height: number }> { } +export class Defs extends Component { } +export class RadialGradient extends Component { } + +/** + * Take Snapshot + */ +export function takeSnapshotAsync( + view?: (number | React.ReactElement), + options?: { + width?: number, + height?: number, + format?: 'png' | 'jpg' | 'jpeg' | 'webm', + quality?: number, + result?: 'file' | 'base64' | 'data-uri', + } +): Promise; + +/** + * Util + */ +export namespace Util { + function getCurrentDeviceCountryAsync(): Promise; + function getCurrentLocaleAsync(): Promise; + function getCurrentTimeZoneAsync(): Promise; + function reload(): void; + function addNewVersionListenerExperimental(listener: (event: { + manifest: object; + }) => void): { remove(): void; }; // Android only +} + +/** + * Web Browser + */ +export namespace WebBrowser { + function openBrowserAsync(url: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function openAuthSessionAsync(url: string, redirectUrl?: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function dismissBrowser(): Promise<{ type: 'dismissed' }>; +} diff --git a/types/expo/tsconfig.json b/types/expo/tsconfig.json new file mode 100644 index 0000000000..5d0f560837 --- /dev/null +++ b/types/expo/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "expo-tests.tsx" + ] +} diff --git a/types/expo/tslint.json b/types/expo/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/expo/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/express-cluster/express-cluster-tests.ts b/types/express-cluster/express-cluster-tests.ts new file mode 100644 index 0000000000..4eb096ffd6 --- /dev/null +++ b/types/express-cluster/express-cluster-tests.ts @@ -0,0 +1,6 @@ +import cluster = require('express-cluster'); + +() => { + cluster(worker => {}, {count: 5}); + cluster({count: 5}, worker => {}); +}; diff --git a/types/express-cluster/index.d.ts b/types/express-cluster/index.d.ts new file mode 100644 index 0000000000..bee845d02e --- /dev/null +++ b/types/express-cluster/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for express-cluster 0.0 +// Project: https://github.com/Flipboard/express-cluster +// Definitions by: Miloslav Nenadál +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import cluster = require('cluster'); + +interface Config { + count?: number; + respawn?: boolean; + verbose?: boolean; + workerListener?(): void; + outputStream?: NodeJS.WritableStream; +} + +type WorkerFunction = (worker: cluster.Worker) => void; + +interface Cluster { + (fn: WorkerFunction, config: Config): void; + (config: Config, fn: WorkerFunction): void; +} + +declare const c: Cluster; +export = c; diff --git a/types/express-cluster/tsconfig.json b/types/express-cluster/tsconfig.json new file mode 100644 index 0000000000..5d27d3ec2e --- /dev/null +++ b/types/express-cluster/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-cluster-tests.ts" + ] +} \ No newline at end of file diff --git a/types/express-cluster/tslint.json b/types/express-cluster/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-cluster/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/express-serve-static-core/index.d.ts b/types/express-serve-static-core/index.d.ts index 9119c8497f..2f8d862b14 100644 --- a/types/express-serve-static-core/index.d.ts +++ b/types/express-serve-static-core/index.d.ts @@ -820,7 +820,7 @@ export interface Application extends IRouter, Express.Application { * Express instance itself is a request handler, which could be invoked without * third argument. */ - (req: Request, res: Response): any; + (req: Request | http.IncomingMessage, res: Response | http.ServerResponse): any; /** * Initialize the server. diff --git a/types/faker/faker-tests.ts b/types/faker/faker-tests.ts index 5fb6a53746..df671dcf6a 100644 --- a/types/faker/faker-tests.ts +++ b/types/faker/faker-tests.ts @@ -1,5 +1,3 @@ - - let resultStr: string; let resultBool: boolean; let resultNum: number; @@ -17,7 +15,7 @@ resultStr = faker.address.cityPrefix(); resultStr = faker.address.citySuffix(); resultStr = faker.address.streetName(); resultStr = faker.address.streetAddress(); -resultStr = faker.address.streetAddress(false);; +resultStr = faker.address.streetAddress(false); resultStr = faker.address.streetSuffix(); resultStr = faker.address.streetPrefix(); resultStr = faker.address.secondaryAddress(); @@ -63,6 +61,8 @@ resultDate = faker.date.between('foo', 'bar'); resultDate = faker.date.between(new Date(), new Date()); resultDate = faker.date.recent(); resultDate = faker.date.recent(100); +resultDate = faker.date.soon(); +resultDate = faker.date.soon(30); resultStr = faker.date.month(); resultStr = faker.date.month({ abbr: true, @@ -86,6 +86,9 @@ resultStr = faker.finance.currencyCode(); resultStr = faker.finance.currencyName(); resultStr = faker.finance.currencySymbol(); resultStr = faker.finance.bitcoinAddress(); +resultStr = faker.finance.ethereumAddress(); +resultStr = faker.finance.iban(); +resultStr = faker.finance.iban(true); resultStr = faker.finance.bic(); resultStr = faker.hacker.abbreviation(); @@ -96,7 +99,7 @@ resultStr = faker.hacker.ingverb(); resultStr = faker.hacker.phrase(); resultStr = faker.helpers.randomize(); -resultNum = faker.helpers.randomize([1,2,3,4]); +resultNum = faker.helpers.randomize([1, 2, 3, 4]); resultStr = faker.helpers.randomize(['foo', 'bar', 'quux']); resultStr = faker.helpers.slugify('foo bar quux'); resultStr = faker.helpers.replaceSymbolWithNumber('foo# bar#'); @@ -167,7 +170,6 @@ resultStr = faker.name.jobType(); resultStr = faker.phone.phoneNumber(); resultStr = faker.phone.phoneNumber('#'); resultStr = faker.phone.phoneNumberFormat(); -// https://github.com/Marak/faker.js/blob/master/lib/phone_number.js#L9-L13 resultStr = faker.phone.phoneNumberFormat(0); resultStr = faker.phone.phoneFormats(); @@ -179,27 +181,104 @@ resultNum = faker.random.number({ precision: 0 }); resultStr = faker.random.arrayElement(); -resultStr = faker.random.arrayElement(['foo', 'bar', 'quux']) +resultStr = faker.random.arrayElement(['foo', 'bar', 'quux']); resultStr = faker.random.objectElement(); resultStr = faker.random.objectElement({foo: 'bar', field: 'foo'}); resultStr = faker.random.uuid(); resultBool = faker.random.boolean(); resultStr = faker.random.word(); +resultStr = faker.random.word("noun"); resultStr = faker.random.words(); resultStr = faker.random.words(0); resultStr = faker.random.image(); resultStr = faker.random.locale(); resultStr = faker.random.alphaNumeric(); resultStr = faker.random.alphaNumeric(0); +resultStr = faker.random.hexaDecimal(); +resultStr = faker.random.hexaDecimal(3); -resultStr = faker.system.fileName( "foo", "bar" ); -resultStr = faker.system.commonFileName( "foo", "bar" ); +resultStr = faker.system.fileName("foo", "bar"); +resultStr = faker.system.commonFileName("foo", "bar"); resultStr = faker.system.mimeType(); resultStr = faker.system.commonFileType(); resultStr = faker.system.commonFileExt(); resultStr = faker.system.fileType(); -resultStr = faker.system.fileExt( "foo" ); +resultStr = faker.system.fileExt("foo"); +resultStr = faker.system.directoryPath(); +resultStr = faker.system.filePath(); resultStr = faker.system.semver(); +import fakerAz = require('faker/locale/az'); +resultStr = fakerAz.name.firstName(); +import fakerCz = require('faker/locale/cz'); +resultStr = fakerCz.name.firstName(); +import fakerDe = require('faker/locale/de'); +resultStr = fakerDe.name.firstName(); +import fakerDeAT = require('faker/locale/de_AT'); +resultStr = fakerDeAT.name.firstName(); +import fakerdeCH = require('faker/locale/de_CH'); +resultStr = fakerdeCH.name.firstName(); import fakerEn = require('faker/locale/en'); -resultStr = faker.name.firstName(); +resultStr = fakerEn.name.firstName(); +import fakerEnAU = require('faker/locale/en_AU'); +resultStr = fakerEnAU.name.firstName(); +import fakerEnBORK = require('faker/locale/en_BORK'); +resultStr = fakerEnBORK.name.firstName(); +import fakerEnCA = require('faker/locale/en_CA'); +resultStr = fakerEnCA.name.firstName(); +import fakerEnGB = require('faker/locale/en_GB'); +resultStr = fakerEnGB.name.firstName(); +import fakerEnIE = require('faker/locale/en_IE'); +resultStr = fakerEnIE.name.firstName(); +import fakerEnIND = require('faker/locale/en_IND'); +resultStr = fakerEnIND.name.firstName(); +import fakerEnUS = require('faker/locale/en_US'); +resultStr = fakerEnUS.name.firstName(); +import fakerEnAuOcker = require('faker/locale/en_au_ocker'); +resultStr = fakerEnAuOcker.name.firstName(); +import fakerEs = require('faker/locale/es'); +resultStr = fakerEs.name.firstName(); +import fakerEsMX = require('faker/locale/es_MX'); +resultStr = fakerEsMX.name.firstName(); +import fakerFa = require('faker/locale/fa'); +resultStr = fakerFa.name.firstName(); +import fakerFr = require('faker/locale/fr'); +resultStr = fakerFr.name.firstName(); +import fakerFrCA = require('faker/locale/fr_CA'); +resultStr = fakerFrCA.name.firstName(); +import fakerGe = require('faker/locale/ge'); +resultStr = fakerGe.name.firstName(); +import fakerIdID = require('faker/locale/id_ID'); +resultStr = fakerIdID.name.firstName(); +import fakerIt = require('faker/locale/it'); +resultStr = fakerIt.name.firstName(); +import fakerJa = require('faker/locale/ja'); +resultStr = fakerJa.name.firstName(); +import fakerKo = require('faker/locale/ko'); +resultStr = fakerKo.name.firstName(); +import fakerNbNO = require('faker/locale/nb_NO'); +resultStr = fakerNbNO.name.firstName(); +import fakerNep = require('faker/locale/nep'); +resultStr = fakerNep.name.firstName(); +import fakerNl = require('faker/locale/nl'); +resultStr = fakerNl.name.firstName(); +import fakerPl = require('faker/locale/pl'); +resultStr = fakerPl.name.firstName(); +import fakerPtBR = require('faker/locale/pt_BR'); +resultStr = fakerPtBR.name.firstName(); +import fakerRu = require('faker/locale/ru'); +resultStr = fakerRu.name.firstName(); +import fakerSk = require('faker/locale/sk'); +resultStr = fakerSk.name.firstName(); +import fakerSv = require('faker/locale/sv'); +resultStr = fakerSv.name.firstName(); +import fakerTr = require('faker/locale/tr'); +resultStr = fakerTr.name.firstName(); +import fakerUk = require('faker/locale/uk'); +resultStr = fakerUk.name.firstName(); +import fakerVi = require('faker/locale/vi'); +resultStr = fakerVi.name.firstName(); +import fakerZhCN = require('faker/locale/zh_CN'); +resultStr = fakerZhCN.name.firstName(); +import fakerZhTW = require('faker/locale/zh_TW'); +resultStr = fakerZhTW.name.firstName(); diff --git a/types/faker/index.d.ts b/types/faker/index.d.ts index eda944d515..552e7d3eeb 100644 --- a/types/faker/index.d.ts +++ b/types/faker/index.d.ts @@ -1,9 +1,12 @@ -// Type definitions for faker v4.1.0 +// Type definitions for faker 4.1 // Project: http://marak.com/faker.js/ -// Definitions by: Ben Swartz , Bas Pennings , Yuki Kokubun +// Definitions by: Ben Swartz , +// Bas Pennings , +// Yuki Kokubun , +// Matt Bishop // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare var fakerStatic: Faker.FakerStatic; +declare const fakerStatic: Faker.FakerStatic; declare namespace Faker { interface FakerStatic { @@ -64,6 +67,7 @@ declare namespace Faker { future(years?: number, refDate?: string|Date): Date; between(from: string|number|Date, to: string|Date): Date; recent(days?: number): Date; + soon(days?: number): Date; month(options?: { abbr?: boolean, context?: boolean }): string; weekday(options?: { abbr?: boolean, context?: boolean }): string; }; @@ -74,12 +78,14 @@ declare namespace Faker { account(length?: number): string; accountName(): string; mask(length?: number, parens?: boolean, elipsis?: boolean): string; - amount(min?:number, max?: number, dec?: number, symbol?: string): string; + amount(min?: number, max?: number, dec?: number, symbol?: string): string; transactionType(): string; currencyCode(): string; currencyName(): string; currencySymbol(): string; bitcoinAddress(): string; + ethereumAddress(): string; + iban(formatted?: boolean): string bic(): string }; @@ -101,13 +107,12 @@ declare namespace Faker { shuffle(o: T[]): T[]; shuffle(): string[]; mustache(str: string, data: { [key: string]: string|((substring: string, ...args: any[]) => string) }): string; - createCard(): Faker.Card; - contextualCard(): Faker.ContextualCard; - userCard(): Faker.UserCard; - createTransaction(): Faker.Transaction; + createCard(): Card; + contextualCard(): ContextualCard; + userCard(): UserCard; + createTransaction(): Transaction; }; - image: { image(): string; avatar(): string; @@ -186,11 +191,12 @@ declare namespace Faker { objectElement(object?: { [key: string]: T }, field?: any): T; uuid(): string; boolean(): boolean; - word(): string; // TODO: have ability to return specific type of word? As in: noun, adjective, verb, etc + word(type?: string): string; words(count?: number): string; image(): string; locale(): string; alphaNumeric(count?: number): string; + hexaDecimal(count?: number): string; }; system: { @@ -201,8 +207,8 @@ declare namespace Faker { commonFileExt(): string; fileType(): string; fileExt(mimeType: string): string; - //directoryPath(): string; - //filePath(): string; + directoryPath(): string; + filePath(): string; semver(): string; }; @@ -315,10 +321,6 @@ declare module "faker/locale/de_CH" { export = fakerStatic; } -declare module "faker/locale/el_GR" { - export = fakerStatic; -} - declare module "faker/locale/en" { export = fakerStatic; } diff --git a/types/fontfaceobserver/index.d.ts b/types/fontfaceobserver/index.d.ts index 8f461dbd4f..a10214a57d 100644 --- a/types/fontfaceobserver/index.d.ts +++ b/types/fontfaceobserver/index.d.ts @@ -25,7 +25,7 @@ declare class FontFaceObserver { * @param testString If your font doesn't contain latin characters you can pass a custom test string. * @param timeout The default timeout for giving up on font loading is 3 seconds. You can increase or decrease this by passing a number of milliseconds. */ - load(testString?: string, timeout?: number): Promise; + load(testString?: string | null, timeout?: number): Promise; } declare module "fontfaceobserver" { diff --git a/types/gapi.auth2/index.d.ts b/types/gapi.auth2/index.d.ts index c5cfff0d9e..0acae5e2a7 100644 --- a/types/gapi.auth2/index.d.ts +++ b/types/gapi.auth2/index.d.ts @@ -27,7 +27,7 @@ declare namespace gapi.auth2 { * Signs in the user using the specified options. * If no option specified here, fallback to the options specified to gapi.auth2.init(). */ - signIn(options?: SigninOptions | SigninOptionsBuilder): any; + signIn(options?: SigninOptions | SigninOptionsBuilder): Promise; /** * Signs out all accounts from the application. diff --git a/types/geojson/geojson-tests.ts b/types/geojson/geojson-tests.ts index 4adb7f88f2..ce8c62418e 100644 --- a/types/geojson/geojson-tests.ts +++ b/types/geojson/geojson-tests.ts @@ -1,4 +1,10 @@ -let featureCollection: GeoJSON.FeatureCollection = { +import { + BBox, + Feature, FeatureCollection, GeometryCollection, LineString, + MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, GeometryObject +} from "geojson"; + +let featureCollection: FeatureCollection = { type: "FeatureCollection", features: [ { @@ -34,7 +40,7 @@ let featureCollection: GeoJSON.FeatureCollection = { geometry: { type: "Polygon", coordinates: [ - [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] + [[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]] ] }, properties: { @@ -44,17 +50,10 @@ let featureCollection: GeoJSON.FeatureCollection = { } } } - ], - crs: { - type: "link", - properties: { - href: "http://example.com/crs/42", - type: "proj4" - } - } + ] }; -let featureWithPolygon: GeoJSON.Feature = { +const featureWithPolygon: Feature = { type: "Feature", bbox: [-180.0, -90.0, 180.0, 90.0], geometry: { @@ -66,57 +65,57 @@ let featureWithPolygon: GeoJSON.Feature = { properties: null }; -let point: GeoJSON.Point = { +const point: Point = { type: "Point", coordinates: [100.0, 0.0] }; // This type is commonly used in the turf package -let pointCoordinates: number[] = point.coordinates; +const pointCoordinates: number[] = point.coordinates; -let lineString: GeoJSON.LineString = { +const lineString: LineString = { type: "LineString", - coordinates: [ [100.0, 0.0], [101.0, 1.0] ] + coordinates: [[100.0, 0.0], [101.0, 1.0]] }; -let polygon: GeoJSON.Polygon = { +const polygon: Polygon = { type: "Polygon", coordinates: [ - [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] + [[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]] ] }; -let polygonWithHole: GeoJSON.Polygon = { +const polygonWithHole: Polygon = { type: "Polygon", coordinates: [ - [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], - [ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ] + [[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], + [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]] ] }; -let multiPoint: GeoJSON.MultiPoint = { +const multiPoint: MultiPoint = { type: "MultiPoint", - coordinates: [ [100.0, 0.0], [101.0, 1.0] ] + coordinates: [[100.0, 0.0], [101.0, 1.0]] }; -let multiLineString: GeoJSON.MultiLineString = { +const multiLineString: MultiLineString = { type: "MultiLineString", coordinates: [ - [ [100.0, 0.0], [101.0, 1.0] ], - [ [102.0, 2.0], [103.0, 3.0] ] + [[100.0, 0.0], [101.0, 1.0]], + [[102.0, 2.0], [103.0, 3.0]] ] }; -let multiPolygon: GeoJSON.MultiPolygon = { +const multiPolygon: MultiPolygon = { type: "MultiPolygon", coordinates: [ [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], - [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] + [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] ] }; -let geometryCollection: GeoJSON.GeometryCollection = { +const geometryCollection: GeometryCollection = { type: "GeometryCollection", geometries: [ { @@ -125,16 +124,17 @@ let geometryCollection: GeoJSON.GeometryCollection = { }, { type: "LineString", - coordinates: [ [101.0, 0.0], [102.0, 1.0] ] + coordinates: [[101.0, 0.0], [102.0, 1.0]] } ] }; -let feature: GeoJSON.Feature = { +let feature: Feature = { type: "Feature", geometry: lineString, properties: null }; + feature = { type: "Feature", geometry: polygon, @@ -172,44 +172,37 @@ featureCollection = { { type: "Feature", geometry: lineString, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: polygon, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: polygonWithHole, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: multiPoint, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: multiLineString, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: multiPolygon, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: geometryCollection, - properties: {test: "OK"} + properties: { test: "OK" } } - ], - crs: { - type: "link", - properties: { - href: "http://example.com/crs/42", - type: "proj4" - } - } + ] }; // Allow access to custom properties -const pt: GeoJSON.Feature = { +const pt: Feature = { type: "Feature", properties: { foo: "bar", @@ -221,9 +214,14 @@ const pt: GeoJSON.Feature = { coordinates: [0, 0] } }; -pt.properties.foo; -pt.properties.hello; -pt.properties[1]; + +if (pt.properties) { + if (pt.properties.foo == null || pt.properties.hello == null || pt.properties[1] == null) { + throw TypeError("Properties should not be null or undefined."); + } +} else { + throw TypeError("Feature should have a 'properties' property."); +} // Optional generic for properties @@ -232,19 +230,21 @@ interface TestProperty { hello: string; } -const typedPropertiesFeature: GeoJSON.Feature = { +const testProps: TestProperty = { + foo: "bar", + hello: "world" +}; + +const typedPropertiesFeature: Feature = { type: "Feature", - properties: { - foo: "bar", - hello: "world", - }, + properties: testProps, geometry: { type: "Point", coordinates: [0, 0] } }; -const typedPropertiesFeatureCollection: GeoJSON.FeatureCollection = { +const typedPropertiesFeatureCollection: FeatureCollection = { type: "FeatureCollection", features: [typedPropertiesFeature] }; diff --git a/types/geojson/index.d.ts b/types/geojson/index.d.ts index b916179fac..e6783255eb 100644 --- a/types/geojson/index.d.ts +++ b/types/geojson/index.d.ts @@ -1,123 +1,165 @@ -// Type definitions for GeoJSON Format Specification Revision 1.0 -// Project: http://geojson.org/ +// Type definitions for geojson 7946.0 +// Project: https://geojson.org/ // Definitions by: Jacob Bruun // Arne Schubert +// Jeff Jacobson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 +// Note: as of the RFC 7946 version of GeoJSON, Coordinate Reference Systems +// are no longer supported. (See https://tools.ietf.org/html/rfc7946#appendix-B)} + export as namespace GeoJSON; -/*** - * http://geojson.org/geojson-spec.html#geojson-objects +/** + * The valid values for the "type" property of GeoJSON geometry objects. + * https://tools.ietf.org/html/rfc7946#section-1.4 + */ +export type GeoJsonGeometryTypes = "Point" | "LineString" | "MultiPoint" | "Polygon" | "MultiLineString" | + "MultiPolygon" | "GeometryCollection"; + +/** + * The value values for the "type" property of GeoJSON Objects. + * https://tools.ietf.org/html/rfc7946#section-1.4 + */ +export type GeoJsonTypes = "FeatureCollection" | "Feature" | GeoJsonGeometryTypes; + +/** + * Bounding box + * https://tools.ietf.org/html/rfc7946#section-5 + */ +export type BBox = [number, number, number, number] | [number, number, number, number, number, number]; + +/** + * A Position is an array of coordinates. + * https://tools.ietf.org/html/rfc7946#section-3.1.1 + * Array should contain between two and three elements. + * The previous GeoJSON specification allowed more elements (e.g., which could be used to represent M values), + * but the current specification only allows X, Y, and (optionally) Z to be defined. + */ +export type Position = number[]; // [number, number] | [number, number, number]; + +/** + * The base GeoJSON object. + * https://tools.ietf.org/html/rfc7946#section-3 + * The GeoJSON specification also allows foreign members + * (https://tools.ietf.org/html/rfc7946#section-6.1) + * Developers should use "&" type in TypeScript or extend the interface + * to add these foreign members. */ export interface GeoJsonObject { - type: string; - bbox?: number[]; - crs?: CoordinateReferenceSystem; + // Don't include foreign members directly into this type def. + // in order to preserve type safety. + // [key: string]: any; + /** + * Specifies the type of GeoJSON object. + */ + type: GeoJsonTypes; + /** + * Bounding box of the coordinate range of the object's Geometries, Features, or Feature Collections. + * https://tools.ietf.org/html/rfc7946#section-5 + */ + bbox?: BBox; } -/*** - * http://geojson.org/geojson-spec.html#positions - */ -export type Position = number[]; - -/*** - * http://geojson.org/geojson-spec.html#geometry-objects - */ -export interface DirectGeometryObject extends GeoJsonObject { - coordinates: Position[][][] | Position[][] | Position[] | Position; -} /** - * GeometryObject supports geometry collection as well + * A geometry object. + * https://tools.ietf.org/html/rfc7946#section-3 */ -export type GeometryObject = DirectGeometryObject | GeometryCollection; +export interface GeometryObject extends GeoJsonObject { + type: GeoJsonGeometryTypes; +} -/*** - * http://geojson.org/geojson-spec.html#point +/** + * Point geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.2 */ -export interface Point extends DirectGeometryObject { +export interface Point extends GeometryObject { type: "Point"; coordinates: Position; } -/*** - * http://geojson.org/geojson-spec.html#multipoint +/** + * MultiPoint geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.3 */ -export interface MultiPoint extends DirectGeometryObject { +export interface MultiPoint extends GeometryObject { type: "MultiPoint"; coordinates: Position[]; } -/*** - * http://geojson.org/geojson-spec.html#linestring +/** + * LineString geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.4 */ -export interface LineString extends DirectGeometryObject { +export interface LineString extends GeometryObject { type: "LineString"; coordinates: Position[]; } -/*** - * http://geojson.org/geojson-spec.html#multilinestring +/** + * MultiLineString geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.5 */ -export interface MultiLineString extends DirectGeometryObject { +export interface MultiLineString extends GeometryObject { type: "MultiLineString"; coordinates: Position[][]; } -/*** - * http://geojson.org/geojson-spec.html#polygon +/** + * Polygon geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.6 */ -export interface Polygon extends DirectGeometryObject { +export interface Polygon extends GeometryObject { type: "Polygon"; coordinates: Position[][]; } -/*** - * http://geojson.org/geojson-spec.html#multipolygon +/** + * MultiPolygon geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.7 */ -export interface MultiPolygon extends DirectGeometryObject { +export interface MultiPolygon extends GeometryObject { type: "MultiPolygon"; coordinates: Position[][][]; } -/*** - * http://geojson.org/geojson-spec.html#geometry-collection +/** + * Geometry Collection + * https://tools.ietf.org/html/rfc7946#section-3.1.8 */ -export interface GeometryCollection extends GeoJsonObject { +export interface GeometryCollection extends GeometryObject { type: "GeometryCollection"; - geometries: GeometryObject[]; + geometries: Array; } -/*** +export type GeoJsonProperties = { [name: string]: any; } | null; + +/** + * A feature object which contains a geometry and associated properties. * https://tools.ietf.org/html/rfc7946#section-3.2 */ -export interface Feature extends GeoJsonObject { +export interface Feature extends GeoJsonObject { type: "Feature"; - geometry: G; - properties: P; + /** + * The feature's geometry + */ + geometry: G | null; + /** + * A value that uniquely identifies this feature in a + * https://tools.ietf.org/html/rfc7946#section-3.2. + */ id?: string | number; + /** + * Properties associated with this feature. + */ + properties: P | null; } -/*** - * http://geojson.org/geojson-spec.html#feature-collection-objects +/** + * A collection of feature objects. + * https://tools.ietf.org/html/rfc7946#section-3.3 */ -export interface FeatureCollection extends GeoJsonObject { - type: "FeatureCollection"; +export interface FeatureCollection extends GeoJsonObject { features: Array>; } - -/*** - * http://geojson.org/geojson-spec.html#coordinate-reference-system-objects - */ -export interface CoordinateReferenceSystem { - type: string; - properties: any; -} - -export interface NamedCoordinateReferenceSystem extends CoordinateReferenceSystem { - properties: { name: string }; -} - -export interface LinkedCoordinateReferenceSystem extends CoordinateReferenceSystem { - properties: { href: string; type: string }; -} diff --git a/types/google-apps-script/google-apps-script.card.d.ts b/types/google-apps-script/google-apps-script.card.d.ts new file mode 100644 index 0000000000..62d497eb4f --- /dev/null +++ b/types/google-apps-script/google-apps-script.card.d.ts @@ -0,0 +1,657 @@ +// Type definitions for Google Apps Script 2017-10-30 +// Project: https://developers.google.com/apps-script/ +// Definitions by: dhayab +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace GoogleAppsScript { + export module Card { + export interface Action { + /** + * Sets the name of the callback function to be called. + */ + setFunctionName(functionName: string): Action; + /** + * Sets the loading indicator that displays while the action is in progress. + */ + setLoadIndicator(loadIndicator: LoadIndicator): Action; + /** + * Allows custom parameters to be passed to the callback function. + */ + setParameters(parameters: { [key: string]: string }): Action; + } + + export interface ActionEvent { + messageMetadata: { + /** + * An access token. You can use this to enable access to user data using temporary Gmail add-on scopes. + */ + accessToken: string; + /** + * The message ID of the thread open in the Gmail UI. + */ + messageId: string; + } + /** + * Indicates where the event originates (web, iOS, or Android). + */ + clientPlatform: string; + /** + * The current values of all form widgets in the card, restricted to one value per widget. The keys are the string IDs associated with the widgets. + * + * The event object provides `formInput` as a convenience for when you need to read data from multiple widgets with expected singular values, such as text inputs and switches. + * + * For multi-valued widgets such as checkboxes, you can read each value from `formInputs` instead. + */ + formInput: { [key: string]: string }; + /** + * The current values of widgets in the card, presented in arrays. The keys are the string IDs associated with the widget. + * + * For single-valued widgets, the value is presented in a single-element array. For multi-valued widgets such as checkboxes, all the values are presented in an array. + */ + formInputs: { [key: string]: string[] }; + /** + * Any additional parameters you supply to the `Action` using `Action.setParameters()`. + */ + parameters: { [key: string]: string }; + } + + export interface ActionResponse { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + } + + export interface ActionResponseBuilder { + /** + * Builds the current action response and validates it. + */ + build(): ActionResponse; + /** + * Sets the response to `Navigation` action. + */ + setNavigation(navigation: Navigation): ActionResponseBuilder; + /** + * Sets the notification to display when the action is activated. + */ + setNotification(notification: Notification): ActionResponseBuilder; + /** + * Sets the URL to navigate to when the action is activated. + */ + setOpenLink(openLink: OpenLink): ActionResponseBuilder; + } + + export interface AuthorizationAction { + /** + * Sets the authorization URL that user is taken to from the authorization prompt. + */ + setAuthorizationUrl(authorizationUrl: string): AuthorizationAction; + } + + export interface AuthorizationException { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + /** + * Sets the authorization URL that user is taken to from the authorization prompt. + */ + setAuthorizationUrl(authUrl: string): AuthorizationException; + /** + * The name of a function to call to generate a custom authorization prompt. + */ + setCustomUiCallback(callback: string): AuthorizationException; + /** + * Sets the name that is displayed to the user when asking for authorization. + */ + setResourceDisplayName(name: string): AuthorizationException; + /** + * Triggers this exception to be thrown. + */ + throwException(): void; + } + + interface Button extends Widget { + /** + * Sets an authorization action that opens a URL to the authorization flow when the object is clicked. + */ + setAuthorizationAction(action: AuthorizationAction): T; + /** + * Sets an action that composes a draft email when the object is clicked. + */ + setComposeAction(action: Action, composedEmailType: ComposedEmailType): T; + /** + * Sets an action that executes when the object is clicked. + */ + setOnClickAction(action: Action): T; + /** + * Sets an action that opens a URL in a tab when the object is clicked. + */ + setOnClickOpenLinkAction(action: Action): T; + /** + * Sets a URL to be opened when the object is clicked. + */ + setOpenLink(openLink: OpenLink): T; + } + + export interface ButtonSet extends Widget { + /** + * Adds a button. + */ + addButton(button: Button): ButtonSet; + } + + export interface Card { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + } + + export interface CardAction extends Button { + /** + * Sets the menu text for this action. + */ + setText(text: string): CardAction; + } + + export interface CardBuilder { + /** + * Adds a CardAction to this Card. + */ + addCardAction(cardAction: CardAction): CardBuilder; + /** + * Adds a section to this card. + */ + addSection(section: CardSection): CardBuilder; + /** + * Builds the current card and validates it. + */ + build(): Card; + /** + * Sets the header for this card. + */ + setHeader(cardHeader: CardHeader): CardBuilder; + /** + * Sets the name for this card. + */ + setName(name: string): CardBuilder; + } + + export interface CardHeader { + /** + * Sets the alternative text for the header image. + */ + setImageAltText(imageAltText: string): CardHeader; + /** + * Sets the cropping of the icon in the card header. + */ + setImageStyle(imageStyle: ImageStyle): CardHeader; + /** + * Sets the image to use in the header by providing its URL. + */ + setImageUrl(imageUrl: string): CardHeader; + /** + * Sets the subtitle of the card header. + */ + setSubtitle(subtitle: string): CardHeader; + /** + * Sets the title of the card header. + */ + setTitle(title: string): CardHeader; + } + + export interface CardSection { + /** + * Adds the given widget to this section. + */ + addWidget(widget: Widget): CardSection; + /** + * Sets whether the section can be collapsed. + */ + setCollapsible(collapsible: boolean): CardSection; + /** + * Sets the header of the section. + */ + setHeader(header: string): CardSection; + /** + * Sets the number of widgets that are still shown when this section is collapsed. + */ + setNumUncollapsibleWidgets(numUncollapsibleWidgets: Integer): CardSection; + } + + export interface CardService { + /** + * Specifies whether the composed email is a standalone or reply draft. + */ + ComposedEmailType: typeof ComposedEmailType; + /** + * Predefined icons that can be used in various UI objects, such as ImageButton or KeyValue widgets. + */ + Icon: typeof Icon; + /** + * Defines an image cropping style. + */ + ImageStyle: typeof ImageStyle; + /** + * Specifies the type of loading or progress indicator to display while an Action is being processed. + */ + LoadIndicator: typeof LoadIndicator; + /** + * Type of notification to show. + */ + NotificationType: typeof NotificationType; + /** + * Specifies what to do when a URL opened through an OpenLink is closed. + * + * When a link is opened, the client either forgets about it or waits until the window is closed. The implementation depends on the client platform capabilities. OnClose may cause OpenAs to be ignored; if the client platform cannot support both selected values together, OnClose takes precedence. + */ + OnClose: typeof OnClose; + /** + * Specifies how to open a URL. + * + * The client can open a URL as either a full size window (if that is the frame used by the client), or an overlay (such as a pop-up). The implementation depends on the client platform capabilities, and the value selected may be ignored if the client does not support it. FULL_SIZE is supported by all clients. + * + * Using OnClose may cause OpenAs to be ignored; if the client platform cannot support both selected values together, OnClose takes precedence. + */ + OpenAs: typeof OpenAs; + /** + * Type of selection input. + */ + SelectionInputType: typeof SelectionInputType; + /** + * Creates a new `Action`. + */ + newAction(): Action; + /** + * Creates a new `ActionResponseBuilder`. + */ + newActionResponseBuilder(): ActionResponseBuilder; + /** + * Creates a new `AuthorizationAction`. + */ + newAuthorizationAction(): AuthorizationAction; + /** + * Creates a new `AuthorizationException`. + */ + newAuthorizationException(): AuthorizationException; + /** + * Creates a new `ButtonSet`. + */ + newButtonSet(): ButtonSet; + /** + * Creates a new `CardAction`. + */ + newCardAction(): CardAction; + /** + * Creates a new `CardBuilder`. + */ + newCardBuilder(): CardBuilder; + /** + * Creates a new `CardHeader`. + */ + newCardHeader(): CardHeader; + /** + * Creates a new `CardSection`. + */ + newCardSection(): CardSection; + /** + * Creates a new `ComposeActionResponseBuilder`. + */ + newComposeActionResponseBuilder(): ComposeActionResponseBuilder; + /** + * Creates a new `Image`. + */ + newImage(): Image; + /** + * Creates a new `ImageButton`. + */ + newImageButton(): ImageButton; + /** + * Creates a new `KeyValue`. + */ + newKeyValue(): KeyValue; + /** + * Creates a new `Navigation`. + */ + newNavigation(): Navigation; + /** + * Creates a new `Notification`. + */ + newNotification(): Notification; + /** + * Creates a new `OpenLink`. + */ + newOpenLink(): OpenLink; + /** + * Creates a new `SelectionInput`. + */ + newSelectionInput(): SelectionInput; + /** + * Creates a new `Suggestions`. + */ + newSuggestions(): Suggestions; + /** + * Creates a new `SuggestionsResponseBuilder`. + */ + newSuggestionsResponseBuilder(): SuggestionsResponseBuilder; + /** + * Creates a new `Switch`. + */ + newSwitch(): Switch; + /** + * Creates a new `TextButton`. + */ + newTextButton(): TextButton; + /** + * Creates a new `TextInput`. + */ + newTextInput(): TextInput; + /** + * Creates a new `TextParagraph`. + */ + newTextParagraph(): TextParagraph; + /** + * Creates a new `UniversalActionResponseBuilder`. + */ + newUniversalActionResponseBuilder(): UniversalActionResponseBuilder; + } + + export interface ComposeActionResponse { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + } + + export interface ComposeActionResponseBuilder { + /** + * Builds the current compose action response and validates it. + */ + build(): ComposeActionResponse; + /** + * Sets the draft `GmailMessage` created using `GmailMessage.createDraftReply(body)` or similar functions. + */ + setGmailDraft(draft: Gmail.GmailDraft): ComposeActionResponseBuilder; + } + + export interface Image extends Button { + /** + * Sets the alternative text of the image for accessibility. + */ + setAltText(altText: string): Image; + /** + * Sets the URL of the image. + */ + setImageUrl(url: string): Image; + } + + export interface ImageButton extends Button { + /** + * Sets the alternative text of the button for accessibility. + */ + setAltText(altText: string): ImageButton; + /** + * Sets a predefined Icon to display on the button. + */ + setIcon(icon: Icon): ImageButton; + /** + * Sets the URL of an image to use as this button's icon. + */ + setIconUrl(url: string): ImageButton; + } + + export interface KeyValue extends Button { + /** + * Sets the label text to be used as the key. + */ + setBottomLabel(text: string): KeyValue; + /** + * Sets the Button that is displayed to the right of the context. + */ + setButton(button: Button): KeyValue; + /** + * Sets the text to be used as the value. + */ + setContent(text: string): KeyValue; + /** + * Sets the icon to be used as the key. + */ + setIcon(icon: Icon): KeyValue; + /** + * Sets the alternative text for the icon. + */ + setIconAltText(altText: string): KeyValue; + /** + * Sets the URL of the icon to be used as the key. + */ + setIconUrl(url: string): KeyValue; + /** + * Sets whether the value text should be displayed on a single line or multiple lines. + */ + setMultiline(multiline: boolean): KeyValue; + /** + * Sets the Switch that is displayed to the right of the content. + */ + setSwitch(switchToSet: Switch): KeyValue; + /** + * Sets the label text to be used as the key. + */ + setTopLabel(text: string): KeyValue; + } + + export interface Navigation { + /** + * Pops a card from the navigation stack. + */ + popCard(): Navigation; + /** + * Pops to the specified card by its card name. + */ + popToNamedCard(cardName: string): Navigation; + /** + * Pops the card stack to the root card. + */ + popToRoot(): Navigation; + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + /** + * Pushes the given card onto the stack. + */ + pushCard(card: Card): Navigation; + /** + * Does an in-place replacement of the current card. + */ + updateCard(card: Card): Navigation; + } + + export interface Notification { + /** + * Sets the text to show in the notification. + */ + setText(text: string): Notification; + /** + * Sets the notification type to show. + */ + setType(type: NotificationType): Notification; + } + + export interface OpenLink { + /** + * Sets the behavior of the URL action when the URL window or tab is closed. + */ + setOnClose(onClose: OnClose): OpenLink; + /** + * Sets the behavior of URL when it is opened. + */ + setOpenAs(openAs: OpenAs): OpenLink; + /** + * Sets the URL to be opened. + */ + setUrl(url: string): OpenLink; + } + + export interface SelectionInput extends Widget { + /** + * Adds a new item that can be selected. + */ + addItem(text: Object, value: Object, selected: boolean): SelectionInput; + /** + * Sets the key that identifies this selection input in the event object that is generated when there is a UI interaction. + */ + setFieldName(fieldName: string): SelectionInput; + /** + * Sets an Action to be performed whenever the selection input changes. + */ + setOnChangeAction(action: Action): SelectionInput; + /** + * Sets the title to be shown ahead of the input field. + */ + setTitle(title: string): SelectionInput; + /** + * Sets the type of this input. + */ + setType(type: SelectionInputType): SelectionInput; + } + + export interface Suggestions { + /** + * Add a text suggestion. + */ + addSuggestion(suggestion: string): Suggestions; + /** + * Add a list of text suggestions. + */ + addSuggestions(suggestions: string[]): Suggestions; + } + + export interface SuggestionsResponse { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + } + + export interface SuggestionsResponseBuilder { + /** + * Builds the current suggestions response and validates it. + */ + build(): SuggestionsResponse; + /** + * Sets the suggestions used in auto complete in text fields. + */ + setSuggestions(suggestions: Suggestions): SuggestionsResponseBuilder; + } + + export interface Switch extends Widget { + /** + * Sets the key that identified this switch in the event object that is generated when there is a UI interaction. + */ + setFieldName(fieldName: string): Switch; + /** + * Sets the action to take when the switch is toggled. + */ + setOnChangeAction(action: Action): Switch; + /** + * Sets whether this switch should start as selected or unselected. + */ + setSelected(selected: boolean): Switch; + /** + * Sets the value that is sent as the form input when this switch is toggled on. + */ + setValue(value: string): Switch; + } + + export interface TextButton extends Button { + /** + * Sets the text to be displayed on the button. + */ + setText(text: string): TextButton; + } + + export interface TextInput extends Widget { + /** + * Sets the key that identifies this text input in the event object that is generated when there is a UI interaction. + */ + setFieldName(fieldName: string): TextInput; + /** + * Sets a hint for the text input. + */ + setHint(hint: string): TextInput; + /** + * Sets whether the input text shows on one line or multiple lines. + */ + setMultiline(multiline: boolean): TextInput; + /** + * Sets an action to be performed whenever the text input changes. + */ + setOnChangeAction(action: Action): TextInput; + /** + * Sets the suggestions for autocompletion in the text field. + */ + setSuggestions(suggestions: Suggestions): TextInput; + /** + * Sets the callback action to fetch suggestions based on user input for autocompletion. + */ + setSuggestionsAction(suggestionsAction: Action): TextInput + /** + * Sets the title to be shown above the input field. + */ + setTitle(title: string): TextInput; + /** + * Sets the pre-filled value to be set in the input field. + */ + setValue(value: string): TextInput; + } + + export interface TextParagraph extends Widget { + /** + * Sets the text of the paragraph. + */ + setText(text: string): TextParagraph; + } + + export interface UniversalActionResponse { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + } + + export interface UniversalActionResponseBuilder { + /** + * Builds the current universal action response and validates it. + */ + build(): UniversalActionResponse; + /** + * Displays the add-on with the specified cards. + */ + displayAddOnCards(cardObjects: Card[]): UniversalActionResponseBuilder; + /** + * Sets the URL to open when the universal action is selected. + */ + setOpenLink(openLink: OpenLink): UniversalActionResponseBuilder; + } + + export interface Widget { } + + export enum ComposedEmailType { REPLY_AS_DRAFT, STANDALONE_DRAFT } + export enum Icon { NONE, AIRPLANE, BOOKMARK, BUS, CAR, CLOCK, CONFIRMATION_NUMBER_ICON, DOLLAR, DESCRIPTION, EMAIL, EVENT_PERFORMER, EVENT_SEAT, FLIGHT_ARRIVAL, FLIGHT_DEPARTURE, HOTEL, HOTEL_ROOM_TYPE, INVITE, MAP_PIN, MEMBERSHIP, MULTIPLE_PEOPLE, OFFER, PERSON, PHONE, RESTAURANT_ICON, SHOPPING_CART, STAR, STORE, TICKET, TRAIN, VIDEO_CAMERA, VIDEO_PLAY } + export enum ImageStyle { SQUARE, CIRCLE } + export enum LoadIndicator { SPINNER, NONE } + export enum NotificationType { INFO, ERROR, WARNING } + export enum OnClose { NOTHING, RELOAD_ADD_ON } + export enum OpenAs { FULL_SIZE, OVERLAY } + export enum SelectionInputType { CHECK_BOX, RADIO_BUTTON, DROPDOWN } + } +} + +/** + * CardService provides the ability to create generic cards used across different Google extensibility products, such as [Gmail add-ons](https://developers.google.com/gmail/add-ons). + */ +declare var CardService: GoogleAppsScript.Card.CardService; diff --git a/types/google-apps-script/google-apps-script.gmail.d.ts b/types/google-apps-script/google-apps-script.gmail.d.ts index 41be4dbb56..4967f53394 100644 --- a/types/google-apps-script/google-apps-script.gmail.d.ts +++ b/types/google-apps-script/google-apps-script.gmail.d.ts @@ -1,6 +1,7 @@ // Type definitions for Google Apps Script 2017-05-12 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen +// dhayab // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -12,12 +13,16 @@ declare namespace GoogleAppsScript { * Provides access to Gmail threads, messages, and labels. */ export interface GmailApp { + createDraft(recipient: string, subject: string, body: string): GmailDraft; + createDraft(recipient: string, subject: string, body: string, options: GmailDraftOptions): GmailDraft; createLabel(name: string): GmailLabel; deleteLabel(label: GmailLabel): GmailApp; getAliases(): string[]; getChatThreads(): GmailThread[]; getChatThreads(start: Integer, max: Integer): GmailThread[]; + getDraft(draftId: string): GmailDraft; getDraftMessages(): GmailMessage[]; + getDrafts(): GmailDraft[]; getInboxThreads(): GmailThread[]; getInboxThreads(start: Integer, max: Integer): GmailThread[]; getInboxUnreadCount(): Integer; @@ -68,6 +73,7 @@ declare namespace GoogleAppsScript { search(query: string, start: Integer, max: Integer): GmailThread[]; sendEmail(recipient: string, subject: string, body: string): GmailApp; sendEmail(recipient: string, subject: string, body: string, options: Object): GmailApp; + setCurrentMessageAccessToken(accessToken: string): void; starMessage(message: GmailMessage): GmailApp; starMessages(messages: GmailMessage[]): GmailApp; unstarMessage(message: GmailMessage): GmailApp; @@ -112,6 +118,72 @@ declare namespace GoogleAppsScript { getAllBlobs(): Base.Blob[]; } + export interface GmailDraft { + /** + * Deletes this draft message. + */ + deleteDraft(): void; + /** + * Gets the ID of this draft message. + */ + getId(): string; + /** + * Returns a GmailMessage representing this draft. + */ + getMessage(): GmailMessage; + /** + * Returns the ID of the `GmailMessage` representing this draft. + */ + getMessageId(): string; + /** + * Sends this draft email message. + */ + send(): GmailMessage; + /** + * Replaces the contents of this draft message. + */ + update(recipient: string, subject: string, body: string): GmailDraft; + /** + * Replaces the contents of this draft message using optional arguments. + */ + update(recipient: string, subject: string, body: string, options: GmailDraftOptions): GmailDraft; + } + + export type GmailDraftOptions = { + /** + * An array of files to send with the email. + */ + attachments?: Base.BlobSource[]; + /** + * A comma-separated list of email addresses to BCC. + */ + bcc?: string; + /** + * A comma-separated list of email addresses to CC. + */ + cc?: string; + /** + * The address that the email should be sent from, which must be one of the values returned by `GmailApp.getAliases()`. + */ + from?: string; + /** + * If set, devices capable of rendering HTML will use it instead of the required body argument; you can add an optional `inlineImages` field in HTML body if you have inlined images for your email. + */ + htmlBody?: string; + /** + * A JavaScript object containing a mapping from image key (`String`) to image data (`BlobSource`) ; this assumes that the `htmlBody` parameter is used and contains references to these images in the format ``. + */ + inlineImages?: { [imageKey: string]: Base.BlobSource }; + /** + * The name of the sender of the email (default: the user's name). + */ + name?: string; + /** + * An email address to use as the default reply-to address (default: the user's email address). + */ + replyTo?: string; + } + /** * A user-created label in a user's Gmail account. */ @@ -131,6 +203,10 @@ declare namespace GoogleAppsScript { * A message in a user's Gmail account. */ export interface GmailMessage { + createDraftReply(body: string): GmailDraft; + createDraftReply(body: string, options: GmailDraftOptions): GmailDraft; + createDraftReplyAll(body: string): GmailDraft; + createDraftReplyAll(body: string, options: GmailDraftOptions): GmailDraft; forward(recipient: string): GmailMessage; forward(recipient: string, options: Object): GmailMessage; getAttachments(): GmailAttachment[]; @@ -169,6 +245,10 @@ declare namespace GoogleAppsScript { */ export interface GmailThread { addLabel(label: GmailLabel): GmailThread; + createDraftReply(body: string): GmailDraft; + createDraftReply(body: string, options: GmailDraftOptions): GmailDraft; + createDraftReplyAll(body: string): GmailDraft; + createDraftReplyAll(body: string, options: GmailDraftOptions): GmailDraft; getFirstMessageSubject(): string; getId(): string; getLabels(): GmailLabel[]; diff --git a/types/google-apps-script/index.d.ts b/types/google-apps-script/index.d.ts index f80598c391..0e4ca164a9 100644 --- a/types/google-apps-script/index.d.ts +++ b/types/google-apps-script/index.d.ts @@ -7,6 +7,7 @@ /// /// /// +/// /// /// /// diff --git a/types/googlemaps/index.d.ts b/types/googlemaps/index.d.ts index 66ddb31f5d..5e977257b8 100644 --- a/types/googlemaps/index.d.ts +++ b/types/googlemaps/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Google Maps JavaScript API 3.29 +// Type definitions for Google Maps JavaScript API 3.30 // Project: https://developers.google.com/maps/ -// Definitions by: Folia A/S , Chris Wrench , Kiarash Ghiaseddin , Grant Hutchins , Denis Atyasov , Michael McMullin , Martin Costello +// Definitions by: Folia A/S , Chris Wrench , Kiarash Ghiaseddin , Grant Hutchins , Denis Atyasov , Michael McMullin , Martin Costello , Sven Kreiss // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* @@ -2697,7 +2697,7 @@ declare namespace google.maps { * Accepted values are 'marker', 'polygon', 'polyline', 'rectangle', 'circle', or null. A drawing mode * of null means that the user can interact with the map as normal, and clicks do not draw anything. */ - drawingMode?: OverlayType; + drawingMode?: OverlayType | null; /** * The Map to which the DrawingManager is attached, which is the Map on which the overlays created * will be placed. diff --git a/types/graphql/type/definition.d.ts b/types/graphql/type/definition.d.ts index 7f84c875fb..52df7bd46c 100644 --- a/types/graphql/type/definition.d.ts +++ b/types/graphql/type/definition.d.ts @@ -455,6 +455,7 @@ export class GraphQLEnumType { constructor(config: GraphQLEnumTypeConfig); getValues(): GraphQLEnumValue[]; getValue(name: string): GraphQLEnumValue; + isValidValue(value: any): boolean; serialize(value: any): string; parseValue(value: any): any; parseLiteral(valueNode: ValueNode): any; diff --git a/types/gzip-size/gzip-size-tests.ts b/types/gzip-size/gzip-size-tests.ts index f07d99bd50..70ea15b5e6 100644 --- a/types/gzip-size/gzip-size-tests.ts +++ b/types/gzip-size/gzip-size-tests.ts @@ -1,7 +1,16 @@ +import fs = require('fs'); import gzipSize = require('gzip-size'); const string = 'Lorem ipsum dolor sit amet.'; console.log(string.length); +gzipSize(string).then(size => console.log(size)); + console.log(gzipSize.sync(string)); + +const stream = fs.createReadStream("index.d.ts"); +const gstream = stream.pipe(gzipSize.stream()).on("gzip-size", size => console.log(size)); +console.log(gstream.gzipSize); // Could be a number or undefined. Recommended to use "gzip-size" event instead + +gzipSize.file("index.d.ts").then(size => console.log(size)); diff --git a/types/gzip-size/index.d.ts b/types/gzip-size/index.d.ts index cab8ec225b..66251e0da8 100644 --- a/types/gzip-size/index.d.ts +++ b/types/gzip-size/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for gzip-size 4.0 +// Type definitions for gzip-size 4.1 // Project: https://github.com/sindresorhus/gzip-size // Definitions by: York Yao // Jimi van der Woning +// Andre Wiggins // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -9,11 +10,45 @@ import * as stream from 'stream'; import * as zlib from 'zlib'; +interface GzipSizeStream extends stream.PassThrough { + on(event: string, listener: (...args: any[]) => void): this; + on(event: "gzip-size", listener: (size: number) => void): this; + + /** + * Contains the gzip size of the stream after it is finished. + * Since this happens asynchronously, it is recommended you use + * the `.on("gzip-size", size => console.log(size))` method instead + */ + gzipSize?: number; +} + +/** + * Returns a Promise for the size. + * @param input A string or Buffer to determine the gzip size of + * @param options Any zlib option + */ declare function gzipSize(input: string | Buffer, options?: zlib.ZlibOptions): Promise; declare namespace gzipSize { + /** + * Returns the size synchronously + * @param input A string or Buffer to determine the gzip size of + * @param options Any zlib option + */ function sync(input: string | Buffer, options?: zlib.ZlibOptions): number; - function stream(options?: zlib.ZlibOptions): stream.PassThrough; + + /** + * Returns a stream.PassThrough. The stream emits a gzip-size event and has a gzipSize property. + * @param options Any zlib option + */ + function stream(options?: zlib.ZlibOptions): GzipSizeStream; + + /** + * Returns a Promise for the size of the file. + * @param path The path to the file + * @param options Any zlib option + */ + function file(path: string, options?: zlib.ZlibOptions): Promise; } export = gzipSize; diff --git a/types/haversine/haversine-tests.ts b/types/haversine/haversine-tests.ts index 043d7d5898..5c068ea4b3 100644 --- a/types/haversine/haversine-tests.ts +++ b/types/haversine/haversine-tests.ts @@ -1,11 +1,11 @@ import haversine = require('haversine'); -const start: haversine.Coordinate = { +const start: haversine.CoordinateLongitudeLatitude = { longitude: 48.1548256, latitude: 11.4017529 }; -const end: haversine.Coordinate = { +const end: haversine.CoordinateLongitudeLatitude = { longitude: 52.5065133, latitude: 13.1445551 }; @@ -16,3 +16,51 @@ const options: haversine.Options = { }; haversine(start, end, options); + +const startShort: haversine.CoordinateLonLat = { + lon: 48.1548256, + lat: 11.4017529 +}; + +const endShort: haversine.CoordinateLonLat = { + lon: 52.5065133, + lat: 13.1445551 +}; + +const optionsShort: haversine.Options = { + format: '{lon,lat}' +}; + +haversine(startShort, endShort, optionsShort); + +const startLatLon: haversine.LatLonTuple = [11.4017529, 48.1548256]; + +const endLatLon: haversine.LatLonTuple = [13.1445551, 52.5065133]; + +const optionsLatLon: haversine.Options = { + format: '[lat,lon]' +}; + +haversine(startLatLon, endLatLon, optionsLatLon); + +const startGeoJSON = { + type: "Feature", + geometry: { + type: "LineString", + coordinates: startLatLon + } +}; + +const endGeoJSON = { + type: "Feature", + geometry: { + type: "LineString", + coordinates: endLatLon + } +}; + +const optionsGeoJSON: haversine.Options = { + format: 'geojson' +}; + +haversine(startGeoJSON, endGeoJSON, optionsGeoJSON); diff --git a/types/haversine/index.d.ts b/types/haversine/index.d.ts index 6fed860d8b..5f6d1e9173 100644 --- a/types/haversine/index.d.ts +++ b/types/haversine/index.d.ts @@ -1,14 +1,29 @@ -// Type definitions for haversine 1.0 +// Type definitions for haversine 1.1 // Project: https://github.com/njj/haversine // Definitions by: Christian Rackerseder // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace haversine { - interface Coordinate { + interface CoordinateLongitudeLatitude { longitude: number; latitude: number; } + interface CoordinateLonLat { + lon: number; + lat: number; + } + + type LatLonTuple = [number, number]; + + interface GeoJSON { + geometry: { + coordinates: LatLonTuple + }; + } + + type Coordinate = (CoordinateLongitudeLatitude | CoordinateLonLat | LatLonTuple | GeoJSON); + interface Options { /** * Unit of measurement applied to result. Default: "km". @@ -18,6 +33,10 @@ declare namespace haversine { * If passed, will result in library returning boolean value of whether or not the start and end points are within that supplied threshold. Default: null. */ threshold?: number; + /** + * Format of coordinate arguments. + */ + format?: '[lat,lon]' | '[lon,lat]' | '{lon,lat}' | 'geojson'; } } diff --git a/types/hex-rgba/hex-rgba-tests.ts b/types/hex-rgba/hex-rgba-tests.ts new file mode 100644 index 0000000000..f7ee8cf285 --- /dev/null +++ b/types/hex-rgba/hex-rgba-tests.ts @@ -0,0 +1,3 @@ +import hexToRgba = require('hex-rgba'); + +const rgba = hexToRgba('#1b2b34', 40); diff --git a/types/hex-rgba/index.d.ts b/types/hex-rgba/index.d.ts new file mode 100644 index 0000000000..ba4205a73f --- /dev/null +++ b/types/hex-rgba/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for hex-rgba 1.0 +// Project: https://github.com/developersoul/hex-rgba#readme +// Definitions by: Andrew Makarov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = hexToRgba; + +declare function hexToRgba(hex: string, opacity: number): string; diff --git a/types/hex-rgba/tsconfig.json b/types/hex-rgba/tsconfig.json new file mode 100644 index 0000000000..82f2e3808e --- /dev/null +++ b/types/hex-rgba/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "hex-rgba-tests.ts" + ] +} diff --git a/types/hex-rgba/tslint.json b/types/hex-rgba/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hex-rgba/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index 3ce85ed9e2..f7f3759432 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -5266,6 +5266,9 @@ declare namespace Highcharts { * interfaces (AreaChartSeriesOptions, LineChartSeriesOptions, etc.) */ interface IndividualSeriesOptions { + size?: number | string; + innerSize?: number | string; + type?: string; /** * The main color or the series. In line type series it applies to the line and the point markers unless otherwise diff --git a/types/highlight.js/index.d.ts b/types/highlight.js/index.d.ts index d691811b47..f96be1c06f 100644 --- a/types/highlight.js/index.d.ts +++ b/types/highlight.js/index.d.ts @@ -1,10 +1,14 @@ // Type definitions for highlight.js v9.12 // Project: https://github.com/isagalaev/highlight.js -// Definitions by: Niklas Mollenhauer , Jeremy Hull +// Definitions by: Niklas Mollenhauer +// Jeremy Hull +// Josh Goldberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace hljs { + interface Node { } + export function highlight( name: string, value: string, diff --git a/types/highlight.js/tsconfig.json b/types/highlight.js/tsconfig.json index 5f5d2ae011..e3627e99ca 100644 --- a/types/highlight.js/tsconfig.json +++ b/types/highlight.js/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/html-webpack-plugin/html-webpack-plugin-tests.ts b/types/html-webpack-plugin/html-webpack-plugin-tests.ts index a84d19bea5..7a1e5f20bc 100644 --- a/types/html-webpack-plugin/html-webpack-plugin-tests.ts +++ b/types/html-webpack-plugin/html-webpack-plugin-tests.ts @@ -19,6 +19,9 @@ const optionsArray: HtmlWebpackPlugin.Options[] = [ { arbitrary: 'data', }, + { + chunksSortMode: 'manual', + } ]; const plugins: HtmlWebpackPlugin[] = optionsArray.map(options => new HtmlWebpackPlugin(options)); diff --git a/types/html-webpack-plugin/index.d.ts b/types/html-webpack-plugin/index.d.ts index b08a69faa5..dc23e020d7 100644 --- a/types/html-webpack-plugin/index.d.ts +++ b/types/html-webpack-plugin/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for html-webpack-plugin 2.28 +// Type definitions for html-webpack-plugin 2.30 // Project: https://github.com/ampedandwired/html-webpack-plugin -// Definitions by: Simon Hartcher , Benjamin Lim +// Definitions by: Simon Hartcher +// Benjamin Lim +// Tomek Łaziuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { Plugin } from 'webpack'; @@ -35,9 +37,9 @@ declare namespace HtmlWebpackPlugin { cache?: boolean; /** * Allows to control how chunks should be sorted before they are included to the html. - * Allowed values: `'none' | 'auto' | 'dependency' | {function}` - default: `'auto'` + * Allowed values: 'none' | 'auto' | 'dependency' |'manual' | {function} - default: 'auto' */ - chunksSortMode?: 'none' | 'auto' | 'dependency' | ChunkComparator; + chunksSortMode?: 'none' | 'auto' | 'dependency' | 'manual' | ChunkComparator; /** Allows you to add only some chunks (e.g. only the unit-test chunk) */ chunks?: string[]; /** Allows you to skip some chunks (e.g. don't add the unit-test chunk) */ diff --git a/types/http-aws-es/index.d.ts b/types/http-aws-es/index.d.ts index c14547a58f..91e12604f8 100644 --- a/types/http-aws-es/index.d.ts +++ b/types/http-aws-es/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/TheDeveloper/http-aws-es#readme // Definitions by: Marco Gonzalez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/http-proxy-agent/http-proxy-agent-tests.ts b/types/http-proxy-agent/http-proxy-agent-tests.ts new file mode 100644 index 0000000000..f730cd1bde --- /dev/null +++ b/types/http-proxy-agent/http-proxy-agent-tests.ts @@ -0,0 +1,12 @@ +import Agent = require('http-proxy-agent'); + +// $ExpectType HttpProxyAgent +new Agent('url'); +new Agent({}); +new Agent({ host: 'url' }); + +// $ExpectError +new Agent(); + +// $ExpectError +new Agent({ a: 1 }); diff --git a/types/http-proxy-agent/index.d.ts b/types/http-proxy-agent/index.d.ts new file mode 100644 index 0000000000..015508b5d1 --- /dev/null +++ b/types/http-proxy-agent/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for http-proxy-agent 2.0 +// Project: https://github.com/TooTallNate/node-http-proxy-agent +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Agent } from 'http'; +import { Url } from 'url'; + +declare class HttpProxyAgent extends Agent { + constructor(options: string | Url); +} + +export = HttpProxyAgent; diff --git a/types/http-proxy-agent/tsconfig.json b/types/http-proxy-agent/tsconfig.json new file mode 100644 index 0000000000..626d4eaa4c --- /dev/null +++ b/types/http-proxy-agent/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "http-proxy-agent-tests.ts" + ] +} diff --git a/types/http-proxy-agent/tslint.json b/types/http-proxy-agent/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/http-proxy-agent/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hystrixjs/hystrixjs-tests.ts b/types/hystrixjs/hystrixjs-tests.ts index 676015be06..7ed7819fb7 100644 --- a/types/hystrixjs/hystrixjs-tests.ts +++ b/types/hystrixjs/hystrixjs-tests.ts @@ -4,7 +4,7 @@ import q = require('q'); var commandFactory = hystrixjs.commandFactory; var command = commandFactory - .getOrCreate('testCommand', 'testGroup') + .getOrCreate('testCommand', 'testGroup') .circuitBreakerSleepWindowInMilliseconds(5000) .errorHandler((error) => { return false; diff --git a/types/hystrixjs/index.d.ts b/types/hystrixjs/index.d.ts index 865f2b3916..b49cd40ba4 100644 --- a/types/hystrixjs/index.d.ts +++ b/types/hystrixjs/index.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as Q from "q"; import * as RX from "rx"; export as namespace hystrixjs; @@ -23,7 +22,8 @@ export interface HystrixProperties { "hystrix.metrics.statistical.window.bucketsNumber"?: number, "hystrix.metrics.percentile.window.timeInMilliseconds"?: number, "hystrix.metrics.percentile.window.bucketsNumber"?: number, - "hystrix.request.volume.rejectionThreshold"?: number + "hystrix.request.volume.rejectionThreshold"?: number, + "hystrix.promise.implementation"?: PromiseConstructorLike, } export interface HystrixConfig { @@ -46,7 +46,39 @@ export interface HystrixConfig { } export interface Command { - execute(...args: any[]): Q.Promise; + execute(...args: any[]): PromiseLike +} + +export interface CommandA0 { + execute(): PromiseLike +} + +export interface CommandA1 { + execute(t: T): PromiseLike +} + +export interface CommandA2 { + execute(t: T, u: U): PromiseLike +} + +export interface CommandA3 { + execute(t: T, u: U, v: V): PromiseLike +} + +export interface CommandA4 { + execute(t: T, u: U, v: V, w: W): PromiseLike +} + +export interface CommandA5 { + execute(t: T, u: U, v: V, w: W, x: X): PromiseLike +} + +export interface CommandA6 { + execute(t: T, u: U, v: V, w: W, x: X, y: Y): PromiseLike +} + +export interface CommandA7 { + execute(t: T, u: U, v: V, w: W, x: X, y: Y, z: Z): PromiseLike } export interface CommandBuilder { @@ -62,14 +94,174 @@ export interface CommandBuilder { percentileWindowNumberOfBuckets(value: number): CommandBuilder; percentileWindowLength(value: number): CommandBuilder; circuitBreakerErrorThresholdPercentage(value: number): CommandBuilder; - run(value: (args: any) => Q.Promise): CommandBuilder; - fallbackTo(value: (...args: any[]) => Q.Promise): CommandBuilder; context(value: any): CommandBuilder; - build(): Command; + run(value: (...args: any[]) => PromiseLike): CommandBuilder; + fallbackTo(value: (error: Error, args ?: any[]) => PromiseLike): CommandBuilder; + build() : Command; +} + +export interface CommandBuilderA0 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA0; + errorHandler(value: (error: any) => boolean): CommandBuilderA0; + timeout(value: number): CommandBuilderA0; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA0; + requestVolumeRejectionThreshold(value: number): CommandBuilderA0; + circuitBreakerForceOpened(value: boolean): CommandBuilderA0; + circuitBreakerForceClosed(value: boolean): CommandBuilderA0; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA0; + statisticalWindowLength(value: number): CommandBuilderA0; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA0; + percentileWindowLength(value: number): CommandBuilderA0; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA0; + context(value: any): CommandBuilderA0; + run(value: () => PromiseLike): CommandBuilderA0; + fallbackTo(value: (error: Error) => PromiseLike): CommandBuilderA0; + build() : CommandA0; +} + +export interface CommandBuilderA1 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA1; + errorHandler(value: (error: any) => boolean): CommandBuilderA1; + timeout(value: number): CommandBuilderA1; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA1; + requestVolumeRejectionThreshold(value: number): CommandBuilderA1; + circuitBreakerForceOpened(value: boolean): CommandBuilderA1; + circuitBreakerForceClosed(value: boolean): CommandBuilderA1; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA1; + statisticalWindowLength(value: number): CommandBuilderA1; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA1; + percentileWindowLength(value: number): CommandBuilderA1; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA1; + context(value: any): CommandBuilderA1; + run(value: (t: T) => PromiseLike): CommandBuilderA1; + fallbackTo(value: (error: Error, args : [T]) => PromiseLike): CommandBuilderA1; + build(): CommandA1; +} + +export interface CommandBuilderA2 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA2; + errorHandler(value: (error: any) => boolean): CommandBuilderA2; + timeout(value: number): CommandBuilderA2; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA2; + requestVolumeRejectionThreshold(value: number): CommandBuilderA2; + circuitBreakerForceOpened(value: boolean): CommandBuilderA2; + circuitBreakerForceClosed(value: boolean): CommandBuilderA2; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA2; + statisticalWindowLength(value: number): CommandBuilderA2; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA2; + percentileWindowLength(value: number): CommandBuilderA2; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA2; + context(value: any): CommandBuilderA2; + run(value: (t: T, u: U) => PromiseLike): CommandBuilderA2; + fallbackTo(value: (error: Error, args: [T, U]) => PromiseLike): CommandBuilderA2; + build(): CommandA2; +} + +export interface CommandBuilderA3 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA3; + errorHandler(value: (error: any) => boolean): CommandBuilderA3; + timeout(value: number): CommandBuilderA3; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA3; + requestVolumeRejectionThreshold(value: number): CommandBuilderA3; + circuitBreakerForceOpened(value: boolean): CommandBuilderA3; + circuitBreakerForceClosed(value: boolean): CommandBuilderA3; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA3; + statisticalWindowLength(value: number): CommandBuilderA3; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA3; + percentileWindowLength(value: number): CommandBuilderA3; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA3; + context(value: any): CommandBuilderA3; + run(value: (t: T, u: U, v: V) => PromiseLike): CommandBuilderA3; + fallbackTo(value: (error: Error, args: [T, U, V]) => PromiseLike): CommandBuilderA3; + build(): CommandA3; +} + +export interface CommandBuilderA4 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA4; + errorHandler(value: (error: any) => boolean): CommandBuilderA4; + timeout(value: number): CommandBuilderA4; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA4; + requestVolumeRejectionThreshold(value: number): CommandBuilderA4; + circuitBreakerForceOpened(value: boolean): CommandBuilderA4; + circuitBreakerForceClosed(value: boolean): CommandBuilderA4; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA4; + statisticalWindowLength(value: number): CommandBuilderA4; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA4; + percentileWindowLength(value: number): CommandBuilderA4; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA4; + context(value: any): CommandBuilderA4; + run(value: (t: T, u: U, v: V, w: W) => PromiseLike): CommandBuilderA4; + fallbackTo(value: (error: Error, args: [T, U, V, W]) => PromiseLike): CommandBuilderA4; + build(): CommandA4; +} + +export interface CommandBuilderA5 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA5; + errorHandler(value: (error: any) => boolean): CommandBuilderA5; + timeout(value: number): CommandBuilderA5; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA5; + requestVolumeRejectionThreshold(value: number): CommandBuilderA5; + circuitBreakerForceOpened(value: boolean): CommandBuilderA5; + circuitBreakerForceClosed(value: boolean): CommandBuilderA5; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA5; + statisticalWindowLength(value: number): CommandBuilderA5; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA5; + percentileWindowLength(value: number): CommandBuilderA5; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA5; + context(value: any): CommandBuilderA5; + run(value: (t: T, u: U, v: V, w: W, x: X) => PromiseLike): CommandBuilderA5; + fallbackTo(value: (error: Error, args: [T, U, V, W, X]) => PromiseLike): CommandBuilderA5; + build(): CommandA5; +} + +export interface CommandBuilderA6 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA6; + errorHandler(value: (error: any) => boolean): CommandBuilderA6; + timeout(value: number): CommandBuilderA6; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA6; + requestVolumeRejectionThreshold(value: number): CommandBuilderA6; + circuitBreakerForceOpened(value: boolean): CommandBuilderA6; + circuitBreakerForceClosed(value: boolean): CommandBuilderA6; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA6; + statisticalWindowLength(value: number): CommandBuilderA6; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA6; + percentileWindowLength(value: number): CommandBuilderA6; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA6; + context(value: any): CommandBuilderA6; + run(value: (t: T, u: U, v: V, w: W, x: X, y: Y) => PromiseLike): CommandBuilderA6; + fallbackTo(value: (error: Error, args: [T, U, V, W, X, Y]) => PromiseLike): CommandBuilderA6; + build(): CommandA6; +} + +export interface CommandBuilderA7 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA7; + errorHandler(value: (error: any) => boolean): CommandBuilderA7; + timeout(value: number): CommandBuilderA7; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA7; + requestVolumeRejectionThreshold(value: number): CommandBuilderA7; + circuitBreakerForceOpened(value: boolean): CommandBuilderA7; + circuitBreakerForceClosed(value: boolean): CommandBuilderA7; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA7; + statisticalWindowLength(value: number): CommandBuilderA7; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA7; + percentileWindowLength(value: number): CommandBuilderA7; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA7; + context(value: any): CommandBuilderA7; + run(value: (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z) => PromiseLike): CommandBuilderA7; + fallbackTo(value: (error: Error, args: [T, U, V, W, X, Y, Z]) => PromiseLike): CommandBuilderA7; + build(): CommandA7; } export interface CommandFactory { getOrCreate(commandKey: string, commandGroup?: string): CommandBuilder; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA0; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA1; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA2; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA3; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA4; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA5; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA6; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA7; resetCache(): void; } @@ -141,4 +333,4 @@ export var commandFactory: CommandFactory; export var metricsFactory: MetricsFactory; export var circuitFactory: CircuitFactory; export var hystrixSSEStream: HystrixSSEStream; -export var hystrixConfig: HystrixConfig; \ No newline at end of file +export var hystrixConfig: HystrixConfig; diff --git a/types/hystrixjs/tsconfig.json b/types/hystrixjs/tsconfig.json index 0cf5de7b81..480476e8d1 100644 --- a/types/hystrixjs/tsconfig.json +++ b/types/hystrixjs/tsconfig.json @@ -13,11 +13,7 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, + "paths": {}, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true @@ -26,4 +22,4 @@ "index.d.ts", "hystrixjs-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/i18n-js/i18n-js-tests.ts b/types/i18n-js/i18n-js-tests.ts new file mode 100644 index 0000000000..4f19dc4c02 --- /dev/null +++ b/types/i18n-js/i18n-js-tests.ts @@ -0,0 +1,81 @@ +/** + * Test suite created by Yuya Tanaka + * Created by using code examples from https://github.com/fnando/i18n-js + */ + +import I18n = require("i18n-js"); + +I18n.defaultLocale = "pt-BR"; +I18n.locale = "pt-BR"; +I18n.currentLocale() === "pt-BR"; + +I18n.t("some.scoped.translation"); +I18n.t("some.scoped.translation", { locale: "fr" }); +I18n.t("hello", { name: "John Doe" }); +I18n.t("some.missing.scope", { defaultValue: "A default message" }); +I18n.t("noun", { defaultValue: "I'm a {{noun}}", noun: "Mac" }); +I18n.t("some.missing.scope", { defaults: [{ scope: "some.existing.scope" }] }); +I18n.t("some.missing.scope", { defaults: [{ message: "Some message" }] }); + +I18n.fallbacks = true; +I18n.locales.no = ["nb", "en"]; +I18n.locales.no = "nb"; +I18n.locales.no = locale => ["nb"]; + +I18n.missingBehaviour = "guess"; +I18n.missingTranslationPrefix = "EE: "; +I18n.missingTranslation = (scope, options) => "foobar"; +I18n.missingTranslation = (scope, options) => null; +I18n.missingTranslation = (scope, options) => undefined; + +I18n.t("inbox.counting", { count: 10 }); +I18n.pluralization["ru"] = count => { + const key = count % 10 === 1 && count % 100 !== 11 ? "one" + : [2, 3, 4].indexOf(count % 10) >= 0 && [12, 13, 14].indexOf(count % 100) < 0 ? "few" + : count % 10 === 0 || [5, 6, 7, 8, 9].indexOf(count % 10) >= 0 || [11, 12, 13, 14].indexOf(count % 100) >= 0 ? "many" + : "other"; + return [key]; +}; + +const options = { scope: "activerecord.attributes.user" }; +I18n.t("name", options); +I18n.t(["greetings", "hello"]); + +I18n.l("currency", 1990.99); +I18n.l("number", 1990.99); +I18n.l("percentage", 123.45); + +I18n.toNumber(1000); +I18n.toCurrency(1000); +I18n.toPercentage(100); + +I18n.toNumber(1000, { precision: 0 }); +I18n.toNumber(1000, { delimiter: ".", separator: "," }); +I18n.toNumber(1000, { delimiter: ".", precision: 0 }); + +I18n.toCurrency(1000, { precision: 0 }); + +I18n.toHumanSize(1234); + +I18n.l("date.formats.short", "2009-09-18"); +I18n.l("time.formats.short", "2009-09-18 23:12:43"); +I18n.l("time.formats.short", "2009-11-09T18:10:34"); +I18n.l("time.formats.short", "2009-11-09T18:10:34Z"); +I18n.l("date.formats.short", 1251862029000); +I18n.l("date.formats.short", "09/18/2009"); +I18n.l("date.formats.short", (new Date())); + +I18n.l("date.formats.ordinal_day", "2009-09-18", { day: "18th" }); + +I18n.strftime(new Date(), "%d/%m/%Y"); + +const point_in_number = 1000; +I18n.t("point", { count: point_in_number, formatted_number: I18n.toNumber(point_in_number) }); + +I18n.translations = {}; +I18n.translations["en"] = { + message: "Some special message for you" +}; +I18n.translations["pt-BR"] = { + message: "Uma mensagem especial para você" +}; diff --git a/types/i18n-js/index.d.ts b/types/i18n-js/index.d.ts new file mode 100644 index 0000000000..4800125087 --- /dev/null +++ b/types/i18n-js/index.d.ts @@ -0,0 +1,79 @@ +// Type definitions for i18n-js 3.0 +// Project: https://github.com/fnando/i18n-js +// Definitions by: Yuya Tanaka +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +// tslint:disable-next-line:export-just-namespace +export = I18n; +export as namespace I18n; + +declare namespace I18n { + type Scope = string | string[]; + + let defaultLocale: string; + let locale: string; + let defaultSeparator: string; + let placeholder: RegExp; + let fallbacks: boolean; + let missingBehaviour: "message" | "guess"; + let missingTranslationPrefix: string; + + // tslint:disable-next-line prefer-declare-function + let missingTranslation: (scope: string, options?: TranslateOptions) => string | null | undefined; + // tslint:disable-next-line prefer-declare-function + let missingPlaceholder: (placeholder: string, message: string, options?: InterpolateOptions) => string | null | undefined; + // tslint:disable-next-line prefer-declare-function + let nullPlaceholder: (placeholder: string, message: string, options?: InterpolateOptions) => string | null | undefined; + + let translations: { [locale: string]: object }; + let locales: { [key: string]: string | string[] | ((locale: string) => string | string[]) }; + let pluralization: { [locale: string]: (count: number) => string[] }; + + function reset(): void; + + function currentLocale(): string; + + interface InterpolateOptions { + [key: string]: any; // interpolation + } + + interface TranslateOptions extends InterpolateOptions { + scope?: Scope; + message?: string; + defaults?: Array<{ message: string } | { scope: Scope }>; + defaultValue?: string; + } + function translate(scope: Scope, options?: TranslateOptions): string; + function t(scope: Scope, options?: TranslateOptions): string; + + function localize(scope: "currency" | "number" | "percentage", value: number, options?: InterpolateOptions): string; + function localize(scope: Scope, value: string | number | Date, options?: InterpolateOptions): string; + function l(scope: "currency" | "number" | "percentage", value: number, options?: InterpolateOptions): string; + function l(scope: Scope, value: string | number | Date, options?: InterpolateOptions): string; + + interface ToNumberOptions { + precision?: number; + separator?: string; + delimiter?: string; + strip_insignificant_zeros?: boolean; + } + function toNumber(num: number, options?: ToNumberOptions): string; + + type ToPercentageOptions = ToNumberOptions; + function toPercentage(num: number, options?: ToPercentageOptions): string; + + interface ToCurrencyOptions extends ToNumberOptions { + format?: string; + unit?: string; + sign_first?: boolean; + } + function toCurrency(num: number, options?: ToCurrencyOptions): string; + + interface ToHumanSizeOptions extends ToNumberOptions { + format?: string; + } + function toHumanSize(num: number, options?: ToHumanSizeOptions): string; + + function strftime(date: Date, format: string): string; +} diff --git a/types/i18n-js/tsconfig.json b/types/i18n-js/tsconfig.json new file mode 100644 index 0000000000..4a9e4d110b --- /dev/null +++ b/types/i18n-js/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "i18n-js-tests.ts" + ] +} diff --git a/types/i18n-js/tslint.json b/types/i18n-js/tslint.json new file mode 100644 index 0000000000..299e93b32f --- /dev/null +++ b/types/i18n-js/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "indent": [true, "spaces", 4], + "quotemark": [true, "double", "avoid-escape"] + } +} diff --git a/types/iltorb/iltorb-tests.ts b/types/iltorb/iltorb-tests.ts new file mode 100644 index 0000000000..5c30fcd3b5 --- /dev/null +++ b/types/iltorb/iltorb-tests.ts @@ -0,0 +1,36 @@ +import { createReadStream, createWriteStream } from 'fs'; +import * as br from 'iltorb'; + +const opts: br.BrotliEncodeParams = { + disable_literal_context_modeling: false, + lgblock: 0, + lgwin: 22, + mode: 0, + quality: 11, + size_hint: 0 +}; + +const onCompress = (err1: Error | null | undefined, compressed: Buffer) => { + br.decompress(compressed, (err2: Error | null | undefined, decompressed: Buffer) => { + console.log(decompressed.toString()); + }); +}; + +br.compress(Buffer.from('foo', 'utf8'), onCompress); + +br.compress(Buffer.from('foo', 'utf8'), opts, onCompress); + +createReadStream(__filename) + .pipe(br.compressStream()) + .pipe(createWriteStream('foo.ts')); + +createReadStream(__dirname) + .pipe(br.compressStream(opts)) + .pipe(createWriteStream('bar.ts')); + +createReadStream('bar.ts') + .pipe(br.decompressStream()) + .pipe(createWriteStream('qux.ts')); + +br.decompressSync(br.compressSync(Buffer.from('foo', 'utf8'))); +br.decompressSync(br.compressSync(Buffer.from('foo', 'utf8'), opts)); diff --git a/types/iltorb/index.d.ts b/types/iltorb/index.d.ts new file mode 100644 index 0000000000..bd6cd88fb7 --- /dev/null +++ b/types/iltorb/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for iltorb 2.0 +// Project: https://github.com/MayhemYDG/iltorb +// Definitions by: Arturas Molcanovas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Transform } from 'stream'; + +export interface BrotliEncodeParams { + disable_literal_context_modeling?: boolean; + lgblock?: number; + lgwin?: number; + mode?: number; + quality?: number; + size_hint?: number; +} + +export type IltorbCallback = (err: Error | null | undefined, output: Buffer) => void; + +export function compress(buffer: Buffer, options: BrotliEncodeParams, callback: IltorbCallback): void; +export function compress(buffer: Buffer, callback: IltorbCallback): void; + +export function decompress(buffer: Buffer, callback: IltorbCallback): void; + +export function compressSync(buffer: Buffer, options?: BrotliEncodeParams): Buffer; +export function decompressSync(buffer: Buffer): Buffer; + +export function compressStream(options?: BrotliEncodeParams): Transform; +export function decompressStream(): Transform; diff --git a/types/iltorb/tsconfig.json b/types/iltorb/tsconfig.json new file mode 100644 index 0000000000..c12ff988ba --- /dev/null +++ b/types/iltorb/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "iltorb-tests.ts" + ] +} diff --git a/types/iltorb/tslint.json b/types/iltorb/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/iltorb/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/ioredis/index.d.ts b/types/ioredis/index.d.ts index 8353b4e563..ec1dbe3512 100644 --- a/types/ioredis/index.d.ts +++ b/types/ioredis/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for ioredis +// Type definitions for ioredis 3.2 // Project: https://github.com/luin/ioredis -// Definitions by: York Yao +// Definitions by: York Yao // Christopher Eck // Yoga Aliarham +// Ebrahim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* =================== USAGE =================== @@ -13,635 +14,738 @@ /// interface RedisStatic { - new (port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; - new (host?: string, options?: IORedis.RedisOptions): IORedis.Redis; - new (options: IORedis.RedisOptions): IORedis.Redis; - new (url: string): IORedis.Redis; + new(port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; + new(host?: string, options?: IORedis.RedisOptions): IORedis.Redis; + new(options?: IORedis.RedisOptions): IORedis.Redis; (port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; (host?: string, options?: IORedis.RedisOptions): IORedis.Redis; - (options: IORedis.RedisOptions): IORedis.Redis; - (url: string): IORedis.Redis; + (options?: IORedis.RedisOptions): IORedis.Redis; Cluster: IORedis.Cluster; + Command: IORedis.Command; } declare var IORedis: RedisStatic; export = IORedis; -declare module IORedis { - interface Commander { - new (): Commander; - getBuiltinCommands(): string[]; - createBuiltinCommand(commandName: string): {}; - defineCommand(name: string, definition: { - numberOfKeys?: number; - lua?: string; - }): any; - sendCommand(): void; +declare class Commander { + getBuiltinCommands(): string[]; + createBuiltinCommand(commandName: string): {}; + defineCommand(name: string, definition: { + numberOfKeys?: number; + lua?: string; + }): any; + sendCommand(): void; +} + +declare namespace IORedis { + interface Command { + setArgumentTransformer(name: string, fn: (args: any[]) => any[]): void; + setReplyTransformer(name: string, fn: (result: any) => any): void; } interface Redis extends NodeJS.EventEmitter, Commander { status: string; - connect(callback?: Function): Promise; + connect(callback?: () => void): Promise; disconnect(): void; duplicate(): Redis; - monitor(calback: (error: Error, monitor: NodeJS.EventEmitter) => void): Promise; send_command(command: string, ...args: any[]): any; - auth(password: string, callback?: ResCallbackT): any; - ping(callback?: ResCallbackT): any; - append(key: string, value: string, callback?: ResCallbackT): any; - bitcount(key: string, callback?: ResCallbackT): any; - bitcount(key: string, start: number, end: number, callback?: ResCallbackT): any; - set(key: string, value: string, callback?: ResCallbackT): any; - get(key: string, callback?: ResCallbackT): any; - exists(key: string, value: string, callback?: ResCallbackT): any; - publish(channel: string, value: any): any; - subscribe(channel: string): any; - get(args: any[], callback?: ResCallbackT): any; - get(...args: any[]): any; - getBuffer(key: string, callback?: ResCallbackT): any; - set(args: any[], callback?: ResCallbackT): any; - set(...args: any[]): any; - setnx(args: any[], callback?: ResCallbackT): any; - setnx(...args: any[]): any; - setex(args: any[], callback?: ResCallbackT): any; - setex(...args: any[]): any; - psetex(args: any[], callback?: ResCallbackT): any; - psetex(...args: any[]): any; - append(args: any[], callback?: ResCallbackT): any; - append(...args: any[]): any; - strlen(args: any[], callback?: ResCallbackT): any; - strlen(...args: any[]): any; - del(args: any[], callback?: ResCallbackT): any; - del(...args: any[]): any; - exists(args: any[], callback?: ResCallbackT): any; - exists(...args: any[]): any; - setbit(args: any[], callback?: ResCallbackT): any; - setbit(...args: any[]): any; - getbit(args: any[], callback?: ResCallbackT): any; - getbit(...args: any[]): any; - setrange(args: any[], callback?: ResCallbackT): any; - setrange(...args: any[]): any; - getrange(args: any[], callback?: ResCallbackT): any; - getrange(...args: any[]): any; - substr(args: any[], callback?: ResCallbackT): any; - substr(...args: any[]): any; - incr(args: any[], callback?: ResCallbackT): any; - incr(...args: any[]): any; - decr(args: any[], callback?: ResCallbackT): any; - decr(...args: any[]): any; - mget(args: any[], callback?: ResCallbackT): any; - mget(...args: any[]): any; - rpush(...args: any[]): any; - lpush(args: any[], callback?: ResCallbackT): any; - lpush(...args: any[]): any; - rpushx(args: any[], callback?: ResCallbackT): any; - rpushx(...args: any[]): any; - lpushx(args: any[], callback?: ResCallbackT): any; - lpushx(...args: any[]): any; - linsert(args: any[], callback?: ResCallbackT): any; - linsert(...args: any[]): any; - rpop(args: any[], callback?: ResCallbackT): any; - rpop(...args: any[]): any; - lpop(args: any[], callback?: ResCallbackT): any; - lpop(...args: any[]): any; - brpop(args: any[], callback?: ResCallbackT): any; - brpop(...args: any[]): any; - brpoplpush(args: any[], callback?: ResCallbackT): any; - brpoplpush(...args: any[]): any; - blpop(args: any[], callback?: ResCallbackT): any; - blpop(...args: any[]): any; - llen(args: any[], callback?: ResCallbackT): any; - llen(...args: any[]): any; - lindex(args: any[], callback?: ResCallbackT): any; - lindex(...args: any[]): any; - lset(args: any[], callback?: ResCallbackT): any; - lset(...args: any[]): any; - lrange(args: any[], callback?: ResCallbackT): any; - lrange(...args: any[]): any; - ltrim(args: any[], callback?: ResCallbackT): any; - ltrim(...args: any[]): any; - lrem(args: any[], callback?: ResCallbackT): any; - lrem(...args: any[]): any; - rpoplpush(args: any[], callback?: ResCallbackT): any; - rpoplpush(...args: any[]): any; - sadd(args: any[], callback?: ResCallbackT): any; - sadd(...args: any[]): any; - srem(args: any[], callback?: ResCallbackT): any; - srem(...args: any[]): any; - smove(args: any[], callback?: ResCallbackT): any; - smove(...args: any[]): any; - sismember(args: any[], callback?: ResCallbackT): any; - sismember(...args: any[]): any; - scard(args: any[], callback?: ResCallbackT): any; - scard(...args: any[]): any; - spop(args: any[], callback?: ResCallbackT): any; - spop(...args: any[]): any; - srandmember(args: any[], callback?: ResCallbackT): any; - srandmember(...args: any[]): any; - sinter(args: any[], callback?: ResCallbackT): any; - sinter(...args: any[]): any; - sinterstore(args: any[], callback?: ResCallbackT): any; - sinterstore(...args: any[]): any; - sunion(args: any[], callback?: ResCallbackT): any; - sunion(...args: any[]): any; - sunionstore(args: any[], callback?: ResCallbackT): any; - sunionstore(...args: any[]): any; - sdiff(args: any[], callback?: ResCallbackT): any; - sdiff(...args: any[]): any; - sdiffstore(args: any[], callback?: ResCallbackT): any; - sdiffstore(...args: any[]): any; - smembers(args: any[], callback?: ResCallbackT): any; - smembers(...args: any[]): any; - zadd(args: any[], callback?: ResCallbackT): any; - zadd(...args: any[]): any; - zincrby(args: any[], callback?: ResCallbackT): any; - zincrby(...args: any[]): any; - zrem(args: any[], callback?: ResCallbackT): any; - zrem(...args: any[]): any; - zremrangebyscore(args: any[], callback?: ResCallbackT): any; - zremrangebyscore(...args: any[]): any; - zremrangebyrank(args: any[], callback?: ResCallbackT): any; - zremrangebyrank(...args: any[]): any; - zunionstore(args: any[], callback?: ResCallbackT): any; - zunionstore(...args: any[]): any; - zinterstore(args: any[], callback?: ResCallbackT): any; - zinterstore(...args: any[]): any; - zrange(args: any[], callback?: ResCallbackT): any; - zrange(...args: any[]): any; - zrangebyscore(args: any[], callback?: ResCallbackT): any; - zrangebyscore(...args: any[]): any; - zrevrangebyscore(args: any[], callback?: ResCallbackT): any; - zrevrangebyscore(...args: any[]): any; - zcount(args: any[], callback?: ResCallbackT): any; - zcount(...args: any[]): any; - zrevrange(args: any[], callback?: ResCallbackT): any; - zrevrange(...args: any[]): any; - zcard(args: any[], callback?: ResCallbackT): any; - zcard(...args: any[]): any; - zscore(args: any[], callback?: ResCallbackT): any; - zscore(...args: any[]): any; - zrank(args: any[], callback?: ResCallbackT): any; - zrank(...args: any[]): any; - zrevrank(args: any[], callback?: ResCallbackT): any; - zrevrank(...args: any[]): any; - hset(args: any[], callback?: ResCallbackT): any; - hset(...args: any[]): any; - hsetnx(args: any[], callback?: ResCallbackT): any; - hsetnx(...args: any[]): any; - hget(args: any[], callback?: ResCallbackT): any; - hget(...args: any[]): any; - hmset(args: any[], callback?: ResCallbackT): any; - hmset(key: string, hash: any, callback?: ResCallbackT): any; - hmset(...args: any[]): any; - hmget(args: any[], callback?: ResCallbackT): any; - hmget(...args: any[]): any; - hincrby(args: any[], callback?: ResCallbackT): any; - hincrby(...args: any[]): any; - hincrbyfloat(args: any[], callback?: ResCallbackT): any; - hincrbyfloat(...args: any[]): any; - hdel(args: any[], callback?: ResCallbackT): any; - hdel(...args: any[]): any; - hlen(args: any[], callback?: ResCallbackT): any; - hlen(...args: any[]): any; - hkeys(args: any[], callback?: ResCallbackT): any; - hkeys(...args: any[]): any; - hvals(args: any[], callback?: ResCallbackT): any; - hvals(...args: any[]): any; - hgetall(args: any[], callback?: ResCallbackT): any; - hgetall(...args: any[]): any; - hgetall(key: string, callback?: ResCallbackT): any; - hexists(args: any[], callback?: ResCallbackT): any; - hexists(...args: any[]): any; - incrby(args: any[], callback?: ResCallbackT): any; - incrby(...args: any[]): any; - incrbyfloat(args: any[], callback?: ResCallbackT): any; - incrbyfloat(...args: any[]): any; - decrby(args: any[], callback?: ResCallbackT): any; - decrby(...args: any[]): any; - getset(args: any[], callback?: ResCallbackT): any; - getset(...args: any[]): any; - mset(args: any[], callback?: ResCallbackT): any; - mset(...args: any[]): any; - msetnx(args: any[], callback?: ResCallbackT): any; - msetnx(...args: any[]): any; - randomkey(args: any[], callback?: ResCallbackT): any; - randomkey(...args: any[]): any; - select(args: any[], callback?: ResCallbackT): void; - select(...args: any[]): void; - move(args: any[], callback?: ResCallbackT): any; - move(...args: any[]): any; - rename(args: any[], callback?: ResCallbackT): any; - rename(...args: any[]): any; - renamenx(args: any[], callback?: ResCallbackT): any; - renamenx(...args: any[]): any; - expire(args: any[], callback?: ResCallbackT): any; - expire(...args: any[]): any; - pexpire(args: any[], callback?: ResCallbackT): any; - pexpire(...args: any[]): any; - expireat(args: any[], callback?: ResCallbackT): any; - expireat(...args: any[]): any; - pexpireat(args: any[], callback?: ResCallbackT): any; - pexpireat(...args: any[]): any; - keys(args: any[], callback?: ResCallbackT): any; - keys(...args: any[]): any; - dbsize(args: any[], callback?: ResCallbackT): any; - dbsize(...args: any[]): any; - auth(args: any[], callback?: ResCallbackT): void; - auth(...args: any[]): void; - ping(args: any[], callback?: ResCallbackT): any; - ping(...args: any[]): any; - echo(args: any[], callback?: ResCallbackT): any; - echo(...args: any[]): any; - save(args: any[], callback?: ResCallbackT): any; - save(...args: any[]): any; - bgsave(args: any[], callback?: ResCallbackT): any; - bgsave(...args: any[]): any; - bgrewriteaof(args: any[], callback?: ResCallbackT): any; - bgrewriteaof(...args: any[]): any; - shutdown(args: any[], callback?: ResCallbackT): any; - shutdown(...args: any[]): any; - lastsave(args: any[], callback?: ResCallbackT): any; - lastsave(...args: any[]): any; - type(args: any[], callback?: ResCallbackT): any; - type(...args: any[]): any; - multi(args: any[], callback?: ResCallbackT): Pipeline; - multi(...args: any[]): Pipeline; - exec(args: any[], callback?: ResCallbackT): any; - exec(...args: any[]): any; - discard(args: any[], callback?: ResCallbackT): any; - discard(...args: any[]): any; - sync(args: any[], callback?: ResCallbackT): any; - sync(...args: any[]): any; - flushdb(args: any[], callback?: ResCallbackT): any; - flushdb(...args: any[]): any; - flushall(args: any[], callback?: ResCallbackT): any; - flushall(...args: any[]): any; - sort(args: any[], callback?: ResCallbackT): any; - sort(...args: any[]): any; - info(args: any[], callback?: ResCallbackT): any; - info(...args: any[]): any; - time(args: any[], callback?: ResCallbackT): any; - time(...args: any[]): any; - monitor(args: any[], callback?: ResCallbackT): any; - monitor(...args: any[]): any; - ttl(args: any[], callback?: ResCallbackT): any; - ttl(...args: any[]): any; - persist(args: any[], callback?: ResCallbackT): any; - persist(...args: any[]): any; - slaveof(args: any[], callback?: ResCallbackT): any; - slaveof(...args: any[]): any; - debug(args: any[], callback?: ResCallbackT): any; + + bitcount(key: string, callback: (err: Error, res: number) => void): void; + bitcount(key: string, start: number, end: number, callback: (err: Error, res: number) => void): void; + bitcount(key: string): Promise; + bitcount(key: string, start: number, end: number): Promise; + + get(key: string, callback: (err: Error, res: string) => void): void; + get(key: string): Promise; + getBuffer(key: string, callback: (err: Error, res: Buffer) => void): void; + getBuffer(key: string): Promise; + + set(key: string, value: any, ...args: any[]): any; + + setnx(key: string, value: any, callback: (err: Error, res: any) => void): void; + setnx(key: string, value: any): Promise; + + setex(key: string, seconds: number, value: any, callback: (err: Error, res: any) => void): void; + setex(key: string, seconds: number, value: any): Promise; + + psetex(key: string, milliseconds: number, value: any, callback: (err: Error, res: any) => void): void; + psetex(key: string, milliseconds: number, value: any): Promise; + + append(key: string, value: any, callback: (err: Error, res: number) => void): void; + append(key: string, value: any): Promise; + + strlen(key: string, callback: (err: Error, res: number) => void): void; + strlen(key: string): Promise; + + del(key: string, ...keys: string[]): any; + + exists(key: string, ...keys: string[]): any; + + setbit(key: string, offset: number, value: any, callback: (err: Error, res: number) => void): void; + setbit(key: string, offset: number, value: any): Promise; + + getbit(key: string, offset: number, callback: (err: Error, res: number) => void): void; + getbit(key: string, offset: number): Promise; + + setrange(key: string, offset: number, value: any, callback: (err: Error, res: number) => void): void; + setrange(key: string, offset: number, value: any): Promise; + + getrange(key: string, start: number, end: number, callback: (err: Error, res: string) => void): void; + getrange(key: string, start: number, end: number): Promise; + + substr(key: string, start: number, end: number, callback: (err: Error, res: string) => void): void; + substr(key: string, start: number, end: number): Promise; + + incr(key: string, callback: (err: Error, res: number) => void): void; + incr(key: string): Promise; + + decr(key: string, callback: (err: Error, res: number) => void): void; + decr(key: string): Promise; + + mget(key: string, ...keys: string[]): any; + + rpush(key: string, value: any, ...values: string[]): any; + + lpush(key: string, value: any, ...values: string[]): any; + + rpushx(key: string, value: any, callback: (err: Error, res: number) => void): void; + rpushx(key: string, value: any): Promise; + + lpushx(key: string, value: any, callback: (err: Error, res: number) => void): void; + lpushx(key: string, value: any): Promise; + + linsert(key: string, direction: "BEFORE" | "AFTER", pivot: string, value: any, callback: (err: Error, res: number) => void): void; + linsert(key: string, direction: "BEFORE" | "AFTER", pivot: string, value: any): Promise; + + rpop(key: string, callback: (err: Error, res: string) => void): void; + rpop(key: string): Promise; + + lpop(key: string, callback: (err: Error, res: string) => void): void; + lpop(key: string): Promise; + + brpop(key: string, ...keys: string[]): any; + + blpop(key: string, ...keys: string[]): any; + + brpoplpush(source: string, destination: string, timeout: number, callback: (err: Error, res: any) => void): void; + brpoplpush(source: string, destination: string, timeout: number): Promise; + + llen(key: string, callback: (err: Error, res: number) => void): void; + llen(key: string): Promise; + + lindex(key: string, index: number, callback: (err: Error, res: string) => void): void; + lindex(key: string, index: number): Promise; + + lset(key: string, index: number, value: any, callback: (err: Error, res: any) => void): void; + lset(key: string, index: number, value: any): Promise; + + lrange(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + lrange(key: string, start: number, stop: number): Promise; + + ltrim(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + ltrim(key: string, start: number, stop: number): Promise; + + lrem(key: string, count: number, value: any, callback: (err: Error, res: number) => void): void; + lrem(key: string, count: number, value: any): Promise; + + rpoplpush(source: string, destination: string, callback: (err: Error, res: string) => void): void; + rpoplpush(source: string, destination: string): Promise; + + sadd(key: string, ...members: any[]): any; + + srem(key: string, ...members: any[]): any; + + smove(source: string, destination: string, member: string, callback: (err: Error, res: string) => void): void; + smove(source: string, destination: string, member: string): Promise; + + sismember(key: string, member: string, callback: (err: Error, res: 1 | 0) => void): void; + sismember(key: string, member: string): Promise<1 | 0>; + + scard(key: string, callback: (err: Error, res: number) => void): void; + scard(key: string): Promise; + + spop(key: string, callback: (err: Error, res: any) => void): void; + spop(key: string, count: number, callback: (err: Error, res: any) => void): void; + spop(key: string, count?: number): Promise; + + srandmember(key: string, callback: (err: Error, res: any) => void): void; + srandmember(key: string, count: number, callback: (err: Error, res: any) => void): void; + srandmember(key: string, count?: number): Promise; + + sinter(key: string, ...keys: string[]): any; + + sinterstore(destination: string, key: string, ...keys: string[]): any; + + sunion(key: string, ...keys: string[]): any; + + sunionstore(destination: string, key: string, ...keys: string[]): any; + + sdiff(key: string, ...keys: string[]): any; + + sdiffstore(destination: string, key: string, ...keys: string[]): any; + + smembers(key: string, callback: (err: Error, res: any) => void): void; + smembers(key: string): Promise; + + zadd(key: string, ...args: string[]): any; + + zincrby(key: string, increment: number, member: string, callback: (err: Error, res: any) => void): void; + zincrby(key: string, increment: number, member: string): Promise; + + zrem(key: string, member: string, ...members: any[]): any; + + zremrangebyscore(key: string, min: number, max: number, callback: (err: Error, res: any) => void): void; + zremrangebyscore(key: string, min: number, max: number): Promise; + + zremrangebyrank(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + zremrangebyrank(key: string, start: number, stop: number): Promise; + + zunionstore(destination: string, numkeys: number, key: string, ...args: string[]): any; + + zinterstore(destination: string, numkeys: number, key: string, ...args: string[]): any; + + zrange(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + zrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback: (err: Error, res: any) => void): void; + zrange(key: string, start: number, stop: number, withScores?: "WITHSCORES"): Promise; + + zrevrange(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + zrevrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback: (err: Error, res: any) => void): void; + zrevrange(key: string, start: number, stop: number, withScores?: "WITHSCORES"): Promise; + + zrangebyscore(key: string, min: number, max: number, ...args: string[]): any; + + zrevrangebyscore(key: string, max: number, min: number, ...args: string[]): any; + + zcount(key: string, min: number, max: number, callback: (err: Error, res: number) => void): void; + zcount(key: string, min: number, max: number): Promise; + + zcard(key: string, callback: (err: Error, res: number) => void): void; + zcard(key: string): Promise; + + zscore(key: string, member: string, callback: (err: Error, res: number) => void): void; + zscore(key: string, member: string): Promise; + + zrank(key: string, member: string, callback: (err: Error, res: number) => void): void; + zrank(key: string, member: string): Promise; + + zrevrank(key: string, member: string, callback: (err: Error, res: number) => void): void; + zrevrank(key: string, member: string): Promise; + + hset(key: string, field: string, value: any, callback: (err: Error, res: 0 | 1) => void): void; + hset(key: string, field: string, value: any): Promise<0 | 1>; + + hsetnx(key: string, field: string, value: any, callback: (err: Error, res: 0 | 1) => void): void; + hsetnx(key: string, field: string, value: any): Promise<0 | 1>; + + hget(key: string, field: string, callback: (err: Error, res: string) => void): void; + hget(key: string, field: string): Promise; + + hmset(key: string, field: string, value: any, ...args: string[]): any; + + hmget(key: string, field: string, ...fields: string[]): any; + + hincrby(key: string, field: string, increment: number, callback: (err: Error, res: number) => void): void; + hincrby(key: string, field: string, increment: number): Promise; + + hincrbyfloat(key: string, field: string, increment: number, callback: (err: Error, res: number) => void): void; + hincrbyfloat(key: string, field: string, increment: number): Promise; + + hdel(key: string, field: string, ...fields: string[]): any; + + hlen(key: string, callback: (err: Error, res: number) => void): void; + hlen(key: string): Promise; + + hkeys(key: string, callback: (err: Error, res: any) => void): void; + hkeys(key: string): Promise; + + hvals(key: string, callback: (err: Error, res: any) => void): void; + hvals(key: string): Promise; + + hgetall(key: string, callback: (err: Error, res: any) => void): void; + hgetall(key: string): Promise; + + hexists(key: string, field: string, callback: (err: Error, res: 0 | 1) => void): void; + hexists(key: string, field: string): Promise<0 | 1>; + + incrby(key: string, increment: number, callback: (err: Error, res: number) => void): void; + incrby(key: string, increment: number): Promise; + + incrbyfloat(key: string, increment: number, callback: (err: Error, res: number) => void): void; + incrbyfloat(key: string, increment: number): Promise; + + decrby(key: string, decrement: number, callback: (err: Error, res: number) => void): void; + decrby(key: string, decrement: number): Promise; + + getset(key: string, value: any, callback: (err: Error, res: string) => void): void; + getset(key: string, value: any): Promise; + + mset(key: string, value: any, ...args: string[]): any; + + msetnx(key: string, value: any, ...args: string[]): any; + + randomkey(callback: (err: Error, res: string) => void): void; + randomkey(): Promise; + + select(index: number, callback: (err: Error, res: string) => void): void; + select(index: number): Promise; + + move(key: string, db: string, callback: (err: Error, res: 0 | 1) => void): void; + move(key: string, db: string): Promise<0 | 1>; + + rename(key: string, newkey: string, callback: (err: Error, res: string) => void): void; + rename(key: string, newkey: string): Promise; + + renamenx(key: string, newkey: string, callback: (err: Error, res: 0 | 1) => void): void; + renamenx(key: string, newkey: string): Promise<0 | 1>; + + expire(key: string, seconds: number, callback: (err: Error, res: 0 | 1) => void): void; + expire(key: string, seconds: number): Promise<0 | 1>; + + pexpire(key: string, milliseconds: number, callback: (err: Error, res: 0 | 1) => void): void; + pexpire(key: string, milliseconds: number): Promise<0 | 1>; + + expireat(key: string, timestamp: number, callback: (err: Error, res: 0 | 1) => void): void; + expireat(key: string, timestamp: number): Promise<0 | 1>; + + pexpireat(key: string, millisecondsTimestamp: number, callback: (err: Error, res: 0 | 1) => void): void; + pexpireat(key: string, millisecondsTimestamp: number): Promise<0 | 1>; + + keys(pattern: string, callback: (err: Error, res: string[]) => void): void; + keys(pattern: string): Promise; + + dbsize(callback: (err: Error, res: number) => void): void; + dbsize(): Promise; + + auth(password: string, callback: (err: Error, res: string) => void): void; + auth(password: string): Promise; + + ping(callback: (err: Error, res: string) => void): void; + ping(message: string, callback: (err: Error, res: string) => void): void; + ping(message?: string): Promise; + + echo(message: string, callback: (err: Error, res: string) => void): void; + echo(message: string): Promise; + + save(callback: (err: Error, res: string) => void): void; + save(): Promise; + + bgsave(callback: (err: Error, res: string) => void): void; + bgsave(): Promise; + + bgrewriteaof(callback: (err: Error, res: string) => void): void; + bgrewriteaof(): Promise; + + shutdown(save: "SAVE" | "NOSAVE", callback: (err: Error, res: any) => void): void; + shutdown(save: "SAVE" | "NOSAVE"): Promise; + + lastsave(callback: (err: Error, res: number) => void): void; + lastsave(): Promise; + + type(key: string, callback: (err: Error, res: string) => void): void; + type(key: string): Promise; + + multi(commands?: string[][], options?: MultiOptions): Pipeline; + multi(options: { pipeline: false }): Promise; + + exec(callback: (err: Error, res: any) => void): void; + exec(): Promise; + + discard(callback: (err: Error, res: any) => void): void; + discard(): Promise; + + sync(callback: (err: Error, res: any) => void): void; + sync(): Promise; + + flushdb(callback: (err: Error, res: string) => void): void; + flushdb(): Promise; + + flushall(callback: (err: Error, res: string) => void): void; + flushall(): Promise; + + sort(key: string, ...args: string[]): any; + + info(callback: (err: Error, res: any) => void): void; + info(section: string, callback: (err: Error, res: any) => void): void; + info(section?: string): Promise; + + time(callback: (err: Error, res: any) => void): void; + time(): Promise; + + monitor(callback: (err: Error, res: NodeJS.EventEmitter) => void): void; + monitor(): Promise; + + ttl(key: string, callback: (err: Error, res: number) => void): void; + ttl(key: string): Promise; + + persist(key: string, callback: (err: Error, res: 0 | 1) => void): void; + persist(key: string): Promise<0 | 1>; + + slaveof(host: string, port: number, callback: (err: Error, res: string) => void): void; + slaveof(host: string, port: number): Promise; + debug(...args: any[]): any; - config(args: any[], callback?: ResCallbackT): any; + config(...args: any[]): any; - subscribe(args: any[], callback?: ResCallbackT): any; - subscribe(...args: any[]): any; - unsubscribe(args: any[], callback?: ResCallbackT): any; - unsubscribe(...args: any[]): any; - psubscribe(args: any[], callback?: ResCallbackT): any; - psubscribe(...args: any[]): any; - punsubscribe(args: any[], callback?: ResCallbackT): any; - punsubscribe(...args: any[]): any; - publish(args: any[], callback?: ResCallbackT): any; - publish(...args: any[]): any; - watch(args: any[], callback?: ResCallbackT): any; - watch(...args: any[]): any; - unwatch(args: any[], callback?: ResCallbackT): any; - unwatch(...args: any[]): any; - cluster(args: any[], callback?: ResCallbackT): any; + + subscribe(channel: string, ...channels: any[]): any; + + unsubscribe(...channels: string[]): any; + + psubscribe(pattern: string, ...patterns: string[]): any; + + punsubscribe(...patterns: string[]): any; + + publish(channel: string, message: string, callback: (err: Error, res: number) => void): void; + publish(channel: string, message: string): Promise; + + watch(key: string, ...keys: string[]): any; + + unwatch(callback: (err: Error, res: string) => void): void; + unwatch(): Promise; + cluster(...args: any[]): any; - restore(args: any[], callback?: ResCallbackT): any; + restore(...args: any[]): any; - migrate(args: any[], callback?: ResCallbackT): any; + migrate(...args: any[]): any; - dump(args: any[], callback?: ResCallbackT): any; - dump(...args: any[]): any; - object(args: any[], callback?: ResCallbackT): any; - object(...args: any[]): any; - client(args: any[], callback?: ResCallbackT): any; + + dump(key: string, callback: (err: Error, res: string) => void): void; + dump(key: string): Promise; + + object(subcommand: string, ...args: any[]): any; + client(...args: any[]): any; - eval(args: any[], callback?: ResCallbackT): any; + eval(...args: any[]): any; - evalsha(args: any[], callback?: ResCallbackT): any; + evalsha(...args: any[]): any; - script(args: any[], callback?: ResCallbackT): any; - script(key: string, callback?: ResCallbackT): any; + script(...args: any[]): any; - quit(args: any[], callback?: ResCallbackT): any; - quit(...args: any[]): any; - scan(args: any[], callback?: ResCallbackT): any; - scan(...args: any[]): any; - hscan(args: any[], callback?: ResCallbackT): any; - hscan(...args: any[]): any; - zscan(args: any[], callback?: ResCallbackT): any; - zscan(...args: any[]): any; - pfmerge(args: any[], callback?: ResCallbackT): any; - pfmerge(...args: any[]): any; - pfadd(args: any[], callback?: ResCallbackT): any; - pfadd(...args: any[]): any; - pfcount(args: any[], callback?: ResCallbackT): any; - pfcount(...args: any[]): any; - pipeline(): Pipeline; - pipeline(commands: string[][]): Pipeline; + quit(callback: (err: Error, res: string) => void): void; + quit(): Promise; - scanStream(options?: IORedis.ScanStreamOption): NodeJS.EventEmitter; - hscanStream(key: string, options?: IORedis.ScanStreamOption): NodeJS.EventEmitter; - zscanStream(key: string, options?: IORedis.ScanStreamOption): NodeJS.EventEmitter; + scan(cursor: number, ...args: any[]): any; + + hscan(key: string, cursor: number, ...args: any[]): any; + + zscan(key: string, cursor: number, ...args: any[]): any; + + pfmerge(destkey: string, sourcekey: string, ...sourcekeys: string[]): any; + + pfadd(key: string, element: string, ...elements: string[]): any; + + pfcount(key: string, ...keys: string[]): any; + + pipeline(commands?: string[][]): Pipeline; + + scanStream(options?: ScanStreamOption): NodeJS.EventEmitter; + hscanStream(key: string, options?: ScanStreamOption): NodeJS.EventEmitter; + zscanStream(key: string, options?: ScanStreamOption): NodeJS.EventEmitter; } interface Pipeline { - exec(callback?: ResCallbackT): any; + bitcount(key: string, callback?: (err: Error, res: number) => void): Pipeline; + bitcount(key: string, start: number, end: number, callback?: (err: Error, res: number) => void): Pipeline; + + get(key: string, callback?: (err: Error, res: string) => void): Pipeline; + getBuffer(key: string, callback?: (err: Error, res: Buffer) => void): Pipeline; + + set(key: string, value: any, ...args: any[]): Pipeline; + + setnx(key: string, value: any, callback?: (err: Error, res: any) => void): Pipeline; + + setex(key: string, seconds: number, value: any, callback?: (err: Error, res: any) => void): Pipeline; + + psetex(key: string, milliseconds: number, value: any, callback?: (err: Error, res: any) => void): Pipeline; + + append(key: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + strlen(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + del(key: string, ...keys: string[]): Pipeline; + + exists(key: string, ...keys: string[]): Pipeline; + + setbit(key: string, offset: number, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + getbit(key: string, offset: number, callback?: (err: Error, res: number) => void): Pipeline; + + setrange(key: string, offset: number, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + getrange(key: string, start: number, end: number, callback?: (err: Error, res: string) => void): Pipeline; + + substr(key: string, start: number, end: number, callback?: (err: Error, res: string) => void): Pipeline; + + incr(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + decr(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + mget(key: string, ...keys: string[]): Pipeline; + + rpush(key: string, value: any, ...values: string[]): Pipeline; + + lpush(key: string, value: any, ...values: string[]): Pipeline; + + rpushx(key: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + lpushx(key: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + linsert(key: string, direction: "BEFORE" | "AFTER", pivot: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + rpop(key: string, callback?: (err: Error, res: string) => void): Pipeline; + + lpop(key: string, callback?: (err: Error, res: string) => void): Pipeline; + + brpop(key: string, ...keys: string[]): Pipeline; + + blpop(key: string, ...keys: string[]): Pipeline; + + brpoplpush(source: string, destination: string, timeout: number, callback?: (err: Error, res: any) => void): Pipeline; + + llen(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + lindex(key: string, index: number, callback?: (err: Error, res: string) => void): Pipeline; + + lset(key: string, index: number, value: any, callback?: (err: Error, res: any) => void): Pipeline; + + lrange(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + + ltrim(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + + lrem(key: string, count: number, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + rpoplpush(source: string, destination: string, callback?: (err: Error, res: string) => void): Pipeline; + + sadd(key: string, ...members: any[]): Pipeline; + + srem(key: string, ...members: any[]): Pipeline; + + smove(source: string, destination: string, member: string, callback?: (err: Error, res: string) => void): Pipeline; + + sismember(key: string, member: string, callback?: (err: Error, res: 1 | 0) => void): Pipeline; + + scard(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + spop(key: string, callback?: (err: Error, res: any) => void): Pipeline; + spop(key: string, count: number, callback?: (err: Error, res: any) => void): Pipeline; + + srandmember(key: string, callback?: (err: Error, res: any) => void): Pipeline; + srandmember(key: string, count: number, callback?: (err: Error, res: any) => void): Pipeline; + + sinter(key: string, ...keys: string[]): Pipeline; + + sinterstore(destination: string, key: string, ...keys: string[]): Pipeline; + + sunion(key: string, ...keys: string[]): Pipeline; + + sunionstore(destination: string, key: string, ...keys: string[]): Pipeline; + + sdiff(key: string, ...keys: string[]): Pipeline; + + sdiffstore(destination: string, key: string, ...keys: string[]): Pipeline; + + smembers(key: string, callback?: (err: Error, res: any) => void): Pipeline; + + zadd(key: string, ...args: string[]): Pipeline; + + zincrby(key: string, increment: number, member: string, callback?: (err: Error, res: any) => void): Pipeline; + + zrem(key: string, member: string, ...members: any[]): Pipeline; + + zremrangebyscore(key: string, min: number, max: number, callback?: (err: Error, res: any) => void): Pipeline; + + zremrangebyrank(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + + zunionstore(destination: string, numkeys: number, key: string, ...args: string[]): Pipeline; + + zinterstore(destination: string, numkeys: number, key: string, ...args: string[]): Pipeline; + + zrange(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + zrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback?: (err: Error, res: any) => void): Pipeline; + + zrevrange(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + zrevrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback?: (err: Error, res: any) => void): Pipeline; + + zrangebyscore(key: string, min: number, max: number, ...args: string[]): Pipeline; + + zrevrangebyscore(key: string, max: number, min: number, ...args: string[]): Pipeline; + + zcount(key: string, min: number, max: number, callback?: (err: Error, res: number) => void): Pipeline; + + zcard(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + zscore(key: string, member: string, callback?: (err: Error, res: number) => void): Pipeline; + + zrank(key: string, member: string, callback?: (err: Error, res: number) => void): Pipeline; + + zrevrank(key: string, member: string, callback?: (err: Error, res: number) => void): Pipeline; + + hset(key: string, field: string, value: any, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + hsetnx(key: string, field: string, value: any, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + hget(key: string, field: string, callback?: (err: Error, res: string) => void): Pipeline; + + hmset(key: string, field: string, value: any, ...args: string[]): Pipeline; + + hmget(key: string, field: string, ...fields: string[]): Pipeline; + + hincrby(key: string, field: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; + + hincrbyfloat(key: string, field: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; + + hdel(key: string, field: string, ...fields: string[]): Pipeline; + + hlen(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + hkeys(key: string, callback?: (err: Error, res: any) => void): Pipeline; + + hvals(key: string, callback?: (err: Error, res: any) => void): Pipeline; + + hgetall(key: string, callback?: (err: Error, res: any) => void): Pipeline; + + hexists(key: string, field: string, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + incrby(key: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; + + incrbyfloat(key: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; + + decrby(key: string, decrement: number, callback?: (err: Error, res: number) => void): Pipeline; + + getset(key: string, value: any, callback?: (err: Error, res: string) => void): Pipeline; + + mset(key: string, value: any, ...args: string[]): Pipeline; + + msetnx(key: string, value: any, ...args: string[]): Pipeline; + + randomkey(callback?: (err: Error, res: string) => void): Pipeline; + + select(index: number, callback?: (err: Error, res: string) => void): Pipeline; + + move(key: string, db: string, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + rename(key: string, newkey: string, callback?: (err: Error, res: string) => void): Pipeline; + + renamenx(key: string, newkey: string, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + expire(key: string, seconds: number, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + pexpire(key: string, milliseconds: number, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + expireat(key: string, timestamp: number, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + pexpireat(key: string, millisecondsTimestamp: number, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + keys(pattern: string, callback?: (err: Error, res: string[]) => void): Pipeline; + + dbsize(callback?: (err: Error, res: number) => void): Pipeline; + + auth(password: string, callback?: (err: Error, res: string) => void): Pipeline; + + ping(callback?: (err: Error, res: string) => void): Pipeline; + ping(message: string, callback?: (err: Error, res: string) => void): Pipeline; + + echo(message: string, callback?: (err: Error, res: string) => void): Pipeline; + + save(callback?: (err: Error, res: string) => void): Pipeline; + + bgsave(callback?: (err: Error, res: string) => void): Pipeline; + + bgrewriteaof(callback?: (err: Error, res: string) => void): Pipeline; + + shutdown(save: "SAVE" | "NOSAVE", callback?: (err: Error, res: any) => void): Pipeline; + + lastsave(callback?: (err: Error, res: number) => void): Pipeline; + + type(key: string, callback?: (err: Error, res: string) => void): Pipeline; + + multi(callback?: (err: Error, res: string) => void): Pipeline; + + exec(callback?: (err: Error, res: any) => void): Promise; + + discard(callback?: (err: Error, res: any) => void): Pipeline; + + sync(callback?: (err: Error, res: any) => void): Pipeline; + + flushdb(callback?: (err: Error, res: string) => void): Pipeline; + + flushall(callback?: (err: Error, res: string) => void): Pipeline; + + sort(key: string, ...args: string[]): Pipeline; + + info(callback?: (err: Error, res: any) => void): Pipeline; + info(section: string, callback?: (err: Error, res: any) => void): Pipeline; + + time(callback?: (err: Error, res: any) => void): Pipeline; + + monitor(callback?: (err: Error, res: NodeJS.EventEmitter) => void): Pipeline; + + ttl(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + persist(key: string, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + slaveof(host: string, port: number, callback?: (err: Error, res: string) => void): Pipeline; - get(args: any[], callback?: ResCallbackT): Pipeline; - get(...args: any[]): Pipeline; - set(args: any[], callback?: ResCallbackT): Pipeline; - set(...args: any[]): Pipeline; - setnx(args: any[], callback?: ResCallbackT): Pipeline; - setnx(...args: any[]): Pipeline; - setex(args: any[], callback?: ResCallbackT): Pipeline; - setex(...args: any[]): Pipeline; - psetex(args: any[], callback?: ResCallbackT): Pipeline; - psetex(...args: any[]): Pipeline; - append(args: any[], callback?: ResCallbackT): Pipeline; - append(...args: any[]): Pipeline; - strlen(args: any[], callback?: ResCallbackT): Pipeline; - strlen(...args: any[]): Pipeline; - del(args: any[], callback?: ResCallbackT): Pipeline; - del(...args: any[]): Pipeline; - exists(args: any[], callback?: ResCallbackT): Pipeline; - exists(...args: any[]): Pipeline; - setbit(args: any[], callback?: ResCallbackT): Pipeline; - setbit(...args: any[]): Pipeline; - getbit(args: any[], callback?: ResCallbackT): Pipeline; - getbit(...args: any[]): Pipeline; - setrange(args: any[], callback?: ResCallbackT): Pipeline; - setrange(...args: any[]): Pipeline; - getrange(args: any[], callback?: ResCallbackT): Pipeline; - getrange(...args: any[]): Pipeline; - substr(args: any[], callback?: ResCallbackT): Pipeline; - substr(...args: any[]): Pipeline; - incr(args: any[], callback?: ResCallbackT): Pipeline; - incr(...args: any[]): Pipeline; - decr(args: any[], callback?: ResCallbackT): Pipeline; - decr(...args: any[]): Pipeline; - mget(args: any[], callback?: ResCallbackT): Pipeline; - mget(...args: any[]): Pipeline; - rpush(...args: any[]): Pipeline; - lpush(args: any[], callback?: ResCallbackT): Pipeline; - lpush(...args: any[]): Pipeline; - rpushx(args: any[], callback?: ResCallbackT): Pipeline; - rpushx(...args: any[]): Pipeline; - lpushx(args: any[], callback?: ResCallbackT): Pipeline; - lpushx(...args: any[]): Pipeline; - linsert(args: any[], callback?: ResCallbackT): Pipeline; - linsert(...args: any[]): Pipeline; - rpop(args: any[], callback?: ResCallbackT): Pipeline; - rpop(...args: any[]): Pipeline; - lpop(args: any[], callback?: ResCallbackT): Pipeline; - lpop(...args: any[]): Pipeline; - brpop(args: any[], callback?: ResCallbackT): Pipeline; - brpop(...args: any[]): Pipeline; - brpoplpush(args: any[], callback?: ResCallbackT): Pipeline; - brpoplpush(...args: any[]): Pipeline; - blpop(args: any[], callback?: ResCallbackT): Pipeline; - blpop(...args: any[]): Pipeline; - llen(args: any[], callback?: ResCallbackT): Pipeline; - llen(...args: any[]): Pipeline; - lindex(args: any[], callback?: ResCallbackT): Pipeline; - lindex(...args: any[]): Pipeline; - lset(args: any[], callback?: ResCallbackT): Pipeline; - lset(...args: any[]): Pipeline; - lrange(args: any[], callback?: ResCallbackT): Pipeline; - lrange(...args: any[]): Pipeline; - ltrim(args: any[], callback?: ResCallbackT): Pipeline; - ltrim(...args: any[]): Pipeline; - lrem(args: any[], callback?: ResCallbackT): Pipeline; - lrem(...args: any[]): Pipeline; - rpoplpush(args: any[], callback?: ResCallbackT): Pipeline; - rpoplpush(...args: any[]): Pipeline; - sadd(args: any[], callback?: ResCallbackT): Pipeline; - sadd(...args: any[]): Pipeline; - srem(args: any[], callback?: ResCallbackT): Pipeline; - srem(...args: any[]): Pipeline; - smove(args: any[], callback?: ResCallbackT): Pipeline; - smove(...args: any[]): Pipeline; - sismember(args: any[], callback?: ResCallbackT): Pipeline; - sismember(...args: any[]): Pipeline; - scard(args: any[], callback?: ResCallbackT): Pipeline; - scard(...args: any[]): Pipeline; - spop(args: any[], callback?: ResCallbackT): Pipeline; - spop(...args: any[]): Pipeline; - srandmember(args: any[], callback?: ResCallbackT): Pipeline; - srandmember(...args: any[]): Pipeline; - sinter(args: any[], callback?: ResCallbackT): Pipeline; - sinter(...args: any[]): Pipeline; - sinterstore(args: any[], callback?: ResCallbackT): Pipeline; - sinterstore(...args: any[]): Pipeline; - sunion(args: any[], callback?: ResCallbackT): Pipeline; - sunion(...args: any[]): Pipeline; - sunionstore(args: any[], callback?: ResCallbackT): Pipeline; - sunionstore(...args: any[]): Pipeline; - sdiff(args: any[], callback?: ResCallbackT): Pipeline; - sdiff(...args: any[]): Pipeline; - sdiffstore(args: any[], callback?: ResCallbackT): Pipeline; - sdiffstore(...args: any[]): Pipeline; - smembers(args: any[], callback?: ResCallbackT): Pipeline; - smembers(...args: any[]): Pipeline; - zadd(args: any[], callback?: ResCallbackT): Pipeline; - zadd(...args: any[]): Pipeline; - zincrby(args: any[], callback?: ResCallbackT): Pipeline; - zincrby(...args: any[]): Pipeline; - zrem(args: any[], callback?: ResCallbackT): Pipeline; - zrem(...args: any[]): Pipeline; - zremrangebyscore(args: any[], callback?: ResCallbackT): Pipeline; - zremrangebyscore(...args: any[]): Pipeline; - zremrangebyrank(args: any[], callback?: ResCallbackT): Pipeline; - zremrangebyrank(...args: any[]): Pipeline; - zunionstore(args: any[], callback?: ResCallbackT): Pipeline; - zunionstore(...args: any[]): Pipeline; - zinterstore(args: any[], callback?: ResCallbackT): Pipeline; - zinterstore(...args: any[]): Pipeline; - zrange(args: any[], callback?: ResCallbackT): Pipeline; - zrange(...args: any[]): Pipeline; - zrangebyscore(args: any[], callback?: ResCallbackT): Pipeline; - zrangebyscore(...args: any[]): Pipeline; - zrevrangebyscore(args: any[], callback?: ResCallbackT): Pipeline; - zrevrangebyscore(...args: any[]): Pipeline; - zcount(args: any[], callback?: ResCallbackT): Pipeline; - zcount(...args: any[]): Pipeline; - zrevrange(args: any[], callback?: ResCallbackT): Pipeline; - zrevrange(...args: any[]): Pipeline; - zcard(args: any[], callback?: ResCallbackT): Pipeline; - zcard(...args: any[]): Pipeline; - zscore(args: any[], callback?: ResCallbackT): Pipeline; - zscore(...args: any[]): Pipeline; - zrank(args: any[], callback?: ResCallbackT): Pipeline; - zrank(...args: any[]): Pipeline; - zrevrank(args: any[], callback?: ResCallbackT): Pipeline; - zrevrank(...args: any[]): Pipeline; - hset(args: any[], callback?: ResCallbackT): Pipeline; - hset(...args: any[]): Pipeline; - hsetnx(args: any[], callback?: ResCallbackT): Pipeline; - hsetnx(...args: any[]): Pipeline; - hget(args: any[], callback?: ResCallbackT): Pipeline; - hget(...args: any[]): Pipeline; - hmset(args: any[], callback?: ResCallbackT): Pipeline; - hmset(key: string, hash: any, callback?: ResCallbackT): Pipeline; - hmset(...args: any[]): Pipeline; - hmget(args: any[], callback?: ResCallbackT): Pipeline; - hmget(...args: any[]): Pipeline; - hincrby(args: any[], callback?: ResCallbackT): Pipeline; - hincrby(...args: any[]): Pipeline; - hincrbyfloat(args: any[], callback?: ResCallbackT): Pipeline; - hincrbyfloat(...args: any[]): Pipeline; - hdel(args: any[], callback?: ResCallbackT): Pipeline; - hdel(...args: any[]): Pipeline; - hlen(args: any[], callback?: ResCallbackT): Pipeline; - hlen(...args: any[]): Pipeline; - hkeys(args: any[], callback?: ResCallbackT): Pipeline; - hkeys(...args: any[]): Pipeline; - hvals(args: any[], callback?: ResCallbackT): Pipeline; - hvals(...args: any[]): Pipeline; - hgetall(args: any[], callback?: ResCallbackT): Pipeline; - hgetall(...args: any[]): Pipeline; - hgetall(key: string, callback?: ResCallbackT): Pipeline; - hexists(args: any[], callback?: ResCallbackT): Pipeline; - hexists(...args: any[]): Pipeline; - incrby(args: any[], callback?: ResCallbackT): Pipeline; - incrby(...args: any[]): Pipeline; - incrbyfloat(args: any[], callback?: ResCallbackT): Pipeline; - incrbyfloat(...args: any[]): Pipeline; - decrby(args: any[], callback?: ResCallbackT): Pipeline; - decrby(...args: any[]): Pipeline; - getset(args: any[], callback?: ResCallbackT): Pipeline; - getset(...args: any[]): Pipeline; - mset(args: any[], callback?: ResCallbackT): Pipeline; - mset(...args: any[]): Pipeline; - msetnx(args: any[], callback?: ResCallbackT): Pipeline; - msetnx(...args: any[]): Pipeline; - randomkey(args: any[], callback?: ResCallbackT): Pipeline; - randomkey(...args: any[]): Pipeline; - select(args: any[], callback?: ResCallbackT): void; - select(...args: any[]): Pipeline; - move(args: any[], callback?: ResCallbackT): Pipeline; - move(...args: any[]): Pipeline; - rename(args: any[], callback?: ResCallbackT): Pipeline; - rename(...args: any[]): Pipeline; - renamenx(args: any[], callback?: ResCallbackT): Pipeline; - renamenx(...args: any[]): Pipeline; - expire(args: any[], callback?: ResCallbackT): Pipeline; - expire(...args: any[]): Pipeline; - pexpire(args: any[], callback?: ResCallbackT): Pipeline; - pexpire(...args: any[]): Pipeline; - expireat(args: any[], callback?: ResCallbackT): Pipeline; - expireat(...args: any[]): Pipeline; - pexpireat(args: any[], callback?: ResCallbackT): Pipeline; - pexpireat(...args: any[]): Pipeline; - keys(args: any[], callback?: ResCallbackT): Pipeline; - keys(...args: any[]): Pipeline; - dbsize(args: any[], callback?: ResCallbackT): Pipeline; - dbsize(...args: any[]): Pipeline; - auth(args: any[], callback?: ResCallbackT): void; - auth(...args: any[]): void; - ping(args: any[], callback?: ResCallbackT): Pipeline; - ping(...args: any[]): Pipeline; - echo(args: any[], callback?: ResCallbackT): Pipeline; - echo(...args: any[]): Pipeline; - save(args: any[], callback?: ResCallbackT): Pipeline; - save(...args: any[]): Pipeline; - bgsave(args: any[], callback?: ResCallbackT): Pipeline; - bgsave(...args: any[]): Pipeline; - bgrewriteaof(args: any[], callback?: ResCallbackT): Pipeline; - bgrewriteaof(...args: any[]): Pipeline; - shutdown(args: any[], callback?: ResCallbackT): Pipeline; - shutdown(...args: any[]): Pipeline; - lastsave(args: any[], callback?: ResCallbackT): Pipeline; - lastsave(...args: any[]): Pipeline; - type(args: any[], callback?: ResCallbackT): Pipeline; - type(...args: any[]): Pipeline; - multi(args: any[], callback?: ResCallbackT): Pipeline; - multi(...args: any[]): Pipeline; - exec(args: any[], callback?: ResCallbackT): Pipeline; - exec(...args: any[]): Pipeline; - discard(args: any[], callback?: ResCallbackT): Pipeline; - discard(...args: any[]): Pipeline; - sync(args: any[], callback?: ResCallbackT): Pipeline; - sync(...args: any[]): Pipeline; - flushdb(args: any[], callback?: ResCallbackT): Pipeline; - flushdb(...args: any[]): Pipeline; - flushall(args: any[], callback?: ResCallbackT): Pipeline; - flushall(...args: any[]): Pipeline; - sort(args: any[], callback?: ResCallbackT): Pipeline; - sort(...args: any[]): Pipeline; - info(args: any[], callback?: ResCallbackT): Pipeline; - info(...args: any[]): Pipeline; - time(args: any[], callback?: ResCallbackT): Pipeline; - time(...args: any[]): Pipeline; - monitor(args: any[], callback?: ResCallbackT): Pipeline; - monitor(...args: any[]): Pipeline; - ttl(args: any[], callback?: ResCallbackT): Pipeline; - ttl(...args: any[]): Pipeline; - persist(args: any[], callback?: ResCallbackT): Pipeline; - persist(...args: any[]): Pipeline; - slaveof(args: any[], callback?: ResCallbackT): Pipeline; - slaveof(...args: any[]): Pipeline; - debug(args: any[], callback?: ResCallbackT): Pipeline; debug(...args: any[]): Pipeline; - config(args: any[], callback?: ResCallbackT): Pipeline; + config(...args: any[]): Pipeline; - subscribe(args: any[], callback?: ResCallbackT): Pipeline; - subscribe(...args: any[]): Pipeline; - unsubscribe(args: any[], callback?: ResCallbackT): Pipeline; - unsubscribe(...args: any[]): Pipeline; - psubscribe(args: any[], callback?: ResCallbackT): Pipeline; - psubscribe(...args: any[]): Pipeline; - punsubscribe(args: any[], callback?: ResCallbackT): Pipeline; - punsubscribe(...args: any[]): Pipeline; - publish(args: any[], callback?: ResCallbackT): Pipeline; - publish(...args: any[]): Pipeline; - watch(args: any[], callback?: ResCallbackT): Pipeline; - watch(...args: any[]): Pipeline; - unwatch(args: any[], callback?: ResCallbackT): Pipeline; - unwatch(...args: any[]): Pipeline; - cluster(args: any[], callback?: ResCallbackT): Pipeline; + + subscribe(channel: string, ...channels: any[]): Pipeline; + + unsubscribe(...channels: string[]): Pipeline; + + psubscribe(pattern: string, ...patterns: string[]): Pipeline; + + punsubscribe(...patterns: string[]): Pipeline; + + publish(channel: string, message: string, callback?: (err: Error, res: number) => void): Pipeline; + + watch(key: string, ...keys: string[]): Pipeline; + + unwatch(callback?: (err: Error, res: string) => void): Pipeline; + cluster(...args: any[]): Pipeline; - restore(args: any[], callback?: ResCallbackT): Pipeline; + restore(...args: any[]): Pipeline; - migrate(args: any[], callback?: ResCallbackT): Pipeline; + migrate(...args: any[]): Pipeline; - dump(args: any[], callback?: ResCallbackT): Pipeline; - dump(...args: any[]): Pipeline; - object(args: any[], callback?: ResCallbackT): Pipeline; - object(...args: any[]): Pipeline; - client(args: any[], callback?: ResCallbackT): Pipeline; + + dump(key: string, callback?: (err: Error, res: string) => void): Pipeline; + + object(subcommand: string, ...args: any[]): Pipeline; + client(...args: any[]): Pipeline; - eval(args: any[], callback?: ResCallbackT): Pipeline; + eval(...args: any[]): Pipeline; - evalsha(args: any[], callback?: ResCallbackT): Pipeline; + evalsha(...args: any[]): Pipeline; - quit(args: any[], callback?: ResCallbackT): Pipeline; - quit(...args: any[]): Pipeline; - scan(...args: any[]): Pipeline; - scan(args: any[], callback?: ResCallbackT): Pipeline; - hscan(...args: any[]): Pipeline; - hscan(args: any[], callback?: ResCallbackT): Pipeline; - zscan(...args: any[]): Pipeline; - zscan(args: any[], callback?: ResCallbackT): Pipeline; + + script(...args: any[]): Pipeline; + + quit(callback?: (err: Error, res: string) => void): Pipeline; + + scan(cursor: number, ...args: any[]): Pipeline; + + hscan(key: string, cursor: number, ...args: any[]): Pipeline; + + zscan(key: string, cursor: number, ...args: any[]): Pipeline; + + pfmerge(destkey: string, sourcekey: string, ...sourcekeys: string[]): Pipeline; + + pfadd(key: string, element: string, ...elements: string[]): Pipeline; + + pfcount(key: string, ...keys: string[]): Pipeline; } interface Cluster extends NodeJS.EventEmitter, Commander { - new (nodes: { host: string; port: number; }[], options?: IORedis.ClusterOptions): Redis; - connect(callback: Function): Promise; + new(nodes: Array<{ host: string; port: number; }>, options?: ClusterOptions): Redis; + connect(callback: () => void): Promise; disconnect(): void; nodes(role: string): Redis[]; } - interface ResCallbackT { - (err: Error, res: R): void; - } - interface RedisOptions { port?: number; host?: string; @@ -678,8 +782,8 @@ declare module IORedis { * When the return value isn't a number, ioredis will stop trying to reconnect. * Fixed in: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/15858 */ - retryStrategy?: (times: number) => number | false; - reconnectOnError?: (error: Error) => boolean; + retryStrategy?(times: number): number | false; + reconnectOnError?(error: Error): boolean; /** * By default, if there is no active connection to the Redis server, commands are added to a queue * and are executed once the connection is "ready" (when enableReadyCheck is true, "ready" means @@ -707,7 +811,7 @@ declare module IORedis { tls?: { ca: Buffer; }; - sentinels?: { host: string; port: number; }[]; + sentinels?: Array<{ host: string; port: number; }>; name?: string; /** * Enable READONLY mode for the connection. Only available for cluster mode. @@ -715,8 +819,9 @@ declare module IORedis { */ readOnly?: boolean; /** - * If you are using the hiredis parser, it's highly recommended to enable this option. Create another instance with dropBufferSupport disabled for other commands that you want to return binary instead of string: - */ + * If you are using the hiredis parser, it's highly recommended to enable this option. + * Create another instance with dropBufferSupport disabled for other commands that you want to return binary instead of string + */ dropBufferSupport?: boolean; /** * Whether to show a friendly error stack. Will decrease the performance significantly. @@ -730,7 +835,7 @@ declare module IORedis { } interface ClusterOptions { - clusterRetryStrategy?: (times: number) => number; + clusterRetryStrategy?(times: number): number; enableOfflineQueue?: boolean; enableReadyCheck?: boolean; scaleReads?: string; @@ -740,4 +845,8 @@ declare module IORedis { retryDelayOnTryAgain?: number; redisOptions?: RedisOptions; } + + interface MultiOptions { + pipeline: boolean; + } } diff --git a/types/ioredis/ioredis-tests.ts b/types/ioredis/ioredis-tests.ts index 373fba52c5..02b62def62 100644 --- a/types/ioredis/ioredis-tests.ts +++ b/types/ioredis/ioredis-tests.ts @@ -1,15 +1,13 @@ - - import * as Redis from "ioredis"; -var redis = new Redis(); +const redis = new Redis(); redis.set('foo', 'bar'); -redis.get('foo', function(err, result) { +redis.get('foo', (err, result) => { console.log(result); }); // Or using a promise if the last argument isn't a function -redis.get('foo').then(function(result: any) { +redis.get('foo').then((result: any) => { console.log(result); }); @@ -18,24 +16,24 @@ redis.sadd('set', 1, 3, 5, 7); redis.sadd('set', [1, 3, 5, 7]); // All arguments are passed directly to the redis server: -redis.set('key', 100, 'EX', 10); +redis.set('key', '100', 'EX', 10); -new Redis() // Connect to 127.0.0.1:6379 -new Redis(6380) // 127.0.0.1:6380 -new Redis(6379, '192.168.1.1') // 192.168.1.1:6379 -new Redis('/tmp/redis.sock') +new Redis(); // Connect to 127.0.0.1:6379 +new Redis(6380); // 127.0.0.1:6380 +new Redis(6379, '192.168.1.1'); // 192.168.1.1:6379 +new Redis('/tmp/redis.sock'); new Redis({ port: 6379, // Redis port host: '127.0.0.1', // Redis host family: 4, // 4 (IPv4) or 6 (IPv6) password: 'auth', db: 0, - retryStrategy: function() { return false; }, + retryStrategy() { return false; }, showFriendlyErrorStack: true -}) +}); -var pub = new Redis(); -redis.subscribe('news', 'music', function(err: any, count: any) { +const pub = new Redis(); +redis.subscribe('news', 'music', (err: any, count: any) => { // Now we are subscribed to both the 'news' and 'music' channels. // `count` represents the number of channels we are currently subscribed to. @@ -43,7 +41,7 @@ redis.subscribe('news', 'music', function(err: any, count: any) { pub.publish('music', 'Hello again!'); }); -redis.on('message', function(channel: any, message: any) { +redis.on('message', (channel: any, message: any) => { // Receive message Hello world! from channel news // Receive message Hello again! from channel music console.log('Receive message %s from channel %s', message, channel); @@ -51,6 +49,58 @@ redis.on('message', function(channel: any, message: any) { // There's also an event called 'messageBuffer', which is the same as 'message' except // it returns buffers instead of strings. -redis.on('messageBuffer', function(channel: any, message: any) { +redis.on('messageBuffer', (channel: any, message: any) => { // Both `channel` and `message` are buffers. }); + +const pipeline = redis.pipeline(); +pipeline.set('foo', 'bar'); +pipeline.del('cc'); +pipeline.exec((err, results) => { + // `err` is always null, and `results` is an array of responses + // corresponding to the sequence of queued commands. + // Each response follows the format `[err, result]`. +}); + +// You can even chain the commands: +redis.pipeline().set('foo', 'bar').del('cc').exec((err, results) => { +}); + +// `exec` also returns a Promise: +const promise = redis.pipeline().set('foo', 'bar').get('foo').exec(); +promise.then((result) => { + // result === [[null, 'OK'], [null, 'bar']] +}); + +redis.pipeline().set('foo', 'bar').get('foo', (err, result) => { + // result === 'bar' +}).exec((err, result) => { + // result[1][1] === 'bar' +}); + +redis.pipeline([ + ['set', 'foo', 'bar'], + ['get', 'foo'] +]).exec(() => { /* ... */ }); + +Redis.Command.setArgumentTransformer('set', args => { + return args; +}); + +Redis.Command.setReplyTransformer('get', (result: any) => { + return result; +}); + +// multi +redis.multi().set('foo', 'bar').set('foo', 'baz').get('foo', (err, result) => { + // result === 'QUEUED' +}).exec((err, results) => { + // results = [[null, 'OK'], [null, 'OK'], [null, 'baz']] +}); + +redis.multi([ + ['set', 'foo', 'bar'], + ['get', 'foo'] +]).exec((err, results) => { + // results = [[null, 'OK'], [null, 'bar']] +}); diff --git a/types/ioredis/tslint.json b/types/ioredis/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/ioredis/tslint.json +++ b/types/ioredis/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/is/index.d.ts b/types/is/index.d.ts index 3c0e279eea..b61bd6deee 100644 --- a/types/is/index.d.ts +++ b/types/is/index.d.ts @@ -1320,4 +1320,8 @@ declare var is: Is; declare module 'is' { export = is; -} \ No newline at end of file +} + +declare module 'is_js' { + export = is; +} diff --git a/types/jasmine/index.d.ts b/types/jasmine/index.d.ts index 8775122526..c1c15e45de 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -88,7 +88,12 @@ declare function expect(actual: ArrayLike): jasmine.ArrayLikeMatchers; * Create an expectation for a spec. * @param actual Actual computed value to test expectations against. */ -declare function expect(actual?: T): jasmine.Matchers; +declare function expect(actual: T): jasmine.Matchers; + +/** + * Create an expectation for a spec. + */ +declare function expect(): jasmine.NothingMatcher; /** * Explicitly mark a spec as failed. @@ -137,7 +142,7 @@ declare namespace jasmine { function arrayContaining(sample: ArrayLike): ArrayContaining; function arrayWithExactContents(sample: ArrayLike): ArrayContaining; function objectContaining(sample: Partial): ObjectContaining; - function createSpy(name: string, originalFn?: Function): Spy; + function createSpy(name?: string, originalFn?: Function): Spy; function createSpyObj(baseName: string, methodNames: any[] | {[methodName: string]: any}): any; function createSpyObj(baseName: string, methodNames: any[] | {[methodName: string]: any}): SpyObj; @@ -441,7 +446,6 @@ declare namespace jasmine { toThrow(expected?: any): boolean; toThrowError(message?: string | RegExp): boolean; toThrowError(expected?: new (...args: any[]) => Error, message?: string | RegExp): boolean; - nothing(): Any; not: Matchers; @@ -455,6 +459,10 @@ declare namespace jasmine { not: ArrayLikeMatchers; } + interface NothingMatcher { + nothing(): void; + } + interface Reporter { reportRunnerStarting(runner: Runner): void; reportRunnerResults(runner: Runner): void; diff --git a/types/jasmine/jasmine-tests.ts b/types/jasmine/jasmine-tests.ts index cec0d557a7..ab132d3cee 100644 --- a/types/jasmine/jasmine-tests.ts +++ b/types/jasmine/jasmine-tests.ts @@ -33,7 +33,7 @@ describe("Included matchers:", () => { var b = a; expect(a).toBe(b); - expect(a).not.toBe(null); + expect(a).not.toBe(24); }); describe("The 'toEqual' matcher", () => { @@ -54,6 +54,11 @@ describe("Included matchers:", () => { }; expect(foo).toEqual(bar); }); + + it("should work for optional values", () => { + var opt: string | undefined = "s"; + expect(opt as (string | undefined)).toEqual(undefined); + }); }); it("The 'toMatch' matcher is for regular expressions", () => { @@ -83,7 +88,7 @@ describe("Included matchers:", () => { }); it("The 'toBeNull' matcher compares against null", () => { - var a: string = null; + var a: string | null = null; var foo = "foo"; expect(null).toBeNull(); @@ -92,14 +97,14 @@ describe("Included matchers:", () => { }); it("The 'toBeTruthy' matcher is for boolean casting testing", () => { - var a: string, foo = "foo"; + var a: string | undefined, foo = "foo"; expect(foo).toBeTruthy(); expect(a).not.toBeTruthy(); }); it("The 'toBeFalsy' matcher is for boolean casting testing", () => { - var a: string, foo = "foo"; + var a: string | undefined, foo = "foo"; expect(a).toBeFalsy(); expect(foo).not.toBeFalsy(); @@ -1026,19 +1031,19 @@ var myReporter: jasmine.CustomReporter = { specDone: (result: jasmine.CustomReporterResult) => { console.log("Spec: " + result.description + " was " + result.status); //tslint:disable-next-line:prefer-for-of - for (var i = 0; i < result.failedExpectations.length; i++) { + for (var i = 0; result.failedExpectations && i < result.failedExpectations.length; i++) { console.log("Failure: " + result.failedExpectations[i].message); console.log("Actual: " + result.failedExpectations[i].actual); console.log("Expected: " + result.failedExpectations[i].expected); console.log(result.failedExpectations[i].stack); } - console.log(result.passedExpectations.length); + console.log(result.passedExpectations && result.passedExpectations.length); }, suiteDone: (result: jasmine.CustomReporterResult) => { console.log('Suite: ' + result.description + ' was ' + result.status); //tslint:disable-next-line:prefer-for-of - for (var i = 0; i < result.failedExpectations.length; i++) { + for (var i = 0; result.failedExpectations && i < result.failedExpectations.length; i++) { console.log('AfterAll ' + result.failedExpectations[i].message); console.log(result.failedExpectations[i].stack); } diff --git a/types/jasmine/tsconfig.json b/types/jasmine/tsconfig.json index 3af72e4d8b..55b83c6d3a 100644 --- a/types/jasmine/tsconfig.json +++ b/types/jasmine/tsconfig.json @@ -11,7 +11,7 @@ ], "noImplicitAny": true, "noImplicitThis": false, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": false, "baseUrl": "../", "typeRoots": [ @@ -21,4 +21,4 @@ "noEmit": true, "forceConsistentCasingInFileNames": true } -} \ No newline at end of file +} diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 1b8d137094..5c2152694f 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -145,10 +145,16 @@ declare namespace jest { */ function runOnlyPendingTimers(): typeof jest; /** - * Executes only the macro task queue (i.e. all tasks queued by setTimeout() - * or setInterval() and setImmediate()). + * (renamed to `advanceTimersByTime` in Jest 21.3.0+) Executes only the macro + * task queue (i.e. all tasks queued by setTimeout() or setInterval() and setImmediate()). */ function runTimersToTime(msToRun: number): typeof jest; + /** + * Advances all timers by msToRun milliseconds. All pending "macro-tasks" that have been + * queued via setTimeout() or setInterval(), and would be executed within this timeframe + * will be executed. + */ + function advanceTimersByTime(msToRun: number): typeof jest; /** * Explicitly supplies the mock object that the module system should return * for the specified module. @@ -555,7 +561,7 @@ declare namespace jasmine { function anything(): Any; function arrayContaining(sample: any[]): ArrayContaining; function objectContaining(sample: any): ObjectContaining; - function createSpy(name: string, originalFn?: (...args: any[]) => any): Spy; + function createSpy(name?: string, originalFn?: (...args: any[]) => any): Spy; function createSpyObj(baseName: string, methodNames: any[]): any; function createSpyObj(baseName: string, methodNames: any[]): T; function pp(value: any): string; @@ -867,6 +873,7 @@ declare namespace jest { runAllTicks(): void; runAllTimers(): void; runTimersToTime(msToRun: number): void; + advanceTimersByTime(msToRun: number): void; runOnlyPendingTimers(): void; runWithRealTimers(callback: any): void; useFakeTimers(): void; diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 6dbc08245a..41a8063cac 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -8,6 +8,7 @@ // Rytis Alekna // Pavel Ivanov // Youngrok Kim +// Dan Kraus // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -127,6 +128,13 @@ export interface UriOptions { scheme?: string | RegExp | Array; } +export interface Base64Options { + /** + * optional parameter defaulting to true which will require = padding if true or make padding optional if false + */ + paddingRequired?: boolean; +} + export interface WhenOptions { /** * the required condition joi type. @@ -520,6 +528,12 @@ export interface StringSchema extends AnySchema { */ normalize(form?: 'NFC' | 'NFD' | 'NFKC' | 'NFKD'): this; + /** + * Requires the string value to be a valid base64 string; does not check the decoded value. + * @param options - optional settings: The unicode normalization options to use. Valid values: NFC [default], NFD, NFKC, NFKD + */ + base64(options?: Base64Options): this; + /** * Requires the number to be a credit card number (Using Lunh Algorithm). */ diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index 96d91a72b9..785360746e 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -1,51 +1,52 @@ import Joi = require('joi'); +import { GuidVersions } from 'joi'; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var x: any = null; -var value: any = null; -var num: number = 0; -var str: string = ''; -var bool: boolean = false; -var exp: RegExp = null; -var obj: object = null; -var date: Date = null; -var err: Error = null; -var func: Function = null; +let x: any = null; +let value: any = null; +let num: number = 0; +let str: string = ''; +let bool: boolean = false; +let exp: RegExp = null; +let obj: object = null; +let date: Date = null; +let err: Error = null; +let func: Function = null; -var anyArr: any[] = []; -var numArr: number[] = []; -var strArr: string[] = []; -var boolArr: boolean[] = []; -var expArr: RegExp[] = []; -var objArr: object[] = []; -var errArr: Error[] = []; -var funcArr: Function[] = []; +let anyArr: any[] = []; +let numArr: number[] = []; +let strArr: string[] = []; +let boolArr: boolean[] = []; +let expArr: RegExp[] = []; +let objArr: object[] = []; +let errArr: Error[] = []; +let funcArr: Function[] = []; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var schema: Joi.Schema = null; -var schemaLike: Joi.SchemaLike = null; +let schema: Joi.Schema = null; +let schemaLike: Joi.SchemaLike = null; -var anySchema: Joi.AnySchema = null; -var numSchema: Joi.NumberSchema = null; -var strSchema: Joi.StringSchema = null; -var arrSchema: Joi.ArraySchema = null; -var boolSchema: Joi.BooleanSchema = null; -var binSchema: Joi.BinarySchema = null; -var dateSchema: Joi.DateSchema = null; -var funcSchema: Joi.FunctionSchema = null; -var objSchema: Joi.ObjectSchema = null; -var altSchema: Joi.AlternativesSchema = null; +let anySchema: Joi.AnySchema = null; +let numSchema: Joi.NumberSchema = null; +let strSchema: Joi.StringSchema = null; +let arrSchema: Joi.ArraySchema = null; +let boolSchema: Joi.BooleanSchema = null; +let binSchema: Joi.BinarySchema = null; +let dateSchema: Joi.DateSchema = null; +let funcSchema: Joi.FunctionSchema = null; +let objSchema: Joi.ObjectSchema = null; +let altSchema: Joi.AlternativesSchema = null; -var schemaArr: Joi.Schema[] = []; +let schemaArr: Joi.Schema[] = []; -var ref: Joi.Reference = null; -var description: Joi.Description = null; +let ref: Joi.Reference = null; +let description: Joi.Description = null; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var validOpts: Joi.ValidationOptions = null; +let validOpts: Joi.ValidationOptions = null; validOpts = { abortEarly: bool }; validOpts = { convert: bool }; @@ -77,7 +78,7 @@ validOpts = { // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var renOpts: Joi.RenameOptions = null; +let renOpts: Joi.RenameOptions = null; renOpts = { alias: bool }; renOpts = { multiple: bool }; @@ -86,7 +87,7 @@ renOpts = { ignoreUndefined: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var emailOpts: Joi.EmailOptions = null; +let emailOpts: Joi.EmailOptions = null; emailOpts = { errorLevel: num }; emailOpts = { errorLevel: bool }; @@ -96,7 +97,7 @@ emailOpts = { minDomainAtoms: num }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var ipOpts: Joi.IpOptions = null; +let ipOpts: Joi.IpOptions = null; ipOpts = { version: str }; ipOpts = { version: strArr }; @@ -104,7 +105,7 @@ ipOpts = { cidr: str }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var uriOpts: Joi.UriOptions = null; +let uriOpts: Joi.UriOptions = null; uriOpts = { scheme: str }; uriOpts = { scheme: exp }; @@ -113,7 +114,13 @@ uriOpts = { scheme: expArr }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var whenOpts: Joi.WhenOptions = null; +let base64Opts: Joi.Base64Options = null; + +base64Opts = { paddingRequired: bool }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let whenOpts: Joi.WhenOptions = null; whenOpts = { is: x }; whenOpts = { is: schema, then: schema }; @@ -122,16 +129,16 @@ whenOpts = { is: schemaLike, then: schemaLike, otherwise: schemaLike }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var refOpts: Joi.ReferenceOptions = null; +let refOpts: Joi.ReferenceOptions = null; refOpts = { separator: str }; refOpts = { contextPrefix: str }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var validErr: Joi.ValidationError = null; -var validErrItem: Joi.ValidationErrorItem; -var validErrFunc: Joi.ValidationErrorFunction; +let validErr: Joi.ValidationError = null; +let validErrItem: Joi.ValidationErrorItem; +let validErrFunc: Joi.ValidationErrorFunction; validErrItem = { message: str, @@ -176,7 +183,7 @@ anySchema = objSchema; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var schemaMap: Joi.SchemaMap = null; +let schemaMap: Joi.SchemaMap = null; schemaMap = { a: numSchema, @@ -765,7 +772,7 @@ strSchema = strSchema.ip(ipOpts); strSchema = strSchema.uri(); strSchema = strSchema.uri(uriOpts); strSchema = strSchema.guid(); -strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] }); +strSchema = strSchema.guid({ version: ['uuidv1' as GuidVersions, 'uuidv2' as GuidVersions, 'uuidv3' as GuidVersions, 'uuidv4' as GuidVersions, 'uuidv5' as GuidVersions]}); strSchema = strSchema.guid({ version: 'uuidv4' }); strSchema = strSchema.hex(); strSchema = strSchema.hostname(); @@ -777,6 +784,8 @@ strSchema = strSchema.truncate(); strSchema = strSchema.truncate(false); strSchema = strSchema.normalize(); strSchema = strSchema.normalize('NFKC'); +strSchema = strSchema.base64(); +strSchema = strSchema.base64(base64Opts); namespace common { strSchema = strSchema.allow(x); diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index 543391b23b..2fa264cbd9 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -1,96 +1,103 @@ -// Type definitions for js-yaml 3.10.0 +// Type definitions for js-yaml 3.10 // Project: https://github.com/nodeca/js-yaml // Definitions by: Bart van der Schoor , Sebastian Clausen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 -declare namespace jsyaml { - export function safeLoad(str: string, opts?: LoadOptions): any; - export function load(str: string, opts?: LoadOptions): any; +export function safeLoad(str: string, opts?: LoadOptions): any; +export function load(str: string, opts?: LoadOptions): any; - export interface Type extends TypeConstructorOptions { } - export class Type { - constructor(tag: string, opts?: TypeConstructorOptions); - tag: string; - } - export class Schema { - constructor(definition: SchemaDefinition); - public static create(types: Type[] | Type): Schema; - public static create(schemas: Schema[] | Schema, types: Type[] | Type): Schema; - } - - export function safeLoadAll(str: string, iterator?: (doc: any) => void, opts?: LoadOptions): any; - export function loadAll(str: string, iterator?: (doc: any) => void, opts?: LoadOptions): any; - - export function safeDump(obj: any, opts?: DumpOptions): string; - export function dump(obj: any, opts?: DumpOptions): string; - - export interface LoadOptions { - // string to be used as a file path in error/warning messages. - filename?: string; - // makes the loader to throw errors instead of warnings. - strict?: boolean; - // specifies a schema to use. - schema?: any; - } - - export interface DumpOptions { - // indentation width to use (in spaces). - indent?: number; - // do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. - skipInvalid?: boolean; - // specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere - flowLevel?: number; - // Each tag may have own set of styles. - "tag" => "style" map. - styles?: Object; - // specifies a schema to use. - schema?: any; - // if true, sort keys when dumping YAML. If a function, use the function to sort the keys. (default: false) - sortKeys?: boolean | ((a: any, b: any) => number); - // set max line width. (default: 80) - lineWidth?: number; - // if true, don't convert duplicate objects into references (default: false) - noRefs?: boolean; - // if true don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 (default: false) - noCompatMode?: boolean; - // if true flow sequences will be condensed, omitting the space between `key: value` or `a, b`. Eg. `'[a,b]'` or `{a:{b:c}}`. Can be useful when using yaml for pretty URL query params as spaces are %-encoded. (default: false) - condenseFlow?: boolean; - } - - export interface TypeConstructorOptions { - kind?: string; - resolve?: Function; - construct?: Function; - instanceOf?: Object; - predicate?: string; - represent?: Function; - defaultStyle?: string; - styleAliases?: Object; - } - - export interface SchemaDefinition { - implicit?: any[]; - explicit?: any[]; - include?: any[]; - } - - // only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 - export var FAILSAFE_SCHEMA: any; - // only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 - export var JSON_SCHEMA: any; - // same as JSON_SCHEMA: http://www.yaml.org/spec/1.2/spec.html#id2804923 - export var CORE_SCHEMA: any; - // all supported YAML types, without unsafe ones (!!js/undefined, !!js/regexp and !!js/function): http://yaml.org/type/ - export var DEFAULT_SAFE_SCHEMA: any; - // all supported YAML types. - export var DEFAULT_FULL_SCHEMA: any; - export var MINIMAL_SCHEMA: any; - export var SAFE_SCHEMA: any; - - export class YAMLException extends Error { - constructor(reason?: any, mark?: any); - toString(compact?: boolean): string; - } +export class Type { + constructor(tag: string, opts?: TypeConstructorOptions); + kind: 'sequence' | 'scalar' | 'mapping' | null; + resolve(data: any): boolean; + construct(data: any): any; + instanceOf: object | null; + predicate: string | null; + represent: ((data: object) => any) | { [x: string]: (data: object) => any; } | null; + defaultStyle: string | null; + styleAliases: { [x: string]: any; }; } -export = jsyaml; -export as namespace jsyaml; +/* tslint:disable-next-line:no-unnecessary-class */ +export class Schema implements SchemaDefinition { + constructor(definition: SchemaDefinition); + static create(types: Type[] | Type): Schema; + static create(schemas: Schema[] | Schema, types: Type[] | Type): Schema; +} + +export function safeLoadAll(str: string, iterator?: (doc: any) => void, opts?: LoadOptions): any; +export function loadAll(str: string, iterator?: (doc: any) => void, opts?: LoadOptions): any; + +export function safeDump(obj: any, opts?: DumpOptions): string; +export function dump(obj: any, opts?: DumpOptions): string; + +export interface LoadOptions { + // string to be used as a file path in error/warning messages. + filename?: string; + // makes the loader to throw errors instead of warnings. + strict?: boolean; + // specifies a schema to use. + schema?: any; + // compatibility with JSON.parse behaviour. + json?: boolean; +} + +export interface DumpOptions { + // indentation width to use (in spaces). + indent?: number; + // do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. + skipInvalid?: boolean; + // specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere + flowLevel?: number; + // Each tag may have own set of styles. - "tag" => "style" map. + styles?: { [x: string]: any; }; + // specifies a schema to use. + schema?: any; + // if true, sort keys when dumping YAML. If a function, use the function to sort the keys. (default: false) + sortKeys?: boolean | ((a: any, b: any) => number); + // set max line width. (default: 80) + lineWidth?: number; + // if true, don't convert duplicate objects into references (default: false) + noRefs?: boolean; + // if true don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 (default: false) + noCompatMode?: boolean; + // if true flow sequences will be condensed, omitting the space between `key: value` or `a, b`. Eg. `'[a,b]'` or `{a:{b:c}}`. + // Can be useful when using yaml for pretty URL query params as spaces are %-encoded. (default: false) + condenseFlow?: boolean; +} + +export interface TypeConstructorOptions { + kind?: 'sequence' | 'scalar' | 'mapping'; + resolve?: (data: any) => boolean; + construct?: (data: any) => any; + instanceOf?: object; + predicate?: string; + represent?: ((data: object) => any) | { [x: string]: (data: object) => any }; + defaultStyle?: string; + styleAliases?: { [x: string]: any; }; +} + +export interface SchemaDefinition { + implicit?: any[]; + explicit?: Type[]; + include?: Schema[]; +} + +// only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 +export let FAILSAFE_SCHEMA: Schema; +// only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 +export let JSON_SCHEMA: Schema; +// same as JSON_SCHEMA: http://www.yaml.org/spec/1.2/spec.html#id2804923 +export let CORE_SCHEMA: Schema; +// all supported YAML types, without unsafe ones (!!js/undefined, !!js/regexp and !!js/function): http://yaml.org/type/ +export let DEFAULT_SAFE_SCHEMA: Schema; +// all supported YAML types. +export let DEFAULT_FULL_SCHEMA: Schema; +export let MINIMAL_SCHEMA: Schema; +export let SAFE_SCHEMA: Schema; + +export class YAMLException extends Error { + constructor(reason?: any, mark?: any); + toString(compact?: boolean): string; +} diff --git a/types/js-yaml/js-yaml-tests.ts b/types/js-yaml/js-yaml-tests.ts index af932cb934..3d5ecc17bf 100644 --- a/types/js-yaml/js-yaml-tests.ts +++ b/types/js-yaml/js-yaml-tests.ts @@ -1,45 +1,55 @@ - - import yaml = require('js-yaml'); import LoadOptions = yaml.LoadOptions; import DumpOptions = yaml.DumpOptions; import TypeConstructorOptions = yaml.TypeConstructorOptions; import SchemaDefinition = yaml.SchemaDefinition; -var bool: boolean; -var num: number; -var str: string; -var obj: Object; -var value: any; -var array: any[]; -var fn: Function; -var schemaDefinition: SchemaDefinition = { +const bool = true; +const num = 0; +const str = ""; +const obj: object = {}; +const map: { [x: string]: any; } = {}; +const array: any[] = []; +const fn: (...args: any[]) => any = () => {}; +const type = new yaml.Type(str); + +const schemaDefinition: SchemaDefinition = { implicit: array, explicit: array, include: array }; -var typeConstructorOptions: TypeConstructorOptions = { - kind: str, +const typeConstructorOptions: TypeConstructorOptions = { + kind: "scalar", resolve: fn, construct: fn, instanceOf: obj, predicate: str, represent: fn, defaultStyle: str, - styleAliases: obj + styleAliases: map }; -var loadOpts: LoadOptions; -var dumpOpts: DumpOptions; +const schema: yaml.Schema = new yaml.Schema(schemaDefinition); + +let value: any; +let loadOpts: LoadOptions; +let dumpOpts: DumpOptions; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +// $ExpectType Schema yaml.FAILSAFE_SCHEMA; +// $ExpectType Schema yaml.JSON_SCHEMA; +// $ExpectType Schema yaml.CORE_SCHEMA; +// $ExpectType Schema yaml.DEFAULT_SAFE_SCHEMA; +// $ExpectType Schema yaml.DEFAULT_FULL_SCHEMA; +// $ExpectType Schema yaml.MINIMAL_SCHEMA; +// $ExpectType Schema yaml.SAFE_SCHEMA; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- @@ -53,6 +63,9 @@ loadOpts = { loadOpts = { schema: bool }; +loadOpts = { + json: bool +}; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- @@ -74,46 +87,87 @@ dumpOpts = { // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -value = yaml.safeLoad(str); -value = yaml.safeLoad(str, loadOpts); +// $ExpectType Type +new yaml.Type(str, typeConstructorOptions); -value = yaml.load(str); -value = yaml.load(str, loadOpts); +// $ExpectType "sequence" | "scalar" | "mapping" | null +type.kind; +// $ExpectType (data: any) => boolean +type.resolve; +// $ExpectType (data: any) => any +type.construct; +// $ExpectType object | null +type.instanceOf; +// $ExpectType string | null +type.predicate; +// $ExpectType ((data: object) => any) | { [x: string]: (data: object) => any; } | null +type.represent; +// $ExpectType string | null +type.defaultStyle; +// $ExpectType { [x: string]: any; } +type.styleAliases; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -value = yaml.safeLoadAll(str); -value = yaml.safeLoadAll(str, (doc) => { +// $ExpectType any +yaml.safeLoad(str); +// $ExpectType any +yaml.safeLoad(str, loadOpts); + +// $ExpectType any +yaml.load(str); +// $ExpectType any +yaml.load(str, loadOpts); + +// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + +// $ExpectType any +yaml.safeLoadAll(str); +// $ExpectType any +yaml.safeLoadAll(str, (doc) => { value = doc; }); -value = yaml.safeLoadAll(str, (doc) => { +// $ExpectType any +yaml.safeLoadAll(str, (doc) => { value = doc; }, loadOpts); value = yaml.safeLoadAll(str, undefined, loadOpts); +// $ExpectType any value = yaml.loadAll(str); -value = yaml.loadAll(str, (doc) => { +// $ExpectType any +yaml.loadAll(str, (doc) => { value = doc; }); -value = yaml.loadAll(str, (doc) => { +// $ExpectType any +yaml.loadAll(str, (doc) => { value = doc; }, loadOpts); value = yaml.loadAll(str, undefined, loadOpts); // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -value = yaml.safeDump(str); -value = yaml.safeDump(str, dumpOpts); +// $ExpectType string +yaml.safeDump(str); +// $ExpectType string +yaml.safeDump(str, dumpOpts); -value = yaml.dump(str); -value = yaml.dump(str, dumpOpts); +// $ExpectType string +yaml.dump(str); +// $ExpectType string +yaml.dump(str, dumpOpts); -value = new yaml.YAMLException(); -value = new yaml.Type(str, typeConstructorOptions); -value = new yaml.Schema(schemaDefinition); -value = yaml.Schema.create([new yaml.Type(str)]); -value = yaml.Schema.create(new yaml.Type(str)); -value = yaml.Schema.create(new yaml.Schema(schemaDefinition), [new yaml.Type(str)]); -value = yaml.Schema.create([new yaml.Schema(schemaDefinition)], [new yaml.Type(str)]); -value = yaml.Schema.create(new yaml.Schema(schemaDefinition), new yaml.Type(str)); -value = yaml.Schema.create([new yaml.Schema(schemaDefinition)], new yaml.Type(str)); +new yaml.YAMLException(); + +// $ExpectType Schema +yaml.Schema.create([type]); +// $ExpectType Schema +yaml.Schema.create(type); +// $ExpectType Schema +yaml.Schema.create(schema, [type]); +// $ExpectType Schema +yaml.Schema.create([schema], [type]); +// $ExpectType Schema +yaml.Schema.create(schema, type); +// $ExpectType Schema +yaml.Schema.create([schema], type); diff --git a/types/js-yaml/tsconfig.json b/types/js-yaml/tsconfig.json index b1e787d1b3..c36931fa61 100644 --- a/types/js-yaml/tsconfig.json +++ b/types/js-yaml/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +20,4 @@ "index.d.ts", "js-yaml-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/js-yaml/tslint.json b/types/js-yaml/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/js-yaml/tslint.json +++ b/types/js-yaml/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/js.spec/index.d.ts b/types/js.spec/index.d.ts index 735de40976..764bfa845e 100644 --- a/types/js.spec/index.d.ts +++ b/types/js.spec/index.d.ts @@ -71,7 +71,7 @@ export interface Problem { * @param value the value to test * @returns true if valid */ -export function valid(spec: Spec, value: any): boolean; +export function valid(spec: spec.SpecInput, value: any): boolean; /** * Returns the conformed value to this spec. @@ -79,7 +79,7 @@ export function valid(spec: Spec, value: any): boolean; * @param value the value to test * @returns if the value does not conform to the spec, or the conformed value if it does. */ -export function conform(spec: Spec, value: any): any; +export function conform(spec: spec.SpecInput, value: any): any; /** * Like explain(), but returns Problems array. @@ -87,28 +87,28 @@ export function conform(spec: Spec, value: any): any; * @param value the value to test * @returns list of problems or null if none */ -export function explainData(spec: Spec, value: any): Problem[]; +export function explainData(spec: spec.SpecInput, value: any): Problem[]; /** * Prints, to the console, reasons why the value did not conform to this spec. * @param spec the spec to test with * @param value the value to test */ -export function explain(spec: Spec, value: any): void; +export function explain(spec: spec.SpecInput, value: any): void; /** * Returns a multiline string with reasons why the value did not conform to this spec. * @param spec the spec to test with * @param value the value to test */ -export function explainStr(spec: Spec, value: any): string; +export function explainStr(spec: spec.SpecInput, value: any): string; /** * Tests if a value conforms to a spec, and if not, throws an Error. * @param spec the spec to test with * @param value the value to test */ -export function assert(spec: Spec, value: any): void; +export function assert(spec: spec.SpecInput, value: any): void; export namespace symbol { /** diff --git a/types/js.spec/js.spec-tests.ts b/types/js.spec/js.spec-tests.ts index 8bb9611e87..e1d7703f76 100644 --- a/types/js.spec/js.spec-tests.ts +++ b/types/js.spec/js.spec-tests.ts @@ -7,20 +7,28 @@ const name: string = spec.name; const options: object = spec.options; const isValid: boolean = S.valid(S.spec.boolean, true); +S.valid((value) => true, "a value"); const result = S.conform(S.spec.map("dancing", {field: S.spec.string}), "not a map"); +S.conform((value) => true, "a value"); const problems: S.Problem[] = S.explainData(S.spec.int, "not a number"); +S.explainData((value) => true, "a value"); const {path, via, value, predicate}: {path: string[], via: string[], value: any, predicate: S.Predicate} = problems[0]; const problemStr: string = S.explainStr(S.spec.even, 3); +S.explainStr((value) => true, "a value"); // $ExpectType void S.explain(S.spec.positive, true); +// $ExpectType void +S.explain((value) => true, "a value"); // $ExpectType void S.assert(S.spec.string, "things"); +// $ExpectType void +S.assert((value) => true, "a value"); const symbols: symbol[] = [S.symbol.count, S.symbol.invalid, S.symbol.maxCount, S.symbol.minCount, S.symbol.optional]; diff --git a/types/jschannel/index.d.ts b/types/jschannel/index.d.ts new file mode 100644 index 0000000000..42145531ea --- /dev/null +++ b/types/jschannel/index.d.ts @@ -0,0 +1,46 @@ +// Type definitions for jschannel 1.0 +// Project: https://github.com/yochannah/jschannel +// Definitions by: Yitzchok Gottlieb +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +export as namespace Channel; + +export function build(config: ChannelConfiguration): MessagingChannel; + +export interface MessagingChannel { + unbind: (method: string, doNotPublish?: boolean) => boolean; + bind: (method: string, callback?: (transaction: MessageTransaction, params: any) => void, doNotPublish?: boolean) => MessagingChannel; + call: (message: Message) => void; + notify: (message: Message) => void; + destroy: () => void; +} + +export interface Message { + method: string; + success?: (result: any) => void; + params?: any; + timeout?: number; + error?: (error: any, message: string) => void; +} + +export interface ChannelConfiguration { + window: any; + origin: string; + scope: string; + debugOutput?: boolean; + postMessageObserver?: (origin: string, message: Message) => void; + gotMessageObserver?: (origin: string, message: Message) => void; + onReady?: (channel: MessagingChannel) => void; + reconnect?: boolean; + publish?: boolean; + remote?: string | ReadonlyArray; +} + +export interface MessageTransaction { + delayReturn: (delay: boolean) => boolean; + complete: (result: any) => void; + error: (error: any, message: string) => void; + invoke: (callbackName: string, params: any) => void; + completed: () => boolean; +} diff --git a/types/jschannel/jschannel-tests.ts b/types/jschannel/jschannel-tests.ts new file mode 100644 index 0000000000..eabd150bf2 --- /dev/null +++ b/types/jschannel/jschannel-tests.ts @@ -0,0 +1,3 @@ +import { build } from 'jschannel'; + +build({ window: null, origin: "*", scope: "testScope"}); diff --git a/types/jschannel/tsconfig.json b/types/jschannel/tsconfig.json new file mode 100644 index 0000000000..83727a281c --- /dev/null +++ b/types/jschannel/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jschannel-tests.ts" + ] +} diff --git a/types/jschannel/tslint.json b/types/jschannel/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jschannel/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/keypress.js/index.d.ts b/types/keypress.js/index.d.ts index 63da327acd..202990da93 100644 --- a/types/keypress.js/index.d.ts +++ b/types/keypress.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Keypress 2.0 +// Type definitions for Keypress 2.1 // Project: https://github.com/dmauro/Keypress/ // Definitions by: Roger Chen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -39,9 +39,9 @@ export class Listener { simple_combo(keys: string, on_keydown_callback: (event?: KeyboardEvent, count?: number) => any): void; counting_combo(keys: string, on_count_callback: (event?: KeyboardEvent, count?: number) => any): void; sequence_combo(keys: string, callback: (event?: KeyboardEvent, count?: number) => any): void; - register_combo(combo: Combo): void; + register_combo(combo: Combo): Combo; unregister_combo(combo: Combo | string): void; - register_many(combos: Combo[]): void; + register_many(combos: Combo[]): Combo[]; unregister_many(combos: Combo[] | string[]): void; get_registered_combos(): Combo[]; destroy(): void; diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index 974c3eb0a4..e96dfbefd8 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Knex.js // Project: https://github.com/tgriesser/knex -// Definitions by: Qubo , Baronfel +// Definitions by: Qubo , Baronfel , Pablo Rodríguez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -8,7 +8,7 @@ import events = require("events"); import stream = require ("stream"); -import Promise = require("bluebird"); +import Bluebird = require("bluebird"); type Callback = Function; type Client = Function; @@ -22,9 +22,9 @@ interface Knex extends Knex.QueryInterface { __knex__: string; raw: Knex.RawBuilder; - transaction(transactionScope: (trx: Knex.Transaction) => any): Promise; + transaction(transactionScope: (trx: Knex.Transaction) => Promise | Bluebird | void): Bluebird; destroy(callback: Function): void; - destroy(): Promise; + destroy(): Bluebird; batchInsert(tableName : TableName, data: any[], chunkSize : number) : Knex.QueryBuilder; schema: Knex.SchemaBuilder; queryBuilder(): Knex.QueryBuilder; @@ -156,7 +156,7 @@ declare namespace Knex { delete(returning?: string | string[]): QueryBuilder; truncate(): QueryBuilder; - transacting(trx: Transaction): QueryBuilder; + transacting(trx?: Transaction): QueryBuilder; connection(connection: any): QueryBuilder; clone(): QueryBuilder; @@ -351,7 +351,7 @@ declare namespace Knex { and: QueryBuilder; //TODO: Promise? - columnInfo(column?: string): Promise; + columnInfo(column?: string): Bluebird; forUpdate(): QueryBuilder; forShare(): QueryBuilder; @@ -372,18 +372,18 @@ declare namespace Knex { // Chainable interface // - interface ChainableInterface extends Promise { + interface ChainableInterface extends Bluebird { toQuery(): string; options(options: any): QueryBuilder; - stream(callback: (readable: stream.PassThrough) => any): Promise; + stream(callback: (readable: stream.PassThrough) => any): Bluebird; stream(options?: { [key: string]: any }): stream.PassThrough; - stream(options: { [key: string]: any }, callback: (readable: stream.PassThrough) => any): Promise; + stream(options: { [key: string]: any }, callback: (readable: stream.PassThrough) => any): Bluebird; pipe(writable: any): stream.PassThrough; exec(callback: Function): QueryBuilder; } interface Transaction extends Knex { - savepoint(transactionScope: (trx: Transaction) => any): Promise; + savepoint(transactionScope: (trx: Transaction) => any): Bluebird; commit(value?: any): QueryBuilder; rollback(error?: any): QueryBuilder; } @@ -392,14 +392,14 @@ declare namespace Knex { // Schema builder // - interface SchemaBuilder extends Promise { + interface SchemaBuilder extends Bluebird { createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; createTableIfNotExists(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; - renameTable(oldTableName: string, newTableName: string): Promise; + renameTable(oldTableName: string, newTableName: string): Bluebird; dropTable(tableName: string): SchemaBuilder; - hasTable(tableName: string): Promise; - hasColumn(tableName: string, columnName: string): Promise; - table(tableName: string, callback: (tableBuilder: AlterTableBuilder) => any): Promise; + hasTable(tableName: string): Bluebird; + hasColumn(tableName: string, columnName: string): Bluebird; + table(tableName: string, callback: (tableBuilder: AlterTableBuilder) => any): Bluebird; dropTableIfExists(tableName: string): SchemaBuilder; raw(statement: string): SchemaBuilder; withSchema(schemaName: string): SchemaBuilder; @@ -666,11 +666,11 @@ declare namespace Knex { } interface Migrator { - make(name: string, config?: MigratorConfig): Promise; - latest(config?: MigratorConfig): Promise; - rollback(config?: MigratorConfig): Promise; - status(config?: MigratorConfig): Promise; - currentVersion(config?: MigratorConfig): Promise; + make(name: string, config?: MigratorConfig): Bluebird; + latest(config?: MigratorConfig): Bluebird; + rollback(config?: MigratorConfig): Bluebird; + status(config?: MigratorConfig): Bluebird; + currentVersion(config?: MigratorConfig): Bluebird; } interface FunctionHelper { diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index 95d28b1b2b..c7c99813f1 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -520,7 +520,6 @@ knex.transaction(function(trx) { }) .then(trx.commit) .catch(trx.rollback); - }).then(function() { console.log('Transaction complete.'); }).catch(function(err) { @@ -537,7 +536,17 @@ knex.transaction(function(trx) { .transacting(trx) .forShare() .select('*') -}); +}) + +const transactionReturnValue = knex.transaction(function(trx) { + return knex("table") + .insert({ foo: "bar" }) + .returning(["id"]) + .then(function(result) { return result[0].id as number }) +}) + +// Tests that the transaction has kept the type of its return value by referencing a method of number +transactionReturnValue.then(value => value.toExponential); knex('users').count('active'); @@ -616,7 +625,7 @@ knex.transaction(function(trx) { }); // Using trx as a transaction object: -knex.transaction(function(trx) { +knex.transaction<{ length: number }>(function(trx) { trx.raw(''); @@ -663,6 +672,9 @@ knex.transaction(function(trx) { console.error(error); }); +// transacting handles undefined +knex.insert({ name: 'Old Books'}).transacting(undefined); + knex.schema.withSchema("public").hasTable("table") as Promise; knex.schema.createTable('users', function (table) { diff --git a/types/knockout-amd-helpers/index.d.ts b/types/knockout-amd-helpers/index.d.ts index d12c8d9a8f..6f3a5493e1 100644 --- a/types/knockout-amd-helpers/index.d.ts +++ b/types/knockout-amd-helpers/index.d.ts @@ -2,10 +2,10 @@ // Project: https://github.com/rniemeyer/knockout-amd-helpers // Definitions by: David Sichau // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// - interface KnockoutAMDModule { baseDir: string; initializer: string; diff --git a/types/knockout-secure-binding/index.d.ts b/types/knockout-secure-binding/index.d.ts index 84a432738b..f7c7500cff 100644 --- a/types/knockout-secure-binding/index.d.ts +++ b/types/knockout-secure-binding/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/brianmhunt/knockout-secure-binding // Definitions by: Pine Mizune // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// @@ -28,4 +29,4 @@ declare module "knockout-secure-binding" { }; export = klass; -} \ No newline at end of file +} diff --git a/types/knockout-transformations/index.d.ts b/types/knockout-transformations/index.d.ts index 958eb99fb6..5fab318c1b 100644 --- a/types/knockout-transformations/index.d.ts +++ b/types/knockout-transformations/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/One-com/knockout-transformations // Definitions by: John Reilly , Wim Looman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.deferred.updates/index.d.ts b/types/knockout.deferred.updates/index.d.ts index 89fb752089..c02f371277 100644 --- a/types/knockout.deferred.updates/index.d.ts +++ b/types/knockout.deferred.updates/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mbest/knockout-deferred-updates // Definitions by: Sebastián Galiano // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// @@ -42,4 +43,4 @@ interface KnockoutUtils { // Deferred extender interface KnockoutExtenders { deferred(target: any, value: boolean): any; -} \ No newline at end of file +} diff --git a/types/knockout.editables/index.d.ts b/types/knockout.editables/index.d.ts index 4a4ed59d3b..5167287e7e 100644 --- a/types/knockout.editables/index.d.ts +++ b/types/knockout.editables/index.d.ts @@ -2,6 +2,7 @@ // Project: http://romanych.github.com/ko.editables/ // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.es5/index.d.ts b/types/knockout.es5/index.d.ts index ce41db0d73..0ae2526c25 100644 --- a/types/knockout.es5/index.d.ts +++ b/types/knockout.es5/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/SteveSanderson/knockout-es5 // Definitions by: Sebastián Galiano // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.mapper/index.d.ts b/types/knockout.mapper/index.d.ts index 747a3d1f4a..d77f3e8f22 100644 --- a/types/knockout.mapper/index.d.ts +++ b/types/knockout.mapper/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/LucasLorentz/knockout.mapper // Definitions by: Brandon Meyer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.mapping/index.d.ts b/types/knockout.mapping/index.d.ts index 23f7aae8b5..e6d5fe2f6c 100644 --- a/types/knockout.mapping/index.d.ts +++ b/types/knockout.mapping/index.d.ts @@ -1,7 +1,9 @@ // Type definitions for Knockout.Mapping 2.0 // Project: https://github.com/SteveSanderson/knockout.mapping -// Definitions by: Boris Yankov +// Definitions by: Boris Yankov , +// Mathias Lorenzen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// @@ -33,17 +35,25 @@ declare global { update?: (options: KnockoutMappingUpdateOptions) => void; key?: (data: any) => any; } + + type KnockoutObservableType = { + [P in keyof T]: KnockoutObservable; + }; interface KnockoutMapping { isMapped(viewModel: any): boolean; - fromJS(jsObject: any): any; - fromJS(jsObject: any, targetOrOptions: any): any; - fromJS(jsObject: any, inputOptions: any, target: any): any; + fromJS(jsObject: T[]): KnockoutObservableType[]; + fromJS(jsObject: T[], targetOrOptions: any): KnockoutObservableType[]; + fromJS(jsObject: T[], inputOptions: any, target: any): KnockoutObservableType[]; + fromJS(jsObject: T): KnockoutObservableType; + fromJS(jsObject: T, targetOrOptions: any): KnockoutObservableType; + fromJS(jsObject: T, inputOptions: any, target: any): KnockoutObservableType; fromJSON(jsonString: string): any; fromJSON(jsonString: string, targetOrOptions: any): any; fromJSON(jsonString: string, inputOptions: any, target: any): any; - toJS(rootObject: any, options?: KnockoutMappingOptions): any; - toJSON(rootObject: any, options?: KnockoutMappingOptions): any; + toJS(rootObject: KnockoutObservableArray|T, options?: KnockoutMappingOptions): T[]; + toJS(rootObject: KnockoutObservableType|T, options?: KnockoutMappingOptions): T; + toJSON(rootObject: any, options?: KnockoutMappingOptions): string; defaultOptions(): KnockoutMappingOptions; resetDefaultOptions(): void; getType(x: any): any; diff --git a/types/knockout.postbox/index.d.ts b/types/knockout.postbox/index.d.ts index 56afa3a2b6..d7e967bcb9 100644 --- a/types/knockout.postbox/index.d.ts +++ b/types/knockout.postbox/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/rniemeyer/knockout-postbox // Definitions by: Judah Gabriel Himango // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.projections/index.d.ts b/types/knockout.projections/index.d.ts index aae8b55f57..bed2ac82ca 100644 --- a/types/knockout.projections/index.d.ts +++ b/types/knockout.projections/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/stevesanderson/knockout-projections // Definitions by: John Reilly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.punches/index.d.ts b/types/knockout.punches/index.d.ts index aec2860bd9..c378d68c37 100644 --- a/types/knockout.punches/index.d.ts +++ b/types/knockout.punches/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mbest/knockout.punches // Definitions by: Stephen Lautier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.rx/index.d.ts b/types/knockout.rx/index.d.ts index 82a5473f1c..fea2c5175b 100644 --- a/types/knockout.rx/index.d.ts +++ b/types/knockout.rx/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Igorbek/knockout.rx // Definitions by: Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// /// diff --git a/types/knockout.validation/index.d.ts b/types/knockout.validation/index.d.ts index 8b0300bd7f..e302ee6279 100644 --- a/types/knockout.validation/index.d.ts +++ b/types/knockout.validation/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/ericmbarnard/Knockout-Validation // Definitions by: Dan Ludwig // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.viewmodel/index.d.ts b/types/knockout.viewmodel/index.d.ts index 5e57afb449..2ea6815531 100644 --- a/types/knockout.viewmodel/index.d.ts +++ b/types/knockout.viewmodel/index.d.ts @@ -2,6 +2,7 @@ // Project: http://coderenaissance.github.com/knockout.viewmodel/ // Definitions by: Oisin Grehan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index 4ef3bc8739..8d035ed8d2 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -1,12 +1,13 @@ // Type definitions for Knockout v3.4.0 // Project: http://knockoutjs.com -// Definitions by: Boris Yankov -// Igor Oleinikov -// Clément Bourgeois -// Matt Brooks -// Benjamin Eckardt +// Definitions by: Boris Yankov , +// Igor Oleinikov , +// Clément Bourgeois , +// Matt Brooks , +// Benjamin Eckardt , +// Mathias Lorenzen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 interface KnockoutExtensionFunctions { [key: string]: any; diff --git a/types/knockout/test/index.ts b/types/knockout/test/index.ts index e3f7820f94..9913b64fa8 100644 --- a/types/knockout/test/index.ts +++ b/types/knockout/test/index.ts @@ -484,8 +484,8 @@ function test_mappingplugin() { ko.mapping.fromJS(data, {}, this); var alice, aliceMappingOptions, bob, bobMappingOptions; - var viewModel = ko.mapping.fromJS(alice, aliceMappingOptions); - ko.mapping.fromJS(bob, bobMappingOptions, viewModel); + var aliceViewModel = ko.mapping.fromJS(alice, aliceMappingOptions); + ko.mapping.fromJS(bob, bobMappingOptions, aliceViewModel); var obj; var result = ko.mapping.fromJS(obj, { diff --git a/types/koa-router/index.d.ts b/types/koa-router/index.d.ts index ba7815ef54..4ad96140eb 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -34,15 +34,25 @@ declare module Router { export interface IRouterOptions { /** - * Router prefixes + * Prefix for all routes. */ prefix?: string; /** - * HTTP verbs + * Methods which should be supported by the router. */ methods?: string[]; routerPath?: string; + /** + * Whether or not routing should be case-sensitive. + */ sensitive?: boolean; + /** + * Whether or not routes should matched strictly. + * + * If strict matching is enabled, the trailing slash is taken into + * account when matching routes. + */ + strict?: boolean; } export interface IRouterContext extends Koa.Context { @@ -140,7 +150,7 @@ declare class Router { * "down" the middleware stack. */ use(...middleware: Array): Router; - use(path: string | RegExp, ...middleware: Array): Router; + use(path: string | string[] | RegExp, ...middleware: Array): Router; /** * HTTP get method diff --git a/types/koa/index.d.ts b/types/koa/index.d.ts index d46920bf07..d4f339aa32 100644 --- a/types/koa/index.d.ts +++ b/types/koa/index.d.ts @@ -136,6 +136,11 @@ declare interface ContextDelegatedRequest { */ secure: boolean; + /** + * Request remote address. Supports X-Forwarded-For when app.proxy is true. + */ + ip: string; + /** * When `app.proxy` is `true`, parse * the "X-Forwarded-For" ip address list. diff --git a/types/kolite/knockout.activity.d.ts b/types/kolite/knockout.activity.d.ts index 8a1f1a0fac..8022e18cff 100644 --- a/types/kolite/knockout.activity.d.ts +++ b/types/kolite/knockout.activity.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/CodeSeven/kolite // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 /// /// diff --git a/types/kolite/knockout.command.d.ts b/types/kolite/knockout.command.d.ts index ff509dbd16..786bbcfaae 100644 --- a/types/kolite/knockout.command.d.ts +++ b/types/kolite/knockout.command.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/CodeSeven/kolite // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 /// /// diff --git a/types/kolite/knockout.dirtyFlag.d.ts b/types/kolite/knockout.dirtyFlag.d.ts index 1c63ce8b7d..2f63a110e0 100644 --- a/types/kolite/knockout.dirtyFlag.d.ts +++ b/types/kolite/knockout.dirtyFlag.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/CodeSeven/kolite // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 /// /// diff --git a/types/leaflet-draw/index.d.ts b/types/leaflet-draw/index.d.ts index de0767d462..35d014b699 100644 --- a/types/leaflet-draw/index.d.ts +++ b/types/leaflet-draw/index.d.ts @@ -66,6 +66,13 @@ declare module 'leaflet' { */ circle?: DrawOptions.CircleOptions | false; + /** + * Circle marker draw handler options. Set to false to disable handler. + * + * Default value: {} + */ + circlemarker?: DrawOptions.CircleMarkerOptions | false; + /** * Marker draw handler options. Set to false to disable handler. * @@ -201,6 +208,71 @@ declare module 'leaflet' { repeatMode?: boolean; } + interface CircleMarkerOptions { + /** + * Whether to draw stroke around the circle marker. + * + * Default value: true + */ + stroke?: boolean; + + /** + * The stroke color of the circle marker. + * + * Default value: '#3388ff' + */ + color?: string; + + /** + * The stroke width in pixels of the circle marker. + * + * Default value: 4 + */ + weight?: number; + + /** + * The stroke opacity of the circle marker. + * + * Default value: 0.5 + */ + opacity?: number; + + /** + * Whether to fill the circle marker with color. + * + * Default value: true + */ + fill?: boolean; + + /** + * The fill color of the circle marker. Defaults to the value of the color option. + * + * Default value: null + */ + fillColor?: string; + + /** + * The opacity of the circle marker. + * + * Default value: 0.2 + */ + fillOpacity?: number; + + /** + * Whether you can click the circle marker. + * + * Default value: true + */ + clickable?: boolean; + + /** + * This should be a high number to ensure that you can draw over all other layers on the map. + * + * Default value: 2000 + */ + zIndexOffset?: number; + } + interface MarkerOptions { /** * TThe icon displayed when drawing a marker. diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index f038846d22..a0eaef941c 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -1234,7 +1234,7 @@ declare namespace _ { */ findIndex( array: List | null | undefined, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): number; } @@ -1245,7 +1245,7 @@ declare namespace _ { */ findIndex( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): number; } @@ -1256,7 +1256,7 @@ declare namespace _ { */ findIndex( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; } @@ -1282,7 +1282,7 @@ declare namespace _ { */ findLastIndex( array: List | null | undefined, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): number; } @@ -1293,7 +1293,7 @@ declare namespace _ { */ findLastIndex( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): number; } @@ -1304,7 +1304,7 @@ declare namespace _ { */ findLastIndex( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; } @@ -4315,6 +4315,14 @@ declare namespace _ { * @param thisArg The this binding of iteratee. * @return Returns the composed aggregate object. */ + countBy( + collection: string | null | undefined, + iteratee?: StringIterator + ): Dictionary; + + /** + * @see _.countBy + */ countBy( collection: List | null | undefined, iteratee?: ListIteratee @@ -4338,6 +4346,14 @@ declare namespace _ { } interface LoDashImplicitWrapper { + /** + * @see _.countBy + */ + countBy( + this: LoDashImplicitWrapper, + iteratee?: StringIterator + ): LoDashImplicitWrapper>; + /** * @see _.countBy */ @@ -4364,6 +4380,14 @@ declare namespace _ { } interface LoDashExplicitWrapper { + /** + * @see _.countBy + */ + countBy( + this: LoDashExplicitWrapper, + iteratee?: StringIterator + ): LoDashExplicitWrapper>; + /** * @see _.countBy */ @@ -4479,7 +4503,7 @@ declare namespace _ { */ every( collection: List | null | undefined, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): boolean; /** @@ -4487,7 +4511,7 @@ declare namespace _ { */ every( collection: NumericDictionary | null | undefined, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): boolean; /** @@ -4495,7 +4519,7 @@ declare namespace _ { */ every( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): boolean; } @@ -4505,7 +4529,7 @@ declare namespace _ { */ every( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): boolean; /** @@ -4513,7 +4537,7 @@ declare namespace _ { */ every( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): boolean; /** @@ -4521,7 +4545,7 @@ declare namespace _ { */ every( this: LoDashImplicitWrapper | null | undefined>, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): boolean; } @@ -4531,7 +4555,7 @@ declare namespace _ { */ every( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashExplicitWrapper; /** @@ -4539,7 +4563,7 @@ declare namespace _ { */ every( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashExplicitWrapper; /** @@ -4547,7 +4571,7 @@ declare namespace _ { */ every( this: LoDashExplicitWrapper | null | undefined>, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): LoDashExplicitWrapper; } @@ -4589,7 +4613,7 @@ declare namespace _ { */ filter( collection: List | null | undefined, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): T[]; /** @@ -4605,7 +4629,7 @@ declare namespace _ { */ filter( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): Array; } @@ -4631,7 +4655,7 @@ declare namespace _ { */ filter( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashImplicitWrapper; /** @@ -4647,7 +4671,7 @@ declare namespace _ { */ filter( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashImplicitWrapper>; } @@ -4673,7 +4697,7 @@ declare namespace _ { */ filter( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashExplicitWrapper; /** @@ -4689,7 +4713,7 @@ declare namespace _ { */ filter( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashExplicitWrapper>; } @@ -4724,7 +4748,7 @@ declare namespace _ { */ find( collection: List | null | undefined, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): T|undefined; @@ -4742,7 +4766,7 @@ declare namespace _ { */ find( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): T[keyof T]|undefined; } @@ -4762,7 +4786,7 @@ declare namespace _ { */ find( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): T|undefined; @@ -4780,7 +4804,7 @@ declare namespace _ { */ find( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): T[keyof T]|undefined; } @@ -4800,7 +4824,7 @@ declare namespace _ { */ find( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; @@ -4818,7 +4842,7 @@ declare namespace _ { */ find( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; } @@ -4844,7 +4868,7 @@ declare namespace _ { */ findLast( collection: List | null | undefined, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): T|undefined; @@ -4862,7 +4886,7 @@ declare namespace _ { */ findLast( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): T[keyof T]|undefined; } @@ -4882,7 +4906,7 @@ declare namespace _ { */ findLast( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): T | undefined; @@ -4900,7 +4924,7 @@ declare namespace _ { */ findLast( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): T[keyof T]|undefined; } @@ -4920,7 +4944,7 @@ declare namespace _ { */ findLast( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; @@ -4938,7 +4962,7 @@ declare namespace _ { */ findLast( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; } @@ -5849,9 +5873,17 @@ declare namespace _ { * @param thisArg The this binding of iteratee. * @return Returns the composed aggregate object. */ + keyBy( + collection: string | null | undefined, + iteratee?: StringIterator + ): Dictionary; + + /** + * @see _.keyBy + */ keyBy( collection: List | null | undefined, - iteratee?: ListIteratee + iteratee?: ListIterateeCustom ): Dictionary; /** @@ -5859,7 +5891,7 @@ declare namespace _ { */ keyBy( collection: T | null | undefined, - iteratee?: ObjectIteratee + iteratee?: ObjectIterateeCustom ): Dictionary; /** @@ -5867,17 +5899,25 @@ declare namespace _ { */ keyBy( collection: NumericDictionary | null | undefined, - iteratee?: NumericDictionaryIteratee + iteratee?: NumericDictionaryIterateeCustom ): Dictionary; } interface LoDashImplicitWrapper { + /** + * @see _.keyBy + */ + keyBy( + this: LoDashImplicitWrapper, + iteratee?: StringIterator + ): LoDashImplicitWrapper>; + /** * @see _.keyBy */ keyBy( this: LoDashImplicitWrapper | null | undefined>, - iteratee?: ListIteratee + iteratee?: ListIterateeCustom ): LoDashImplicitWrapper>; /** @@ -5885,7 +5925,7 @@ declare namespace _ { */ keyBy( this: LoDashImplicitWrapper, - iteratee?: ObjectIteratee + iteratee?: ObjectIterateeCustom ): LoDashImplicitWrapper>; /** @@ -5893,17 +5933,25 @@ declare namespace _ { */ keyBy( this: LoDashImplicitWrapper | null | undefined>, - iteratee?: NumericDictionaryIteratee + iteratee?: NumericDictionaryIterateeCustom ): LoDashImplicitWrapper>; } interface LoDashExplicitWrapper { + /** + * @see _.keyBy + */ + keyBy( + this: LoDashExplicitWrapper, + iteratee?: StringIterator + ): LoDashExplicitWrapper>; + /** * @see _.keyBy */ keyBy( this: LoDashExplicitWrapper | null | undefined>, - iteratee?: ListIteratee + iteratee?: ListIterateeCustom ): LoDashExplicitWrapper>; /** @@ -5911,7 +5959,7 @@ declare namespace _ { */ keyBy( this: LoDashExplicitWrapper, - iteratee?: ObjectIteratee + iteratee?: ObjectIterateeCustom ): LoDashExplicitWrapper>; /** @@ -5919,7 +5967,7 @@ declare namespace _ { */ keyBy( this: LoDashExplicitWrapper | null | undefined>, - iteratee?: NumericDictionaryIteratee + iteratee?: NumericDictionaryIterateeCustom ): LoDashExplicitWrapper>; } @@ -6718,7 +6766,7 @@ declare namespace _ { */ reject( collection: List | null | undefined, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): T[]; /** @@ -6726,7 +6774,7 @@ declare namespace _ { */ reject( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): Array; } @@ -6744,7 +6792,7 @@ declare namespace _ { */ reject( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashImplicitWrapper; /** @@ -6752,7 +6800,7 @@ declare namespace _ { */ reject( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashImplicitWrapper>; } @@ -6770,7 +6818,7 @@ declare namespace _ { */ reject( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashExplicitWrapper; /** @@ -6778,7 +6826,7 @@ declare namespace _ { */ reject( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashExplicitWrapper>; } @@ -6992,7 +7040,7 @@ declare namespace _ { */ some( collection: List | null | undefined, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): boolean; /** @@ -7000,7 +7048,7 @@ declare namespace _ { */ some( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): boolean; /** @@ -7008,7 +7056,7 @@ declare namespace _ { */ some( collection: NumericDictionary | null | undefined, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): boolean; } @@ -7018,7 +7066,7 @@ declare namespace _ { */ some( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): boolean; /** @@ -7026,7 +7074,7 @@ declare namespace _ { */ some( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): boolean; /** @@ -7034,7 +7082,7 @@ declare namespace _ { */ some( this: LoDashImplicitWrapper | null | undefined>, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): boolean; } @@ -7044,7 +7092,7 @@ declare namespace _ { */ some( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashExplicitWrapper; /** @@ -7052,7 +7100,7 @@ declare namespace _ { */ some( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashExplicitWrapper; /** @@ -7060,7 +7108,7 @@ declare namespace _ { */ some( this: LoDashExplicitWrapper | null | undefined>, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): LoDashExplicitWrapper; } @@ -9315,14 +9363,16 @@ declare namespace _ { /** * @see _.conformsTo */ - conformsTo(source: ConformsPredicateObject): boolean; + conformsTo(this: LoDashImplicitWrapper, source: ConformsPredicateObject): boolean; + // Note: we can't use TValue here, because it generates a typescript error when strictFunctionTypes is enabled. } interface LoDashExplicitWrapper { /** * @see _.conformsTo */ - conformsTo(source: ConformsPredicateObject): LoDashExplicitWrapper; + conformsTo(this: LoDashImplicitWrapper, source: ConformsPredicateObject): LoDashExplicitWrapper; + // Note: we can't use TValue here, because it generates a typescript error when strictFunctionTypes is enabled. } type CondPair = [(val: T) => boolean, (val: T) => R] @@ -10723,7 +10773,7 @@ declare namespace _ { /** * @see _.toArray */ - toArray(): LoDashImplicitWrapper>; + toArray(this: LoDashImplicitWrapper): LoDashImplicitWrapper>; } interface LoDashExplicitWrapper { @@ -10735,7 +10785,7 @@ declare namespace _ { /** * @see _.toArray */ - toArray(): LoDashExplicitWrapper>; + toArray(this: LoDashImplicitWrapper): LoDashExplicitWrapper>; } //_.toPlainObject @@ -14348,6 +14398,9 @@ declare namespace _ { ...props: Array> ): Pick; + /** + * @see _.pick + */ pick( object: T | null | undefined, ...props: PropertyPath[] @@ -14355,6 +14408,14 @@ declare namespace _ { } interface LoDashImplicitWrapper { + /** + * @see _.pick + */ + pick( + this: LoDashImplicitWrapper, + ...props: Array> + ): LoDashImplicitWrapper>; + /** * @see _.pick */ @@ -14365,6 +14426,14 @@ declare namespace _ { } interface LoDashExplicitWrapper { + /** + * @see _.pick + */ + pick( + this: LoDashExplicitWrapper, + ...props: Array> + ): LoDashExplicitWrapper>; + /** * @see _.pick */ @@ -17015,13 +17084,13 @@ declare namespace _ { type ArrayIterator = (value: T, index: number, collection: T[]) => TResult; type ListIterator = (value: T, index: number, collection: List) => TResult; type ListIteratee = ListIterator | string | [string, any] | PartialDeep; - type ListIterateeBoolean = ListIterator | string | [string, any] | PartialDeep; + type ListIterateeCustom = ListIterator | string | [string, any] | PartialDeep; type ListIteratorTypeGuard = (value: T, index: number, collection: List) => value is S; // Note: key should be string, not keyof T, because the actual object may contain extra properties that were not specified in the type. type ObjectIterator = (value: TObject[keyof TObject], key: string, collection: TObject) => TResult; type ObjectIteratee = ObjectIterator | string | [string, any] | PartialDeep; - type ObjectIterateeBoolean = ObjectIterator | string | [string, any] | PartialDeep; + type ObjectIterateeCustom = ObjectIterator | string | [string, any] | PartialDeep; type ObjectIteratorTypeGuard = (value: TObject[keyof TObject], key: string, collection: TObject) => value is S; type DictionaryIterator = ObjectIterator, TResult>; @@ -17030,7 +17099,7 @@ declare namespace _ { type NumericDictionaryIterator = (value: T, key: number, collection: NumericDictionary) => TResult; type NumericDictionaryIteratee = NumericDictionaryIterator | string | [string, any] | PartialDeep; - type NumericDictionaryIterateeBoolean = NumericDictionaryIterator | string | [string, any] | PartialDeep; + type NumericDictionaryIterateeCustom = NumericDictionaryIterator | string | [string, any] | PartialDeep; type StringIterator = (char: string, index: number, string: string) => TResult; diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index e40569204d..dbefb1abaa 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -4,86 +4,19 @@ interface IFoodOrganic { name: string; organic: boolean; } - -interface IFoodType { - name: string; - type: string; -} - -interface IFoodCombined { - name: string; - organic: boolean; - type: string; -} - -interface IStoogesQuote { - name: string; - quotes: string[]; -} - interface IStoogesAge { name: string; age: number; } -interface IStoogesCombined { - name: string; - age: number; - quotes: string[]; -} - -interface IKey { - dir: string; - code: number; -} - -interface IDictionary { - [index: string]: T; -} - const foodsOrganic: IFoodOrganic[] = [ { name: 'banana', organic: true }, { name: 'beet', organic: false }, ]; -const foodsType: IFoodType[] = [ - { name: 'apple', type: 'fruit' }, - { name: 'banana', type: 'fruit' }, - { name: 'beet', type: 'vegetable' } -]; -const foodsCombined: IFoodCombined[] = [ - { 'name': 'apple', 'organic': false, 'type': 'fruit' }, - { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } -]; - -const stoogesQuotes: IStoogesQuote[] = [ - { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, - { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] } -]; const stoogesAges: IStoogesAge[] = [ { 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 } ]; -const stoogesAgesDict: IDictionary = { - first: { 'name': 'moe', 'age': 40 }, - second: { 'name': 'larry', 'age': 50 } -}; -const stoogesCombined: IStoogesCombined[] = [ - { 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, - { 'name': 'moe', 'age': 40, 'quotes': ['Spread out!', 'You knucklehead!'] } -]; - -const keys: IKey[] = [ - { 'dir': 'left', 'code': 97 }, - { 'dir': 'right', 'code': 100 } -]; - -class Dog { - constructor(public name: string) { } - - bark() { - // Woof - } -} let result: any; @@ -4591,9 +4524,9 @@ namespace TestFilter { let obj: any = {}; let dictionary: _.Dictionary | null | undefined = obj; - let stringIterator: (char: string, index: number, string: string) => any = (char: string, index: number, string: string) => 1; - let listIterator: (value: TResult, index: number, collection: _.List) => any = (value: TResult, index: number, collection: _.List) => 1; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any = (value: TResult, key: string, collection: _.Dictionary) => 1; + let stringIterator = (char: string, index: number, string: string) => true; + let listIterator = (value: TResult, index: number, collection: _.List) => true; + let dictionaryIterator = (value: TResult, key: string, collection: _.Dictionary) => true; { let result: string[]; @@ -5207,7 +5140,7 @@ namespace TestFlatMapDepth { let listIterator: (value: number|number[], index: number, collection: _.List) => _.ListOfRecursiveArraysOrValues = (a, b, c) =>[ 1]; - let dictionaryIterator: (value: number|number[], key: number, collection: _.Dictionary) => _.ListOfRecursiveArraysOrValues = (a, b, c) => [1]; + let dictionaryIterator: (value: number|number[], key: string, collection: _.Dictionary) => _.ListOfRecursiveArraysOrValues = (a, b, c) => [1]; let numericDictionaryIterator: (value: number|number[], key: number, collection: _.NumericDictionary) => _.ListOfRecursiveArraysOrValues = (a, b, c) => [1]; @@ -5776,8 +5709,8 @@ namespace TestGroupBy { { let result: _.Dictionary; - result = _.groupBy(''); - result = _.groupBy('', stringIterator); + result = _.groupBy(''); + result = _.groupBy('', stringIterator); } { @@ -5909,16 +5842,16 @@ namespace TestKeyBy { let dictionary: _.Dictionary | null | undefined = obj; let numericDictionary: _.NumericDictionary | null | undefined = obj; - let stringIterator: (value: string, index: number, collection: string) => any = (value: string, index: number, collection: string) => 1; - let listIterator: (value: SampleObject, index: number, collection: _.List) => any = (value: SampleObject, index: number, collection: _.List) => 1; - let dictionaryIterator: (value: SampleObject, key: string, collection: _.Dictionary) => any = (value: SampleObject, key: string, collection: _.Dictionary) => 1; - let numericDictionaryIterator: (value: SampleObject, key: number, collection: _.NumericDictionary) => any = (value: SampleObject, key: number, collection: _.NumericDictionary) => 1; + let stringIterator = (value: string, index: number, collection: string) => "a"; + let listIterator = (value: SampleObject, index: number, collection: _.List) => 1; + let dictionaryIterator = (value: SampleObject, key: string, collection: _.Dictionary) => Symbol.name; + let numericDictionaryIterator = (value: SampleObject, key: number, collection: _.NumericDictionary) => "a"; { let result: _.Dictionary; - result = _.keyBy('abcd'); - result = _.keyBy('abcd', stringIterator); + result = _.keyBy('abcd'); + result = _.keyBy('abcd', stringIterator); } { @@ -6464,9 +6397,9 @@ namespace TestReject { let obj: any = {}; let dictionary: _.Dictionary | null | undefined = obj; - let stringIterator: (char: string, index: number, string: string) => any = (char: string, index: number, string: string) => 1; - let listIterator: (value: TResult, index: number, collection: _.List) => any = (value: TResult, index: number, collection: _.List) => 1; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any = (value: TResult, key: string, collection: _.Dictionary) => 1; + let stringIterator = (char: string, index: number, string: string) => true; + let listIterator = (value: TResult, index: number, collection: _.List) => true; + let dictionaryIterator = (value: TResult, key: string, collection: _.Dictionary) => true; { let result: string[]; @@ -8667,9 +8600,7 @@ namespace TestIsEqual { // _.isEqualWith namespace TestIsEqualWith { - let customizer = (value: any, other: any, indexOrKey: number|string|undefined, parent: any, otherParent: any, stack: any) => { - return value ? undefined : true; - }; + let customizer = (value: any, other: any, indexOrKey: number|string|symbol|undefined, parent: any, otherParent: any, stack: any) => true; { let result: boolean; @@ -8873,7 +8804,7 @@ namespace TestIsMatch { // _.isMatchWith namespace TestIsMatchWith { - let testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string) => true; + let testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string|symbol) => true; let result: boolean; @@ -11890,7 +11821,7 @@ namespace TestPick { { let result: Pick; result = _.pick(obj, 'a', 'b'); - result = _.pick(obj, ['a', 'b']); + result = _.pick(obj, ['a' as 'a', 'b' as 'b']); } { @@ -11901,6 +11832,13 @@ namespace TestPick { result = _(obj).pick(['b', 1], 0, 'a'); } + { + let result: _.LoDashImplicitWrapper>; + + result = _(obj).pick('a', 'b'); + result = _(obj).pick(['a' as 'a', 'b' as 'b']); + } + { let result: _.LoDashExplicitWrapper>; @@ -11908,6 +11846,13 @@ namespace TestPick { result = _(obj).chain().pick(0, 'a'); result = _(obj).chain().pick(['b', 1], 0, 'a'); } + + { + let result: _.LoDashExplicitWrapper>; + + result = _(obj).chain().pick('a', 'b'); + result = _(obj).chain().pick(['a' as 'a', 'b' as 'b']); + } } // _.pickBy diff --git a/types/lodash/tsconfig.json b/types/lodash/tsconfig.json index 2c4aa57c54..8bd56c0b87 100644 --- a/types/lodash/tsconfig.json +++ b/types/lodash/tsconfig.json @@ -7,7 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/lolex/index.d.ts b/types/lolex/index.d.ts index c0dec4cd56..68f87793d9 100644 --- a/types/lolex/index.d.ts +++ b/types/lolex/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for lolex 1.5 +// Type definitions for lolex 2.1 // Project: https://github.com/sinonjs/lolex -// Definitions by: Wim Looman , Josh Goldberg +// Definitions by: Wim Looman +// Josh Goldberg +// Rogier Schouten // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** @@ -34,7 +36,7 @@ type BrowserClock = LolexClock; type NodeClock = LolexClock & { /** * Mimicks process.hrtime(). - * + * * @param prevTime Previous system time to calculate time elapsed. * @returns High resolution real time as [seconds, nanoseconds]. */ @@ -49,7 +51,7 @@ type Clock = BrowserClock | NodeClock; /** * Names of clock methods that may be faked by install. */ -type FakeMethod = "setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date"; +type FakeMethod = "setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date" | "nextTick" | "hrtime"; /** * Controls the flow of time. @@ -67,7 +69,7 @@ export interface LolexClock { /** * Schedules a callback to be fired once timeout milliseconds have ticked by. - * + * * @param callback Callback to be fired. * @param timeout How many ticks to wait to run the callback. * @param args Any extra arguments to pass to the callback. @@ -77,14 +79,14 @@ export interface LolexClock { /** * Clears a timer, as long as it was created using setTimeout. - * + * * @param id Timer ID or object. */ clearTimeout(id: TTimerId): void; /** * Schedules a callback to be fired every time timeout milliseconds have ticked by. - * + * * @param callback Callback to be fired. * @param timeout How many ticks to wait between callbacks. * @param args Any extra arguments to pass to the callback. @@ -94,14 +96,14 @@ export interface LolexClock { /** * Clears a timer, as long as it was created using setInterval. - * + * * @param id Timer ID or object. */ clearInterval(id: TTimerId): void; /** * Schedules the callback to be fired once 0 milliseconds have ticked by. - * + * * @param callback Callback to be fired. * @remarks You'll still have to call clock.tick() for the callback to fire. * @remarks If called during a tick the callback won't fire until 1 millisecond has ticked by. @@ -110,11 +112,16 @@ export interface LolexClock { /** * Clears a timer, as long as it was created using setImmediate. - * + * * @param id Timer ID or object. */ clearImmediate(id: TTimerId): void; + /** + * Simulates process.nextTick(); + */ + nextTick(callback: () => void): void; + /** * Advances the clock to the the moment of the first scheduled timer, firing it. */ @@ -122,14 +129,14 @@ export interface LolexClock { /** * Advance the clock, firing callbacks if necessary. - * + * * @param time How many ticks to advance by. */ tick(time: number | string): void; /** * Runs all pending timers until there are none remaining. - * + * * @remarks If new timers are added while it is executing they will be run as well. */ runAll(): void; @@ -142,7 +149,7 @@ export interface LolexClock { /** * Simulates a user changing the system clock. - * + * * @param now New system time. * @remarks This affects the current time but it does not in itself cause timers to fire. */ @@ -157,7 +164,7 @@ export interface LolexClock { /** * Creates a clock. - * + * * @param now Current time for the clock. * @param loopLimit Maximum number of timers that will be run when calling runAll() * before assuming that we have an infinite loop and throwing an error @@ -167,23 +174,47 @@ export interface LolexClock { */ export declare function createClock(now?: number | Date, loopLimit?: number): TClock; -/** - * Creates a clock and installs it globally. - * - * @param now Current time for the clock, as with lolex.createClock(). - * @param toFake Names of methods that should be faked. - * @type TClock Type of clock to create. - * @usage lolex.install(["setTimeout", "clearTimeout"]); - */ -export declare function install(now?: number | Date, toFake?: FakeMethod[]): TClock; + +export interface LolexInstallOpts { + /** + * Installs lolex onto the specified target context (default: global) + */ + target?: any; + + /** + * Installs lolex with the specified unix epoch (default: 0) + */ + now?: number; + + /** + * An array with explicit function names to hijack. When not set, lolex will automatically fake all methods except nextTick + * e.g., lolex.install({ toFake: ["setTimeout", "nextTick"]}) will fake only setTimeout and nextTick + */ + toFake?: FakeMethod[]; + + /** + * The maximum number of timers that will be run when calling runAll() (default: 1000) + */ + loopLimit?: number; + + /** + * Tells lolex to increment mocked time automatically based on the real system time shift (e.g. the mocked time will be incremented by + * 20ms for every 20ms change in the real system time) (default: false) + */ + shouldAdvanceTime?: boolean; + + /** + * Relevant only when using with shouldAdvanceTime: true. increment mocked time by advanceTimeDelta ms every advanceTimeDelta ms change + * in the real system time (default: 20) + */ + advanceTimeDelta?: number; +} /** - * Creates a clock and installs it onto the context object. - * - * @param context Context to install the clock onto. + * Creates a clock and installs it globally. + * * @param now Current time for the clock, as with lolex.createClock(). * @param toFake Names of methods that should be faked. * @type TClock Type of clock to create. - * @usage lolex.install(context, ["setTimeout", "clearTimeout"]); */ -export declare function install(context?: any, now?: number | Date, toFake?: FakeMethod[]): TClock; +export declare function install(opts?: LolexInstallOpts): TClock; diff --git a/types/lolex/lolex-tests.ts b/types/lolex/lolex-tests.ts index 876e4280c5..95b6a2be78 100644 --- a/types/lolex/lolex-tests.ts +++ b/types/lolex/lolex-tests.ts @@ -16,25 +16,14 @@ lolex.createClock(new Date()); lolex.createClock(7, 9001); lolex.createClock(new Date(), 9001); -lolex.install(7); -lolex.install(new Date()); -lolex.install(7, ["setTimeout"]); -lolex.install(new Date(), ["setTimeout"]); - -lolex.install(7); -lolex.install(new Date()); -lolex.install(7, ["setTimeout"]); -lolex.install(new Date(), ["setTimeout"]); - -lolex.install({}, 7); -lolex.install({}, new Date()); -lolex.install({}, 7, ["setTimeout"]); -lolex.install({}, new Date(), ["setTimeout"]); - -lolex.install({}, 7); -lolex.install({}, new Date()); -lolex.install({}, 7, ["setTimeout"]); -lolex.install({}, new Date(), ["setTimeout"]); +lolex.install({ + advanceTimeDelta: 20, + loopLimit: 10, + now: 0, + shouldAdvanceTime: true, + target: {}, + toFake: ["setTimeout", "nextTick", "hrtime"] +}); const browserNow: number = browserClock.now; const browserDate: Date = new browserClock.Date(); @@ -80,5 +69,7 @@ nodeClock.setSystemTime(); nodeClock.setSystemTime(7); nodeClock.setSystemTime(new Date()); +nodeClock.nextTick(() => undefined); + browserClock.uninstall(); nodeClock.uninstall(); diff --git a/types/lozad/index.d.ts b/types/lozad/index.d.ts index eb0213f6c3..6257c47043 100644 --- a/types/lozad/index.d.ts +++ b/types/lozad/index.d.ts @@ -1,25 +1,25 @@ -// Type definitions for lozad 1.0 +// Type definitions for lozad 1.1 // Project: https://github.com/ApoorvSaxena/lozad.js // Definitions by: York Yao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface Option { - rootMargin?: string; - threshold?: number; - load?(element: HTMLElement | HTMLCanvasElement): void; -} - -interface Observer { - observe(): void; -} - -declare function lozad(selector?: string, options?: Option): Observer; - declare namespace lozad { + interface Option { + rootMargin?: string; + threshold?: number; + load?(element: HTMLElement | HTMLCanvasElement): void; + } + + interface Observer { + observe(): void; + } + const prototype: { }; } +declare function lozad(selector?: string, options?: lozad.Option): lozad.Observer; + export as namespace lozad; export = lozad; diff --git a/types/lusca/index.d.ts b/types/lusca/index.d.ts new file mode 100644 index 0000000000..8527ef3411 --- /dev/null +++ b/types/lusca/index.d.ts @@ -0,0 +1,78 @@ +// Type definitions for lusca 1.5 +// Project: https://github.com/krakenjs/lusca#readme +// Definitions by: Corbin Crutchley +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import express = require('express'); + +declare function lusca(options?: lusca.LuscaOptions): express.RequestHandler; + +declare namespace lusca { + /*~ Documentation declares that: + *~ Setting any value to false will disable it. + */ + interface LuscaOptions { + csrf?: csrfOptions | boolean; + csp?: cspOptions | false; + xframe?: string | false; + p3p?: string | false; + hsts?: hstsOptions | false; + xssProtection?: xssProtectionOptions | boolean; + nosniff?: boolean; + referrerPolicy?: string | false; + } + + interface cspOptions { + policy?: string | object | Array; + reportOnly?: boolean; + reportUri?: string; + styleNonce?: boolean; + scriptNonce?: boolean; + } + + interface hstsOptions { + maxAge?: number; + includeSubDomains?: boolean; + preload?: boolean; + } + + type csrfOptions = csrfOptionsAngular | csrfOptionsNonAngular; + + interface csrfOptionsAngular { + key?: string; + secret?: string; + impl?: () => any; + cookie?: string | { + options?: object; + }; + angular: true; + } + + interface csrfOptionsNonAngular { + key?: string; + secret?: string; + impl?: () => any; + cookie?: string | { + name: string; + options?: object; + }; + angular?: false; + } + + interface xssProtectionOptions { + enabled?: boolean; + mode?: string; + } + + function csrf(options?: csrfOptions): express.RequestHandler; + function csp(options?: cspOptions): express.RequestHandler; + function xframe(value: string): express.RequestHandler; + function p3p(value: string): express.RequestHandler; + function hsts(options?: hstsOptions): express.RequestHandler; + function xssProtection(options?: xssProtectionOptions | true): express.RequestHandler; + function nosniff(): express.RequestHandler; + function referrerPolicy(value: string): express.RequestHandler; +} + +export = lusca; diff --git a/types/lusca/lusca-tests.ts b/types/lusca/lusca-tests.ts new file mode 100644 index 0000000000..8a74ec5e8a --- /dev/null +++ b/types/lusca/lusca-tests.ts @@ -0,0 +1,24 @@ +import express = require('express'); +import lusca = require('lusca'); + +const app = express(); + +app.use(lusca({ + csrf: true, + csp: { policy: "referrer no-referrer"}, + xframe: 'SAMEORIGIN', + p3p: 'ABCDEF', + hsts: {maxAge: 31536000, includeSubDomains: true, preload: true}, + xssProtection: true, + nosniff: true, + referrerPolicy: 'same-origin' +})); + +app.use(lusca.csrf()); +app.use(lusca.csp({policy: [{ "img-src": "'self' http:" }, "block-all-mixed-content"], reportOnly: false})); +app.use(lusca.xframe('SAMEORIGIN')); +app.use(lusca.p3p('ABCDEF')); +app.use(lusca.hsts({ maxAge: 31536000 })); +app.use(lusca.xssProtection(true)); +app.use(lusca.nosniff()); +app.use(lusca.referrerPolicy('same-origin')); diff --git a/types/lusca/tsconfig.json b/types/lusca/tsconfig.json new file mode 100644 index 0000000000..ede7926c1c --- /dev/null +++ b/types/lusca/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "lusca-tests.ts" + ] +} diff --git a/types/lusca/tslint.json b/types/lusca/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/lusca/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 6be9a465ef..ddaafced3d 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mapbox GL JS v0.40.1 +// Type definitions for Mapbox GL JS v0.41.0 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer , Patrick Reames // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -901,7 +901,7 @@ declare namespace mapboxgl { export interface Layer { id: string; - type?: "fill" | "line" | "symbol" | "circle" | "fill-extrusion" | "raster" | "background"; + type?: "fill" | "line" | "symbol" | "circle" | "fill-extrusion" | "raster" | "background" | "heatmap"; metadata?: any; ref?: string; diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index 22b5d1711f..5ae63560cc 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -1440,6 +1440,7 @@ declare namespace __MaterialUI { hintText?: React.ReactNode; iconStyle?: React.CSSProperties; id?: string; + name?: string; labelStyle?: React.CSSProperties; multiple?: boolean; onBlur?: React.FocusEventHandler<{}>; diff --git a/types/mixpanel/index.d.ts b/types/mixpanel/index.d.ts index 4964a55c79..08bbe26720 100644 --- a/types/mixpanel/index.d.ts +++ b/types/mixpanel/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mixpanel 2.13 +// Type definitions for Mixpanel 2.14 // Project: https://mixpanel.com/ // https://github.com/mixpanel/mixpanel-js // Definitions by: Knut Eirik Leira Hjelle @@ -348,6 +348,21 @@ declare namespace Mixpanel { set_once(prop: string, value: any, callback?: () => void): void; set_once(keys: { [index: string]: any }, callback?: () => void): void; + /** + * Unset properties on a user record (permanently removes the properties and their values from a profile). + * + * ### Usage: + * + * mixpanel.people.unset('gender'); + * + * // or unset multiple properties at once + * mixpanel.people.unset(['gender', 'Company']); + * + * @param prop If a string, this is the name of the property. If an array, this is a list of property names. + * @param callback If provided, the callback will be called after the tracking event + */ + unset(prop: string | string[], callback?: () => void): void; + /** * Increment/decrement numeric people analytics properties. * diff --git a/types/mixpanel/mixpanel-tests.ts b/types/mixpanel/mixpanel-tests.ts index b1d735c22e..a48cd4065a 100644 --- a/types/mixpanel/mixpanel-tests.ts +++ b/types/mixpanel/mixpanel-tests.ts @@ -95,6 +95,11 @@ function mixpanel_people() { 'Starting Plan': 'Premium' }, () => {}); + mixpanel.people.unset('Company'); + mixpanel.people.unset('Company', () => {}); + mixpanel.people.unset(['Company', 'Plan']); + mixpanel.people.unset(['Company', 'Plan'], () => {}); + mixpanel.people.increment('page_views'); mixpanel.people.increment('page_views', 1); mixpanel.people.increment('credits_left', -1); diff --git a/types/mobx-apollo/index.d.ts b/types/mobx-apollo/index.d.ts new file mode 100644 index 0000000000..54818cd846 --- /dev/null +++ b/types/mobx-apollo/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for mobx-apollo 0.0 +// Project: https://github.com/sonaye/mobx-apollo#readme +// Definitions by: Paul Selden +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { + ApolloClient, + ObservableQuery, + WatchQueryOptions, + ApolloError +} from 'apollo-client'; + +export interface MobxApolloQueryOptions extends WatchQueryOptions { + client: ApolloClient; + onFetch?: (result: T) => void; + onError?: (error: ApolloError) => void; +} + +export interface MobxApolloQuery { + loading: boolean; + data?: T; + error?: ApolloError; + ref: ObservableQuery; +} + +export default function graphql( + options: MobxApolloQueryOptions +): MobxApolloQuery; diff --git a/types/mobx-apollo/mobx-apollo-tests.ts b/types/mobx-apollo/mobx-apollo-tests.ts new file mode 100644 index 0000000000..50d6b03abb --- /dev/null +++ b/types/mobx-apollo/mobx-apollo-tests.ts @@ -0,0 +1,34 @@ +import { ApolloClient } from 'apollo-client'; +import query from 'mobx-apollo'; + +const PostsQuery = ` + { + posts { + id + title + } + } +` as any; + +interface Post { + id: string; + title: string; +} + +class PostStore { + private get postsQuery() { + return query<{ posts: Post[] }>({ + client: new ApolloClient({ + link: {} as any, + cache: {} as any + }), + query: PostsQuery + }); + } + + get posts() { + return this.postsQuery.data && this.postsQuery.data.posts; + } +} + +new PostStore(); diff --git a/types/mobx-apollo/package.json b/types/mobx-apollo/package.json new file mode 100644 index 0000000000..da0ffc3953 --- /dev/null +++ b/types/mobx-apollo/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "apollo-client": "^2.0.0" + } +} diff --git a/types/mobx-apollo/tsconfig.json b/types/mobx-apollo/tsconfig.json new file mode 100644 index 0000000000..c4c2acace4 --- /dev/null +++ b/types/mobx-apollo/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "target": "es5", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "mobx-apollo-tests.ts"] +} diff --git a/types/mobx-apollo/tslint.json b/types/mobx-apollo/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mobx-apollo/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mock-require/index.d.ts b/types/mock-require/index.d.ts index da5db1c07c..75076ec739 100644 --- a/types/mock-require/index.d.ts +++ b/types/mock-require/index.d.ts @@ -1,31 +1,21 @@ -// Type definitions for mock-require v1.3.0 +// Type definitions for mock-require 2.0 // Project: https://github.com/boblauer/mock-require -// Definitions by: Daniel Pereira +// Definitions by: Giorgio Delgado // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 /// -/** Simple, intuitive mocking of Node.js modules. */ +type StubFunction = (...params: any[]) => any; +type Stub = object | StubFunction; + interface Mock { - /** - * @param {string} path The module you that you want to mock. - * @param {any} mockExport The function or object you want to be returned from require, instead of the path module's exports, or the module you want to be returned from require, instead of the path module's export. - */ - (path: string, mockExport: any | Function | string): void; - - /** - * @param {string} path The module you that you want to stop mocking. - */ + (path: string, mockExport: string | Stub): void; stop(path: string): void; - - /** This function can be used to remove all registered mocks without the need to remove them individually using mock.stop(). */ stopAll(): void; - - /** - * @param {string} path The file whose cache you want to refresh. - */ - reRequire(path: string): void; + reRequire(path: string): any; } -declare const myModule: Mock; -export = myModule; +declare var mock: Mock; + +export = mock; diff --git a/types/mock-require/mock-require-tests.ts b/types/mock-require/mock-require-tests.ts index 41052e2afc..2131bc56de 100644 --- a/types/mock-require/mock-require-tests.ts +++ b/types/mock-require/mock-require-tests.ts @@ -1,10 +1,12 @@ import mock = require('mock-require'); +const request = () => { + console.log('http.request called'); +}; + function testMock() { mock('http', { - request: function () { - console.log('http.request called'); - } + request }); const http = require('http'); @@ -42,4 +44,4 @@ function testReRequire() { let fileToTest = require('./fileToTest'); mock('fs', {}); // fileToTest is still using the unmocked fs module fileToTest = mock.reRequire('./fileToTest'); // fileToTest is now using your mock -} \ No newline at end of file +} diff --git a/types/mock-require/tsconfig.json b/types/mock-require/tsconfig.json index 2f5ec713da..1f6be404c6 100644 --- a/types/mock-require/tsconfig.json +++ b/types/mock-require/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/moment-timezone/index.d.ts b/types/moment-timezone/index.d.ts index a839b093c4..ca62b3cb82 100644 --- a/types/moment-timezone/index.d.ts +++ b/types/moment-timezone/index.d.ts @@ -18,6 +18,7 @@ declare module "moment" { abbr(timestamp: number): string; offset(timestamp: number): number; + utcOffset(timestamp: number): number; parse(timestamp: number): number; } diff --git a/types/moment-timezone/moment-timezone-tests.ts b/types/moment-timezone/moment-timezone-tests.ts index 9e3e720d24..14df62915b 100644 --- a/types/moment-timezone/moment-timezone-tests.ts +++ b/types/moment-timezone/moment-timezone-tests.ts @@ -49,7 +49,7 @@ moment.tz(mo, "America/Los_Angeles"); moment.tz(obj, "America/Los_Angeles"); moment.tz.zone('America/Los_Angeles').abbr(1403465838805); -moment.tz.zone('America/Los_Angeles').offset(1403465838805); +moment.tz.zone('America/Los_Angeles').utcOffset(1403465838805); const zone = moment.tz.zone('America/New_York'); zone.parse(Date.UTC(2012, 2, 19, 8, 30)); // 240 diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 19cf0136e2..32bc523d38 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -5,6 +5,7 @@ // Gady Piazza // Jason Dreyzehner // Gaurav Lahoti +// Mariano Cortesi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -146,6 +147,9 @@ export interface DbCreateOptions { promiseLibrary?: Object; // https://docs.mongodb.com/manual/reference/read-concern/#read-concern readConcern?: { level?: Object }; + // Sets a cap on how many operations the driver will buffer up before giving up on getting a + // working connection, default is -1 which is unlimited. + bufferMaxEntries?: number; } // http://mongodb.github.io/node-mongodb-native/2.2/api/Server.html diff --git a/types/mongodb/mongodb-tests.ts b/types/mongodb/mongodb-tests.ts index 2b8c49d186..52f2d6e4f8 100644 --- a/types/mongodb/mongodb-tests.ts +++ b/types/mongodb/mongodb-tests.ts @@ -3,7 +3,7 @@ import mongodb = require('mongodb'); var MongoClient = mongodb.MongoClient; var format = require('util').format; -let options = { +let options: mongodb.MongoClientOptions = { authSource : ' ', w : 1, wtimeout : 300, diff --git a/types/moxios/index.d.ts b/types/moxios/index.d.ts index b4ca5580fd..b0cc379fef 100644 --- a/types/moxios/index.d.ts +++ b/types/moxios/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Asuka Ito // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import { AxiosInstance } from "axios"; +import { AxiosInstance, AxiosRequestConfig } from "axios"; interface Item { response?: any; @@ -75,7 +75,14 @@ declare class Request { * @param reject The function to call when Promise is rejected * @param config The config object to be used for the request */ - constructor(resolve: (arg: any) => void, reject: (arg: any) => void, config: any); + constructor(resolve: (arg: any) => void, reject: (arg: any) => void, config: AxiosRequestConfig); + + config: AxiosRequestConfig; + headers: any; + url: string; + timeout: number; + withCredentials: boolean; + responseType: string; /** * Respond to this request with a timeout result @@ -102,12 +109,13 @@ declare class Response { */ constructor(req: Request, res: any); - config: any; + config: AxiosRequestConfig; data?: any; status?: number; statusText?: string; headers: any; request: Request; + code?: string; } declare let moxios: { diff --git a/types/multistream/index.d.ts b/types/multistream/index.d.ts new file mode 100644 index 0000000000..7a7d0eb309 --- /dev/null +++ b/types/multistream/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for multistream 2.1 +// Project: https://github.com/feross/multistream +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Stream } from 'stream'; + +declare function multistream(streams: multistream.Streams): NodeJS.ReadableStream; + +declare namespace multistream { + type LazyStream = () => Stream; + type FactoryStream = (cb: (err: Error | null, stream: NodeJS.ReadableStream) => any) => void; + type Streams = Array | FactoryStream; + + function obj(streams: Streams): NodeJS.ReadableStream; +} + +export = multistream; diff --git a/types/multistream/multistream-tests.ts b/types/multistream/multistream-tests.ts new file mode 100644 index 0000000000..99206e0102 --- /dev/null +++ b/types/multistream/multistream-tests.ts @@ -0,0 +1,40 @@ +import fs = require('fs'); +import stream = require('stream'); + +import through = require('through'); +import through2 = require('through2'); +import multistream = require('multistream'); + +const readable = new stream.Readable(); +const writable = new stream.Writable(); +const transform = new stream.Transform(); +const duplex = new stream.Duplex(); +const pass = new stream.PassThrough(); + +const streams = [ + readable, + transform, + duplex, + pass, + through(), + through2(), + fs.createReadStream('.filepath'), + () => fs.createWriteStream('.filepath2') +]; + +const factory: multistream.FactoryStream = (cb) => { + if (1 === 1) return cb(null, fs.createReadStream('.filepath')); + + cb(null, fs.createReadStream('.filepath')); +}; + +// $ExpectType ReadableStream +multistream(streams); +multistream(factory); + +// $ExpectType ReadableStream +multistream.obj(streams); +multistream.obj(factory); + +// $ExpectError +multistream([writable]); diff --git a/types/multistream/tsconfig.json b/types/multistream/tsconfig.json new file mode 100644 index 0000000000..3fa5cc7c47 --- /dev/null +++ b/types/multistream/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "multistream-tests.ts" + ] +} diff --git a/types/multistream/tslint.json b/types/multistream/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/multistream/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mysql/index.d.ts b/types/mysql/index.d.ts index 7260dc2e85..7d3281218f 100644 --- a/types/mysql/index.d.ts +++ b/types/mysql/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mysqljs/mysql // Definitions by: William Johnston // Kacper Polak +// Krittanan Pingclasai // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -422,7 +423,7 @@ export interface ConnectionConfig extends ConnectionOptions { /** * object with ssl parameters or a string containing name of ssl profile */ - ssl?: tls.SecureContextOptions & { rejectUnauthorized?: boolean }; + ssl?: string | (tls.SecureContextOptions & { rejectUnauthorized?: boolean }); } export interface PoolConfig extends ConnectionConfig { diff --git a/types/mysql/mysql-tests.ts b/types/mysql/mysql-tests.ts index a708aa6163..a3ddb27248 100644 --- a/types/mysql/mysql-tests.ts +++ b/types/mysql/mysql-tests.ts @@ -39,6 +39,11 @@ connection.query('SELECT 1', (err, rows) => { // connected! (unless `err` is set) }); +connection = mysql.createConnection({ + host: 'localhost', + ssl: 'Amazon RDS' +}); + connection = mysql.createConnection({ host: 'localhost', ssl: { diff --git a/types/nconf/index.d.ts b/types/nconf/index.d.ts index ff72f3e568..f03eb88b39 100644 --- a/types/nconf/index.d.ts +++ b/types/nconf/index.d.ts @@ -69,7 +69,7 @@ export interface ICallbackFunction { } export declare class Provider { - constructor(options: IOptions); + constructor(options?: IOptions); stores: any; sources: any[]; diff --git a/types/negotiator/index.d.ts b/types/negotiator/index.d.ts index c4d713ac5c..5f665331e3 100644 --- a/types/negotiator/index.d.ts +++ b/types/negotiator/index.d.ts @@ -78,6 +78,6 @@ declare class Negotiator { declare namespace Negotiator { interface Headers { - [key: string]: string | string[]; + [key: string]: string | string[] | undefined; } } diff --git a/types/next/router.d.ts b/types/next/router.d.ts index a1d58bb42a..9f937ca6ba 100644 --- a/types/next/router.d.ts +++ b/types/next/router.d.ts @@ -35,5 +35,7 @@ export interface SingletonRouter { onRouteChangeError?(error: any, url: string): void; } +export function withRouter(Component: React.ComponentType): React.ComponentType; + export const Singleton: SingletonRouter; export default Singleton; diff --git a/types/next/test/next-router-tests.tsx b/types/next/test/next-router-tests.tsx index 37e739d98a..e713f127b7 100644 --- a/types/next/test/next-router-tests.tsx +++ b/types/next/test/next-router-tests.tsx @@ -51,3 +51,5 @@ Router.replace('/route', '/asRoute', {shallow: false}).then((success: boolean) = Router.prefetch('/route').then(Component => { const element = (); }); + +r.withRouter(props =>
); diff --git a/types/nightwatch/index.d.ts b/types/nightwatch/index.d.ts index 3a7e81d0fa..a32a07b3dd 100644 --- a/types/nightwatch/index.d.ts +++ b/types/nightwatch/index.d.ts @@ -4,8 +4,6 @@ // Connor Schlesiger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/* tslint:disable:max-line-length */ - export interface NightwatchCustomPageObjects { page: {}; } @@ -887,7 +885,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The value of the attribute */ - getAttribute(selector: string, attribute: string, callback?: (result: NightwatchCallbackResult) => void): this; + getAttribute(selector: string, attribute: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Retrieve a single cookie visible to the current page. The cookie is returned as a cookie JSON object, as defined here. @@ -906,7 +904,7 @@ export interface NightwatchAPI { * @param callback: The callback function which will receive the response as an argument. * @returns The cookie object as a selenium cookie JSON object or null if the cookie wasn't found. */ - getCookie(name: string, callback?: (result: NightwatchCallbackResult) => void): this; + getCookie(name: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Retrieve all cookies visible to the current page. The cookies are returned as an array of cookie JSON object, @@ -924,7 +922,7 @@ export interface NightwatchAPI { * @param callback: The callback function which will receive the response as an argument. * @returns A list of cookies */ - getCookies(callback?: (result: NightwatchCallbackResult) => void): this; + getCookies(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Retrieve the value of a css property for a given DOM element. Uses elementIdCssProperty protocol command. @@ -944,7 +942,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The value of the css property */ - getCssProperty(selector: string, cssProperty: string, callback?: (result: NightwatchCallbackResult) => void): this; + getCssProperty(selector: string, cssProperty: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Determine an element's size in pixels. Uses elementIdSize protocol command. @@ -964,7 +962,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The width and height of the element in pixels */ - getElementSize(selector: string, callback?: (result: NightwatchCallbackResult) => void): this; + getElementSize(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Determine an element's location on the page. The point (0, 0) refers to the upper-left corner of the page. @@ -985,7 +983,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The X and Y coordinates for the element on the page */ - getLocation(selector: string, callback?: (result: NightwatchCallbackResult) => void): this; + getLocation(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Determine an element's location on the screen once it has been scrolled into view. Uses elementIdLocationInView protocol command. @@ -1005,7 +1003,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The X and Y coordinates for the element on the page. */ - getLocationInView(selector: string, callback?: (result: NightwatchCallbackResult) => void): this; + getLocationInView(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Gets a log from selenium @@ -1059,7 +1057,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The element's tag name, as a lowercase string. */ - getTagName(selector: string, callback?: (result: NightwatchCallbackResult) => void): this; + getTagName(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Returns the visible text for the element. Uses elementIdText protocol command. @@ -1078,7 +1076,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The element's visible text. */ - getText(selector: string, callback?: (result: NightwatchCallbackResult) => void): this; + getText(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Returns the title of the current page. Uses title protocol command. @@ -1095,7 +1093,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The page title. */ - getTitle(callback?: (result: NightwatchCallbackResult) => void): this; + getTitle(callback?: (this: NightwatchAPI, result?: string) => void): this; /** * Returns a form element current value. Uses elementIdValue protocol command. @@ -1114,7 +1112,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The element's value. */ - getValue(selector: string, callback?: (result: NightwatchCallbackResult) => void): this; + getValue(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * This command is an alias to url and also a convenience method when called without any arguments in the sense that it performs a call to .url() with passing the value of launch_url @@ -1180,7 +1178,7 @@ export interface NightwatchAPI { * @param selector: The CSS/Xpath selector used to locate the element. * @param callback: Optional callback function to be called when the command finishes. */ - isVisible(selector: string, callback?: (result: NightwatchCallbackResult) => void): this; + isVisible(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Maximizes the current window. @@ -1559,7 +1557,9 @@ export interface NightwatchAPI { * ``` * @param selector: The selector (CSS / Xpath) used to locate the element. * @param time: The number of milliseconds to wait. The runner performs repeated checks every 500 ms. - * @param abortOnFailure: By the default if the element is not found the test will fail. Set this to false if you wish for the test to continue even if the assertion fails. To set this globally you can define a property `abortOnNightwatchAssertionsFailure` in your globals. + * @param abortOnFailure: By the default if the element is not found the test will fail. + * Set this to false if you wish for the test to continue even if the assertion fails. + * To set this globally you can define a property `abortOnNightwatchAssertionsFailure` in your globals. * @param callback: Optional callback function to be called when the command finishes. * @param message: Optional message to be shown in the output; the message supports two placeholders: %s for current selector and %d for the time (e.g. Element %s was not in the page for %d ms). */ @@ -1847,7 +1847,8 @@ export interface NightwatchAPI { /** * Send a sequence of key strokes to the active element. The sequence is defined in the same format as the sendKeys command. * An object map with available keys and their respective UTF-8 characters, as defined on W3C WebDriver draft spec, is loaded onto the main Nightwatch instance as client.Keys. - * Rather than the setValue, the modifiers are not released at the end of the call. The state of the modifier keys is kept between calls, so mouse interactions can be performed while modifier keys are depressed. + * Rather than the setValue, the modifiers are not released at the end of the call. + * The state of the modifier keys is kept between calls, so mouse interactions can be performed while modifier keys are depressed. * @param keysToSend: The keys sequence to be sent. * @param callback: Optional callback function to be called when the command finishes. */ @@ -1862,8 +1863,10 @@ export interface NightwatchAPI { mouseButtonClick(button: string, callback?: () => void): this; /** - * Click and hold the left mouse button (at the coordinates set by the last moveto command). Note that the next mouse-related command that should follow is mouseButtonUp . Any other mouse command (such as click or another call to buttondown) will yield undefined behaviour. - * Can be used for implementing drag-and-drop. The button can be (0, 1, 2) or ('left', 'middle', 'right'). It defaults to left mouse button, and if you don't pass in a button but do pass in a callback, it will handle it correctly. + * Click and hold the left mouse button (at the coordinates set by the last moveto command). Note that the next mouse-related command that should follow is mouseButtonUp . + * Any other mouse command (such as click or another call to buttondown) will yield undefined behaviour. + * Can be used for implementing drag-and-drop. The button can be (0, 1, 2) or ('left', 'middle', 'right'). + * It defaults to left mouse button, and if you don't pass in a button but do pass in a callback, it will handle it correctly. * @param button: The mouse button * @param callback: Optional callback function to be called when the command finishes. */ @@ -1871,14 +1874,16 @@ export interface NightwatchAPI { /** * Releases the mouse button previously held (where the mouse is currently at). Must be called once for every mouseButtonDown command issued. - * Can be used for implementing drag-and-drop. The button can be (0, 1, 2) or ('left', 'middle', 'right'). It defaults to left mouse button, and if you don't pass in a button but do pass in a callback, it will handle it correctly. + * Can be used for implementing drag-and-drop. The button can be (0, 1, 2) or ('left', 'middle', 'right'). + * It defaults to left mouse button, and if you don't pass in a button but do pass in a callback, it will handle it correctly. * @param button: The mouse button * @param callback: Optional callback function to be called when the command finishes. */ mouseButtonUp(button: string, callback?: () => void): this; /** - * Move the mouse by an offset of the specificed element. If no element is specified, the move is relative to the current mouse cursor. If an element is provided but no offset, the mouse will be moved to the center of the element. + * Move the mouse by an offset of the specificed element. If no element is specified, the move is relative to the current mouse cursor. + * If an element is provided but no offset, the mouse will be moved to the center of the element. * If the element is not visible, it will be scrolled into view. * @param element: Opaque ID assigned to the element to move to. If not specified or is null, the offset is relative to current position of the mouse. * @param xofset: X offset to move to, relative to the top-left corner of the element. If not specified, the mouse will move to the middle of the element. @@ -1997,14 +2002,16 @@ export interface NightwatchAPI { /** * Configure the amount of time that a particular type of operation can execute for before they are aborted and a |Timeout| error is returned to the client. - * @param typeOfOperation: The type of operation to set the timeout for. Valid values are: "script" for script timeouts, "implicit" for modifying the implicit wait timeout and "page load" for setting a page load timeout. + * @param typeOfOperation: The type of operation to set the timeout for. + * Valid values are: "script" for script timeouts, "implicit" for modifying the implicit wait timeout and "page load" for setting a page load timeout. * @param ms: The amount of time, in milliseconds, that time-limited commands are permitted to run. * @param callback: Optional callback function to be called when the command finishes. */ timeouts(typeOfOperation: string, ms: number, callback?: () => void): this; /** - * Set the amount of time, in milliseconds, that asynchronous scripts executed by /session/:sessionId/execute_async are permitted to run before they are aborted and a |Timeout| error is returned to the client. + * Set the amount of time, in milliseconds, that asynchronous scripts executed by /session/:sessionId/execute_async are permitted + * to run before they are aborted and a |Timeout| error is returned to the client. * @param ms: The amount of time, in milliseconds, that time-limited commands are permitted to run. * @param callback: Optional callback function to be called when the command finishes. */ @@ -2087,7 +2094,8 @@ export interface NightwatchAPI { windowMaximize(handleOrName?: string, callback?: () => void): this; /** - * Change or get the position of the specified window. If the second argument is a function it will be used as a callback and the call will perform a get request to retrieve the existing window position. + * Change or get the position of the specified window. If the second argument is a function it will be used as a callback and the call + * will perform a get request to retrieve the existing window position. * @param windowHandle: * @param: offsetX: * @param: offsetY: @@ -2199,5 +2207,3 @@ export interface Nightwatch { api: NightwatchAPI; client: NightwatchClient; } - -/* tslint:enable:max-line-length */ diff --git a/types/nightwatch/nightwatch-tests.ts b/types/nightwatch/nightwatch-tests.ts index a40c8c466a..548dcee9bd 100644 --- a/types/nightwatch/nightwatch-tests.ts +++ b/types/nightwatch/nightwatch-tests.ts @@ -7,6 +7,9 @@ const test: NightwatchTests = { .waitForElementVisible('body', 1000) .setValue('input[type=text]', 'nightwatch') .waitForElementVisible('button[name=btnG]', 1000) + .getTitle(function(result) { + this.assert.equal(typeof result, 'string'); + }) .click('button[name=btnG]') .pause(1000) .assert.containsText('#main', 'Night Watch') diff --git a/types/nightwatch/tslint.json b/types/nightwatch/tslint.json index b1439230db..495d29983d 100644 --- a/types/nightwatch/tslint.json +++ b/types/nightwatch/tslint.json @@ -1,7 +1,5 @@ { "extends": "dtslint/dt.json", "rules": { - // TODO - "no-any-union": false } } diff --git a/types/node-cache/index.d.ts b/types/node-cache/index.d.ts index 558882a086..069bd4fb32 100644 --- a/types/node-cache/index.d.ts +++ b/types/node-cache/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/tcs-de/nodecache // Definitions by: Ilya Mochalov // Daniel Thunell +// Ulf Seltmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -89,8 +90,16 @@ declare namespace NodeCache { ttl( key: Key, - cb?: Callback, - ttl?: number + cb?: Callback + ): boolean; + + getTtl( + key: Key, + ): number|undefined; + + getTtl( + key: Key, + cb?: Callback ): boolean; /** @@ -130,6 +139,7 @@ declare namespace NodeCache { checkperiod?: number; useClones?: boolean; errorOnMissing?: boolean; + deleteOnExpire?: boolean; } interface Stats { @@ -225,7 +235,7 @@ declare class NodeCache extends events.EventEmitter implements NodeCache.NodeCac ): number; /** - * reset or redefine the ttl of a key. If `ttl` is not passed or set to 0 it's similar to `.del()` + * reset or redefine the ttl of a key. If `ttl` is not passed or set to 0 `stdTtl` is used. if set lt 0 it's similar to `.del()` */ ttl( key: Key, @@ -234,9 +244,17 @@ declare class NodeCache extends events.EventEmitter implements NodeCache.NodeCac ): boolean; ttl( + key: Key, + cb?: Callback + ): boolean; + + getTtl( + key: Key + ): number|undefined; + + getTtl( key: Key, cb?: Callback, - ttl?: number ): boolean; /** diff --git a/types/node-cache/node-cache-tests.ts b/types/node-cache/node-cache-tests.ts index 66c2fb4176..ebf1b88688 100644 --- a/types/node-cache/node-cache-tests.ts +++ b/types/node-cache/node-cache-tests.ts @@ -83,7 +83,7 @@ interface TypeSample { result = cache.getStats(); } -/* tslint:disable void-return no-void-expression */ +/* tslint-:disable void-return no-void-expression { let cache: NodeCache; let result: void; @@ -95,4 +95,4 @@ interface TypeSample { let result: void; result = cache.close(); } -/* tslint:enable void-return */ + tslint-:enable void-return */ diff --git a/types/node-zookeeper-client/index.d.ts b/types/node-zookeeper-client/index.d.ts index 0e095cd822..1dcc8eca2a 100644 --- a/types/node-zookeeper-client/index.d.ts +++ b/types/node-zookeeper-client/index.d.ts @@ -172,7 +172,13 @@ export class Exception { code: number; name: string; path?: string; - constructor(code: number, name: string, path?: string); + + // tslint:disable-next-line ban-types + constructor(code: number, name: string, path: string, ctor: Function); + + // tslint:disable-next-line ban-types + constructor(code: number, name: string, ctor: Function); + toString(): string; getCode(): number; getName(): string; diff --git a/types/node-zookeeper-client/node-zookeeper-client-tests.ts b/types/node-zookeeper-client/node-zookeeper-client-tests.ts index 554077e5af..ec8727ae4e 100644 --- a/types/node-zookeeper-client/node-zookeeper-client-tests.ts +++ b/types/node-zookeeper-client/node-zookeeper-client-tests.ts @@ -257,6 +257,6 @@ const client = zookeeper.createClient( } { - new zookeeper.Exception(zookeeper.Exception.NO_NODE, 'test'); - new zookeeper.Exception(zookeeper.Exception.NO_NODE, 'test', '/test'); + new zookeeper.Exception(zookeeper.Exception.NO_NODE, 'test', zookeeper.Exception); + new zookeeper.Exception(zookeeper.Exception.NO_NODE, 'test', '/test', zookeeper.Exception); } diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 188e1315d6..0052b8256e 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -14,6 +14,7 @@ // Kelvin Jin // Alvis HT Tang // Oliver Joseph Ash +// Sebastian Silbermann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************************ @@ -193,8 +194,6 @@ declare var Buffer: { prototype: Buffer; /** * Allocates a new Buffer using an {array} of octets. - * - * @param array */ from(array: any[]): Buffer; /** @@ -204,22 +203,16 @@ declare var Buffer: { * within the {arrayBuffer} that will be shared by the Buffer. * * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length */ from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; /** * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer */ from(buffer: Buffer): Buffer; /** * Creates a new Buffer containing the given JavaScript string {str}. * If provided, the {encoding} parameter identifies the character encoding. * If not provided, {encoding} defaults to 'utf8'. - * - * @param str */ from(str: string, encoding?: string): Buffer; /** @@ -472,11 +465,15 @@ declare namespace NodeJS { exit(code?: number): never; exitCode: number; getgid(): number; - setgid(id: number): void; - setgid(id: string): void; + setgid(id: number | string): void; getuid(): number; - setuid(id: number): void; - setuid(id: string): void; + setuid(id: number | string): void; + geteuid(): number; + seteuid(id: number | string): void; + getegid(): number; + setegid(id: number | string): void; + getgroups(): number[]; + setgroups(groups: Array): void; version: string; versions: ProcessVersions; config: { @@ -838,7 +835,47 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { - [header: string]: string | string[]; + 'accept'?: string; + 'access-control-allow-origin'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-headers'?: string; + 'accept-patch'?: string; + 'accept-ranges'?: string; + 'age'?: string; + 'allow'?: string; + 'alt-svc'?: string; + 'cache-control'?: string; + 'connection'?: string; + 'content-disposition'?: string; + 'content-encoding'?: string; + 'content-language'?: string; + 'content-length'?: string; + 'content-location'?: string; + 'content-range'?: string; + 'content-type'?: string; + 'date'?: string; + 'expires'?: string; + 'host'?: string; + 'last-modified'?: string; + 'location'?: string; + 'pragma'?: string; + 'proxy-authenticate'?: string; + 'public-key-pins'?: string; + 'retry-after'?: string; + 'set-cookie'?: string[]; + 'strict-transport-security'?: string; + 'trailer'?: string; + 'transfer-encoding'?: string; + 'tk'?: string; + 'upgrade'?: string; + 'vary'?: string; + 'via'?: string; + 'warning'?: string; + 'www-authenticate'?: string; + [header: string]: string | string[] | undefined; } // outgoing headers allows numbers (as they are converted internally to strings) @@ -4314,6 +4351,7 @@ declare module "fs" { autoClose?: boolean; start?: number; end?: number; + highWaterMark?: number; }): ReadStream; /** @@ -4483,9 +4521,6 @@ declare module "path" { /** * Solve the relative path from {from} to {to}. * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - * - * @param from - * @param to */ export function relative(from: string, to: string): string; /** @@ -4718,7 +4753,7 @@ declare module "tls" { encrypted: boolean; /** * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. - * @returns {CipherNameAndProtocol} - Returns an object representing the cipher name + * @returns Returns an object representing the cipher name * and the SSL/TLS protocol version of the current connection. */ getCipher(): CipherNameAndProtocol; @@ -4728,21 +4763,21 @@ declare module "tls" { * If detailed argument is true the full chain with issuer property will be returned, * if false only the top certificate without issuer property. * If the peer does not provide a certificate, it returns null or an empty object. - * @param {boolean} detailed - If true; the full chain with issuer property will be returned. - * @returns {PeerCertificate | DetailedPeerCertificate} - An object representing the peer's certificate. + * @param detailed - If true; the full chain with issuer property will be returned. + * @returns An object representing the peer's certificate. */ getPeerCertificate(detailed: true): DetailedPeerCertificate; getPeerCertificate(detailed?: false): PeerCertificate; getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; /** * Could be used to speed up handshake establishment when reconnecting to the server. - * @returns {any} - ASN.1 encoded TLS session or undefined if none was negotiated. + * @returns ASN.1 encoded TLS session or undefined if none was negotiated. */ getSession(): any; /** * NOTE: Works only with client TLS sockets. * Useful only for debugging, for session reuse provide session option to tls.connect(). - * @returns {any} - TLS session ticket or undefined if none was negotiated. + * @returns TLS session ticket or undefined if none was negotiated. */ getTLSTicket(): any; /** @@ -4750,9 +4785,9 @@ declare module "tls" { * * NOTE: Can be used to request peer's certificate after the secure connection has been established. * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. - * @param {TlsOptions} options - The options may contain the following fields: rejectUnauthorized, + * @param options - The options may contain the following fields: rejectUnauthorized, * requestCert (See tls.createServer() for details). - * @param {Function} callback - callback(err) will be executed with null as err, once the renegotiation + * @param callback - callback(err) will be executed with null as err, once the renegotiation * is successfully completed. */ renegotiate(options: TlsOptions, callback: (err: Error | null) => void): any; @@ -4763,8 +4798,8 @@ declare module "tls" { * large fragments can span multiple roundtrips, and their processing can be delayed due to packet * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, * which may decrease overall server throughput. - * @param {number} size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * @returns {boolean} - Returns true on success, false otherwise. + * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns Returns true on success, false otherwise. */ setMaxSendFragment(size: number): boolean; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 315ec48d2f..41639e52c6 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -684,6 +684,7 @@ namespace util_tests { assert(typeof util.inspect.custom === 'symbol'); // util.callbackify + // tslint:disable-next-line no-unnecessary-class class callbackifyTest { static fn(): Promise { assert(arguments.length === 0); @@ -1321,9 +1322,24 @@ namespace http_tests { request.abort(); } - const options: http.RequestOptions = { - timeout: 30000 - }; + // http request options + { + const requestOpts: http.RequestOptions = { + timeout: 30000 + }; + + const clientArgs: http.ClientRequestArgs = { + timeout: 30000 + }; + } + + // http headers + { + const headers: http.IncomingHttpHeaders = { + 'content-type': 'application/json', + 'set-cookie': [ 'type=ninja', 'language=javascript' ] + }; + } } ////////////////////////////////////////////////////// diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index d88db82da1..797bc455b8 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for Node.js 4.2 // Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript , DefinitelyTyped +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Sebastian Silbermann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************************ @@ -154,8 +156,6 @@ declare var Buffer: { prototype: Buffer; /** * Allocates a new Buffer using an {array} of octets. - * - * @param array */ from(array: any[]): Buffer; /** @@ -165,22 +165,16 @@ declare var Buffer: { * within the {arrayBuffer} that will be shared by the Buffer. * * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length */ from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?:number): Buffer; /** * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer */ from(buffer: Buffer): Buffer; /** * Creates a new Buffer containing the given JavaScript string {str}. * If provided, the {encoding} parameter identifies the character encoding. * If not provided, {encoding} defaults to 'utf8'. - * - * @param str */ from(str: string, encoding?: string): Buffer; /** @@ -565,21 +559,74 @@ declare module "http" { import * as net from "net"; import * as stream from "stream"; + // incoming headers will never contain number + export interface IncomingHttpHeaders { + 'accept'?: string; + 'access-control-allow-origin'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-headers'?: string; + 'accept-patch'?: string; + 'accept-ranges'?: string; + 'age'?: string; + 'allow'?: string; + 'alt-svc'?: string; + 'cache-control'?: string; + 'connection'?: string; + 'content-disposition'?: string; + 'content-encoding'?: string; + 'content-language'?: string; + 'content-length'?: string; + 'content-location'?: string; + 'content-range'?: string; + 'content-type'?: string; + 'date'?: string; + 'expires'?: string; + 'host'?: string; + 'last-modified'?: string; + 'location'?: string; + 'pragma'?: string; + 'proxy-authenticate'?: string; + 'public-key-pins'?: string; + 'retry-after'?: string; + 'set-cookie'?: string[]; + 'strict-transport-security'?: string; + 'trailer'?: string; + 'transfer-encoding'?: string; + 'tk'?: string; + 'upgrade'?: string; + 'vary'?: string; + 'via'?: string; + 'warning'?: string; + 'www-authenticate'?: string; + [header: string]: string | string[] | undefined; + } + + // outgoing headers allows numbers (as they are converted internally to strings) + export interface OutgoingHttpHeaders { + [header: string]: number | string | string[] | undefined; + } + export interface RequestOptions { protocol?: string; host?: string; hostname?: string; family?: number; - port?: number; + port?: number | string; localAddress?: string; socketPath?: string; method?: string; path?: string; - headers?: { [key: string]: any }; + headers?: OutgoingHttpHeaders; auth?: string; - agent?: Agent|boolean; + agent?: Agent | boolean; + timeout?: number; } + export type ClientRequestArgs = RequestOptions + export interface Server extends net.Server { setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; @@ -600,8 +647,8 @@ declare module "http" { write(str: string, encoding?: string, fd?: string): boolean; writeContinue(): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; - writeHead(statusCode: number, headers?: any): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; statusCode: number; statusMessage: string; headersSent: boolean; @@ -610,7 +657,7 @@ declare module "http" { getHeader(name: string): string; removeHeader(name: string): void; write(chunk: any, encoding?: string): any; - addTrailers(headers: any): void; + addTrailers(headers: OutgoingHttpHeaders): void; // Extended base methods end(): void; @@ -636,7 +683,7 @@ declare module "http" { setHeader(name: string, value: string | string[]): void; getHeader(name: string): string; removeHeader(name: string): void; - addTrailers(headers: any): void; + addTrailers(headers: OutgoingHttpHeaders): void; // Extended base methods end(): void; @@ -647,10 +694,10 @@ declare module "http" { } export interface IncomingMessage extends events.EventEmitter, stream.Readable { httpVersion: string; - headers: any; + headers: IncomingHttpHeaders; rawHeaders: string[]; - trailers: any; - rawTrailers: any; + trailers: OutgoingHttpHeaders; + rawTrailers: string[]; setTimeout(msecs: number, callback: Function): NodeJS.Timer; /** * Only valid for request obtained from http.Server. @@ -1576,15 +1623,11 @@ declare module "fs" { /** * Asynchronous rename. - * @param oldPath - * @param newPath * @param callback No arguments other than a possible exception are given to the completion callback. */ export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous rename - * @param oldPath - * @param newPath */ export function renameSync(oldPath: string, newPath: string): void; export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; @@ -1629,79 +1672,62 @@ declare module "fs" { /** * Asynchronous unlink - deletes the file specified in {path} * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous unlink - deletes the file specified in {path} - * - * @param path */ export function unlinkSync(path: string): void; /** * Asynchronous rmdir - removes the directory specified in {path} * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous rmdir - removes the directory specified in {path} - * - * @param path */ export function rmdirSync(path: string): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdirSync(path: string, mode?: number): void; /** * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdirSync(path: string, mode?: string): void; /** * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * - * @param prefix * @param callback The created folder path is passed as a string to the callback's second parameter. */ export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; /** * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * - * @param prefix * @returns Returns the created folder path. */ export function mkdtempSync(prefix: string): string; @@ -1736,8 +1762,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName - * @param encoding * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ export function readFile(filename: string, encoding: null, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; @@ -1746,7 +1770,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ @@ -1756,7 +1779,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ @@ -1764,15 +1786,11 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; /** * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param encoding */ export function readFileSync(filename: string, encoding: null): Buffer; export function readFileSync(filename: string, encoding: string): string; @@ -1780,7 +1798,6 @@ declare module "fs" { /** * Synchronous readFile - Synchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. */ export function readFileSync(filename: string, options: { encoding: null; flag?: string; }): Buffer; @@ -1789,7 +1806,6 @@ declare module "fs" { /** * Synchronous readFile - Synchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. */ export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; @@ -1833,6 +1849,7 @@ declare module "fs" { fd?: number; mode?: number; autoClose?: boolean; + highWaterMark?: number; }): ReadStream; export function createWriteStream(path: string, options?: { flags?: string; @@ -1910,9 +1927,6 @@ declare module "path" { /** * Solve the relative path from {from} to {to}. * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - * - * @param from - * @param to */ export function relative(from: string, to: string): string; /** diff --git a/types/node/v4/node-tests.ts b/types/node/v4/node-tests.ts index 05b20806cd..8f005da455 100644 --- a/types/node/v4/node-tests.ts +++ b/types/node/v4/node-tests.ts @@ -499,6 +499,25 @@ namespace http_tests { request.setNoDelay(true); request.abort(); } + + // http request options + { + const requestOpts: http.RequestOptions = { + timeout: 30000 + }; + + const clientArgs: http.ClientRequestArgs = { + timeout: 30000 + }; + } + + // http headers + { + const headers: http.IncomingHttpHeaders = { + 'content-type': 'application/json', + 'set-cookie': [ 'type=ninja', 'language=javascript' ] + }; + } } ////////////////////////////////////////////////////// diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 8f73bab752..e8931e43cf 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -1,6 +1,10 @@ // Type definitions for Node.js v6.x // Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript , DefinitelyTyped , Wilco Bakker , Thomas Bouldin +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Wilco Bakker +// Thomas Bouldin +// Sebastian Silbermann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************************ @@ -150,8 +154,6 @@ declare var Buffer: { prototype: Buffer; /** * Allocates a new Buffer using an {array} of octets. - * - * @param array */ from(array: any[]): Buffer; /** @@ -161,22 +163,16 @@ declare var Buffer: { * within the {arrayBuffer} that will be shared by the Buffer. * * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length */ from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; /** * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer */ from(buffer: Buffer): Buffer; /** * Creates a new Buffer containing the given JavaScript string {str}. * If provided, the {encoding} parameter identifies the character encoding. * If not provided, {encoding} defaults to 'utf8'. - * - * @param str */ from(str: string, encoding?: string): Buffer; /** @@ -637,21 +633,74 @@ declare module "http" { import * as net from "net"; import * as stream from "stream"; + // incoming headers will never contain number + export interface IncomingHttpHeaders { + 'accept'?: string; + 'access-control-allow-origin'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-headers'?: string; + 'accept-patch'?: string; + 'accept-ranges'?: string; + 'age'?: string; + 'allow'?: string; + 'alt-svc'?: string; + 'cache-control'?: string; + 'connection'?: string; + 'content-disposition'?: string; + 'content-encoding'?: string; + 'content-language'?: string; + 'content-length'?: string; + 'content-location'?: string; + 'content-range'?: string; + 'content-type'?: string; + 'date'?: string; + 'expires'?: string; + 'host'?: string; + 'last-modified'?: string; + 'location'?: string; + 'pragma'?: string; + 'proxy-authenticate'?: string; + 'public-key-pins'?: string; + 'retry-after'?: string; + 'set-cookie'?: string[]; + 'strict-transport-security'?: string; + 'trailer'?: string; + 'transfer-encoding'?: string; + 'tk'?: string; + 'upgrade'?: string; + 'vary'?: string; + 'via'?: string; + 'warning'?: string; + 'www-authenticate'?: string; + [header: string]: string | string[] | undefined; + } + + // outgoing headers allows numbers (as they are converted internally to strings) + export interface OutgoingHttpHeaders { + [header: string]: number | string | string[] | undefined; + } + export interface RequestOptions { protocol?: string; host?: string; hostname?: string; family?: number; - port?: number; + port?: number | string; localAddress?: string; socketPath?: string; method?: string; path?: string; - headers?: { [key: string]: any }; + headers?: OutgoingHttpHeaders; auth?: string; agent?: Agent | boolean; + timeout?: number; } + export type ClientRequestArgs = RequestOptions + export interface Server extends net.Server { setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; @@ -673,8 +722,8 @@ declare module "http" { write(str: string, encoding?: string, fd?: string): boolean; writeContinue(): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; - writeHead(statusCode: number, headers?: any): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; statusCode: number; statusMessage: string; headersSent: boolean; @@ -684,7 +733,7 @@ declare module "http" { getHeader(name: string): string; removeHeader(name: string): void; write(chunk: any, encoding?: string): any; - addTrailers(headers: any): void; + addTrailers(headers: OutgoingHttpHeaders): void; finished: boolean; // Extended base methods @@ -711,7 +760,7 @@ declare module "http" { setHeader(name: string, value: string | string[]): void; getHeader(name: string): string; removeHeader(name: string): void; - addTrailers(headers: any): void; + addTrailers(headers: OutgoingHttpHeaders): void; // Extended base methods end(): void; @@ -725,10 +774,10 @@ declare module "http" { httpVersionMajor: number; httpVersionMinor: number; connection: net.Socket; - headers: any; + headers: IncomingHttpHeaders; rawHeaders: string[]; - trailers: any; - rawTrailers: any; + trailers: OutgoingHttpHeaders; + rawTrailers: string[]; setTimeout(msecs: number, callback: Function): NodeJS.Timer; /** * Only valid for request obtained from http.Server. @@ -2354,15 +2403,11 @@ declare module "fs" { /** * Asynchronous rename. - * @param oldPath - * @param newPath * @param callback No arguments other than a possible exception are given to the completion callback. */ export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous rename - * @param oldPath - * @param newPath */ export function renameSync(oldPath: string, newPath: string): void; export function truncate(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; @@ -2407,79 +2452,62 @@ declare module "fs" { /** * Asynchronous unlink - deletes the file specified in {path} * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function unlink(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous unlink - deletes the file specified in {path} - * - * @param path */ export function unlinkSync(path: string | Buffer): void; /** * Asynchronous rmdir - removes the directory specified in {path} * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function rmdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous rmdir - removes the directory specified in {path} - * - * @param path */ export function rmdirSync(path: string | Buffer): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdirSync(path: string | Buffer, mode?: number): void; /** * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdirSync(path: string | Buffer, mode?: string): void; /** * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * - * @param prefix * @param callback The created folder path is passed as a string to the callback's second parameter. */ export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; /** * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * - * @param prefix * @returns Returns the created folder path. */ export function mkdtempSync(prefix: string): string; @@ -2512,8 +2540,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName - * @param encoding * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ export function readFile(filename: string, encoding: null, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; @@ -2522,7 +2548,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ @@ -2532,7 +2557,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ @@ -2540,15 +2564,11 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; /** * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param encoding */ export function readFileSync(filename: string, encoding: null): Buffer; export function readFileSync(filename: string, encoding: string): string; @@ -2556,7 +2576,6 @@ declare module "fs" { /** * Synchronous readFile - Synchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. */ export function readFileSync(filename: string, options: { encoding: null; flag?: string; }): Buffer; @@ -2565,7 +2584,6 @@ declare module "fs" { /** * Synchronous readFile - Synchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. */ export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; @@ -2732,6 +2750,7 @@ declare module "fs" { autoClose?: boolean; start?: number; end?: number; + highWaterMark?: number; }): ReadStream; export function createWriteStream(path: string | Buffer, options?: { flags?: string; @@ -2806,9 +2825,6 @@ declare module "path" { /** * Solve the relative path from {from} to {to}. * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - * - * @param from - * @param to */ export function relative(from: string, to: string): string; /** @@ -3007,7 +3023,7 @@ declare module "tls" { /** * Returns the bound address, the address family name and port of the underlying socket as reported by * the operating system. - * @returns {any} - An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. + * @returns An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. */ address(): { port: number; family: string; address: string }; /** @@ -3026,8 +3042,8 @@ declare module "tls" { encrypted: boolean; /** * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. - * @returns {CipherNameAndProtocol} - Returns an object representing the cipher name - * and the SSL/TLS protocol version of the current connection. + * @returns Returns an object representing the cipher name and the SSL/TLS protocol version of the current + * connection. */ getCipher(): CipherNameAndProtocol; /** @@ -3036,8 +3052,8 @@ declare module "tls" { * If detailed argument is true the full chain with issuer property will be returned, * if false only the top certificate without issuer property. * If the peer does not provide a certificate, it returns null or an empty object. - * @param {boolean} detailed - If true; the full chain with issuer property will be returned. - * @returns {any} - An object representing the peer's certificate. + * @param detailed - If true; the full chain with issuer property will be returned. + * @returns An object representing the peer's certificate. */ getPeerCertificate(detailed?: boolean): { subject: Certificate; @@ -3051,13 +3067,13 @@ declare module "tls" { }; /** * Could be used to speed up handshake establishment when reconnecting to the server. - * @returns {any} - ASN.1 encoded TLS session or undefined if none was negotiated. + * @returns ASN.1 encoded TLS session or undefined if none was negotiated. */ getSession(): any; /** * NOTE: Works only with client TLS sockets. * Useful only for debugging, for session reuse provide session option to tls.connect(). - * @returns {any} - TLS session ticket or undefined if none was negotiated. + * @returns TLS session ticket or undefined if none was negotiated. */ getTLSTicket(): any; /** @@ -3086,9 +3102,9 @@ declare module "tls" { * * NOTE: Can be used to request peer's certificate after the secure connection has been established. * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. - * @param {TlsOptions} options - The options may contain the following fields: rejectUnauthorized, + * @param options - The options may contain the following fields: rejectUnauthorized, * requestCert (See tls.createServer() for details). - * @param {Function} callback - callback(err) will be executed with null as err, once the renegotiation + * @param callback - callback(err) will be executed with null as err, once the renegotiation * is successfully completed. */ renegotiate(options: TlsOptions, callback: (err: Error) => any): any; @@ -3099,8 +3115,8 @@ declare module "tls" { * large fragments can span multiple roundtrips, and their processing can be delayed due to packet * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, * which may decrease overall server throughput. - * @param {number} size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * @returns {boolean} - Returns true on success, false otherwise. + * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns Returns true on success, false otherwise. */ setMaxSendFragment(size: number): boolean; diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index 15c36ef058..1a6b87db05 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -935,6 +935,25 @@ namespace http_tests { request.setNoDelay(true); request.abort(); } + + // http request options + { + const requestOpts: http.RequestOptions = { + timeout: 30000 + }; + + const clientArgs: http.ClientRequestArgs = { + timeout: 30000 + }; + } + + // http headers + { + const headers: http.IncomingHttpHeaders = { + 'content-type': 'application/json', + 'set-cookie': [ 'type=ninja', 'language=javascript' ] + }; + } } ////////////////////////////////////////////////////// diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index fc6cd33091..cc87fadd7c 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -5,6 +5,7 @@ // Parambir Singh // Christian Vaagland Tellnes // Wilco Bakker +// Sebastian Silbermann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************************ @@ -165,8 +166,6 @@ declare var Buffer: { prototype: Buffer; /** * Allocates a new Buffer using an {array} of octets. - * - * @param array */ from(array: any[]): Buffer; /** @@ -176,22 +175,16 @@ declare var Buffer: { * within the {arrayBuffer} that will be shared by the Buffer. * * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length */ from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; /** * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer */ from(buffer: Buffer): Buffer; /** * Creates a new Buffer containing the given JavaScript string {str}. * If provided, the {encoding} parameter identifies the character encoding. * If not provided, {encoding} defaults to 'utf8'. - * - * @param str */ from(str: string, encoding?: string): Buffer; /** @@ -653,22 +646,74 @@ declare module "http" { import * as net from "net"; import * as stream from "stream"; + // incoming headers will never contain number + export interface IncomingHttpHeaders { + 'accept'?: string; + 'access-control-allow-origin'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-headers'?: string; + 'accept-patch'?: string; + 'accept-ranges'?: string; + 'age'?: string; + 'allow'?: string; + 'alt-svc'?: string; + 'cache-control'?: string; + 'connection'?: string; + 'content-disposition'?: string; + 'content-encoding'?: string; + 'content-language'?: string; + 'content-length'?: string; + 'content-location'?: string; + 'content-range'?: string; + 'content-type'?: string; + 'date'?: string; + 'expires'?: string; + 'host'?: string; + 'last-modified'?: string; + 'location'?: string; + 'pragma'?: string; + 'proxy-authenticate'?: string; + 'public-key-pins'?: string; + 'retry-after'?: string; + 'set-cookie'?: string[]; + 'strict-transport-security'?: string; + 'trailer'?: string; + 'transfer-encoding'?: string; + 'tk'?: string; + 'upgrade'?: string; + 'vary'?: string; + 'via'?: string; + 'warning'?: string; + 'www-authenticate'?: string; + [header: string]: string | string[] | undefined; + } + + // outgoing headers allows numbers (as they are converted internally to strings) + export interface OutgoingHttpHeaders { + [header: string]: number | string | string[] | undefined; + } + export interface RequestOptions { protocol?: string; host?: string; hostname?: string; family?: number; - port?: number; + port?: number | string; localAddress?: string; socketPath?: string; method?: string; path?: string; - headers?: { [key: string]: any }; + headers?: OutgoingHttpHeaders; auth?: string; agent?: Agent | boolean; timeout?: number; } + export type ClientRequestArgs = RequestOptions + export interface Server extends net.Server { setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; @@ -690,8 +735,8 @@ declare module "http" { write(str: string, encoding?: string, fd?: string): boolean; writeContinue(): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; - writeHead(statusCode: number, headers?: any): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; statusCode: number; statusMessage: string; headersSent: boolean; @@ -701,7 +746,7 @@ declare module "http" { getHeader(name: string): string; removeHeader(name: string): void; write(chunk: any, encoding?: string): any; - addTrailers(headers: any): void; + addTrailers(headers: OutgoingHttpHeaders): void; finished: boolean; // Extended base methods @@ -728,7 +773,7 @@ declare module "http" { setHeader(name: string, value: string | string[]): void; getHeader(name: string): string; removeHeader(name: string): void; - addTrailers(headers: any): void; + addTrailers(headers: OutgoingHttpHeaders): void; // Extended base methods end(): void; @@ -742,10 +787,10 @@ declare module "http" { httpVersionMajor: number; httpVersionMinor: number; connection: net.Socket; - headers: any; + headers: IncomingHttpHeaders; rawHeaders: string[]; - trailers: any; - rawTrailers: any; + trailers: OutgoingHttpHeaders; + rawTrailers: string[]; setTimeout(msecs: number, callback: Function): NodeJS.Timer; /** * Only valid for request obtained from http.Server. @@ -2487,15 +2532,11 @@ declare module "fs" { /** * Asynchronous rename. - * @param oldPath - * @param newPath * @param callback No arguments other than a possible exception are given to the completion callback. */ export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous rename - * @param oldPath - * @param newPath */ export function renameSync(oldPath: string, newPath: string): void; export function truncate(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; @@ -2540,79 +2581,62 @@ declare module "fs" { /** * Asynchronous unlink - deletes the file specified in {path} * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function unlink(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous unlink - deletes the file specified in {path} - * - * @param path */ export function unlinkSync(path: string | Buffer): void; /** * Asynchronous rmdir - removes the directory specified in {path} * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function rmdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous rmdir - removes the directory specified in {path} - * - * @param path */ export function rmdirSync(path: string | Buffer): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdirSync(path: string | Buffer, mode?: number): void; /** * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdirSync(path: string | Buffer, mode?: string): void; /** * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * - * @param prefix * @param callback The created folder path is passed as a string to the callback's second parameter. */ export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; /** * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * - * @param prefix * @returns Returns the created folder path. */ export function mkdtempSync(prefix: string): string; @@ -2646,8 +2670,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName - * @param encoding * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ export function readFile(filename: string, encoding: null, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; @@ -2656,7 +2678,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ @@ -2666,7 +2687,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ @@ -2674,15 +2694,11 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; /** * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param encoding */ export function readFileSync(filename: string, encoding: null): Buffer; export function readFileSync(filename: string, encoding: string): string; @@ -2690,7 +2706,6 @@ declare module "fs" { /** * Synchronous readFile - Synchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. */ export function readFileSync(filename: string, options: { encoding: null; flag?: string; }): Buffer; @@ -2699,7 +2714,6 @@ declare module "fs" { /** * Synchronous readFile - Synchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. */ export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; @@ -2866,6 +2880,7 @@ declare module "fs" { autoClose?: boolean; start?: number; end?: number; + highWaterMark?: number; }): ReadStream; export function createWriteStream(path: string | Buffer, options?: { flags?: string; @@ -2940,9 +2955,6 @@ declare module "path" { /** * Solve the relative path from {from} to {to}. * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - * - * @param from - * @param to */ export function relative(from: string, to: string): string; /** @@ -3160,7 +3172,7 @@ declare module "tls" { /** * Returns the bound address, the address family name and port of the underlying socket as reported by * the operating system. - * @returns {any} - An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. + * @returns An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. */ address(): { port: number; family: string; address: string }; /** @@ -3179,7 +3191,7 @@ declare module "tls" { encrypted: boolean; /** * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. - * @returns {CipherNameAndProtocol} - Returns an object representing the cipher name + * @returns Returns an object representing the cipher name * and the SSL/TLS protocol version of the current connection. */ getCipher(): CipherNameAndProtocol; @@ -3189,15 +3201,15 @@ declare module "tls" { * If detailed argument is true the full chain with issuer property will be returned, * if false only the top certificate without issuer property. * If the peer does not provide a certificate, it returns null or an empty object. - * @param {boolean} detailed - If true; the full chain with issuer property will be returned. - * @returns {PeerCertificate | DetailedPeerCertificate} - An object representing the peer's certificate. + * @param detailed - If true; the full chain with issuer property will be returned. + * @returns An object representing the peer's certificate. */ getPeerCertificate(detailed: true): DetailedPeerCertificate; getPeerCertificate(detailed?: false): PeerCertificate; getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; /** * Could be used to speed up handshake establishment when reconnecting to the server. - * @returns {any} - ASN.1 encoded TLS session or undefined if none was negotiated. + * @returns ASN.1 encoded TLS session or undefined if none was negotiated. */ getSession(): any; /** @@ -3232,9 +3244,9 @@ declare module "tls" { * * NOTE: Can be used to request peer's certificate after the secure connection has been established. * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. - * @param {TlsOptions} options - The options may contain the following fields: rejectUnauthorized, + * @param options - The options may contain the following fields: rejectUnauthorized, * requestCert (See tls.createServer() for details). - * @param {Function} callback - callback(err) will be executed with null as err, once the renegotiation + * @param callback - callback(err) will be executed with null as err, once the renegotiation * is successfully completed. */ renegotiate(options: TlsOptions, callback: (err: Error) => any): any; @@ -3245,8 +3257,8 @@ declare module "tls" { * large fragments can span multiple roundtrips, and their processing can be delayed due to packet * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, * which may decrease overall server throughput. - * @param {number} size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * @returns {boolean} - Returns true on success, false otherwise. + * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns Returns true on success, false otherwise. */ setMaxSendFragment(size: number): boolean; diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index f439a83213..9bbf6a9300 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -1033,9 +1033,24 @@ namespace http_tests { request.abort(); } - const options: http.RequestOptions = { - timeout: 30000 - }; + // http request options + { + const requestOpts: http.RequestOptions = { + timeout: 30000 + }; + + const clientArgs: http.ClientRequestArgs = { + timeout: 30000 + }; + } + + // http headers + { + const headers: http.IncomingHttpHeaders = { + 'content-type': 'application/json', + 'set-cookie': [ 'type=ninja', 'language=javascript' ] + }; + } } ////////////////////////////////////////////////////// diff --git a/types/nodemailer/lib/smtp-connection.d.ts b/types/nodemailer/lib/smtp-connection.d.ts index 49b1adef8e..1215409b46 100644 --- a/types/nodemailer/lib/smtp-connection.d.ts +++ b/types/nodemailer/lib/smtp-connection.d.ts @@ -70,13 +70,15 @@ declare namespace SMTPConnection { dsn?: DSNOptions; } - class SMTPError extends Error { + interface SMTPError extends NodeJS.ErrnoException { /** string code identifying the error, for example ‘EAUTH’ is returned when authentication */ - code: string; + code?: string; /** the last response received from the server (if the error is caused by an error response from the server) */ - response: string; + response?: string; /** the numeric response code of the response string (if available) */ - responseCode: string; + responseCode?: number; + /** command which provoked an error */ + command?: string; } interface SentMessageInfo { diff --git a/types/nodemailer/nodemailer-tests.ts b/types/nodemailer/nodemailer-tests.ts index 6bf4935e0a..00238d2d5c 100644 --- a/types/nodemailer/nodemailer-tests.ts +++ b/types/nodemailer/nodemailer-tests.ts @@ -1035,7 +1035,13 @@ namespace smtp_connection_test { connection.login({ user: 'user', pass: 'pass' }, (err) => { if (err) throw err; connection.send({ from: 'a@example.com', to: 'b@example.net' }, 'message', (err, info) => { - if (err) throw err; + if (err) { + const code: string = err.code || '???'; + const response: string = err.response || '???'; + const responseCode: number = err.responseCode || 0; + const command: string = err.command || '???'; + throw err; + } connection.reset(() => { if (err) throw err; connection.quit(); diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index fef494614f..e24b6c4a2c 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -181,11 +181,16 @@ declare namespace Office { messageParent(messageObject: any): void; /** * Closes the UI container where the JavaScript is executing. - * The behavior of this method is specified by the following table. - * When called from Behavior - * A UI-less command button No effect. Any dialogs opened by displayDialogAsync will remain open. - * A taskpane The taskpane will close. Any dialogs opened by displayDialogAsync will also close. If the taskpane supports pinning and was pinned by the user, it will be un-pinned. - * A module extension No effect. + * + * Supported hosts: Outlook - Minimum requirement set: Mailbox 1.5 + * + * The behavior of this method is specified by the following: + * + * Called from a UI-less command button: No effect. Any dialog opened by displayDialogAsync will remain open. + * + * Called from a taskpane: The taskpane will close. Any dialog opened by displayDialogAsync will also close. If the taskpane supports pinning and was pinned by the user, it will be un-pinned. + * + * Called from a module extension: No effect. */ closeContainer(): void; } diff --git a/types/opn/index.d.ts b/types/opn/index.d.ts index 78a1043442..2a7c5afe25 100644 --- a/types/opn/index.d.ts +++ b/types/opn/index.d.ts @@ -1,80 +1,52 @@ -// Type definitions for opn 3.0.2 +// Type definitions for opn 5.1 // Project: https://github.com/sindresorhus/opn // Definitions by: Shinnosuke Watanabe , -// Maxime LUCE +// Maxime LUCE , +// Tommy Lent // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -import * as cp from "child_process"; +import * as cp from 'child_process'; -interface DefaultFunction { - /** - * Uses the command open on OS X, start on Windows and xdg-open on other platforms. - * - * Returns the spawned child process. - * You'd normally not need to use this for anything, but it can be useful if you'd like - * to attach custom event listeners or perform other operations directly on the spawned process. - * -* @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. - */ - (target: string): cp.ChildProcess; - - /** - * Uses the command open on OS X, start on Windows and xdg-open on other platforms. - * - * Returns the spawned child process. - * You'd normally not need to use this for anything, but it can be useful if you'd like - * to attach custom event listeners or perform other operations directly on the spawned process. - * - * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. - * @param callback- Called when the opened app exits, or if `wait: false`, immediately when opening. - */ - (target: string, callback: (err: Error) => void): cp.ChildProcess; - - /** - * Uses the command open on OS X, start on Windows and xdg-open on other platforms. - * - * Returns the spawned child process. - * You'd normally not need to use this for anything, but it can be useful if you'd like - * to attach custom event listeners or perform other operations directly on the spawned process. - * - * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. - * @param options - Options to be passed to opn. - */ - (target: string, options: Opn.Options): cp.ChildProcess; - - /** - * Uses the command open on OS X, start on Windows and xdg-open on other platforms. - * - * Returns the spawned child process. - * You'd normally not need to use this for anything, but it can be useful if you'd like - * to attach custom event listeners or perform other operations directly on the spawned process. - * - * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. - * @param options - Options to be passed to opn. - * @param callback- Called when the opened app exits, or if `wait: false`, immediately when opening. - */ - (target: string, options: Opn.Options, callback: (err: Error) => void): cp.ChildProcess; -} - -declare var opn: DefaultFunction; +/* Note that ES6 modules cannot directly export callable functions. + * This file should be imported using the CommonJS-style: + * import x = require('opn'); + */ export = opn; +/** + * Uses the command `open` on OS X, `start` on Windows and `xdg-open` on other platforms. + * + * Returns a promise for the spawned child process. You would normally not need to use this for + * anything, but it can be useful if you'd like to attach custom event listeners or perform + * other operations directly on the spawned process. + * + * @param target The thing you want to open. Can be a URL, file, or executable. + * Opens in the default app for the file type. For example, URLs open in your default + * browser. + * @param options Options to be passed to opn. + */ +declare function opn( + target: string, + options?: Opn.Options +): Promise; + declare namespace Opn { - export interface Options { + interface Options { /** - * Wait for the opened app to exit before calling the `callback`. - * If `false` it's called immediately when opening the app. + * Wait for the opened app to exit before fulfilling the promise. + * If `false` it's fulfilled immediately when opening the app. * On Windows you have to explicitly specify an app for it to be able to wait. + * Defaults to `true`. */ wait?: boolean; - + /** - * Specify the app to open the target with, or an array with the app and app arguments. - * The app name is platform dependent. Don't hard code it in reusable modules. + * Specify the app to open the `target` with, or an array with the app and app arguments. + * The app name is platform dependent. Don't hard code it in reusable modules. * Eg. Chrome is `google chrome` on OS X, `google-chrome` on Linux and `chrome` on Windows. */ - app?: string | string[]; + app?: string | ReadonlyArray; } } diff --git a/types/opn/opn-tests.ts b/types/opn/opn-tests.ts index 33a043de9f..c2956f2546 100644 --- a/types/opn/opn-tests.ts +++ b/types/opn/opn-tests.ts @@ -1,18 +1,8 @@ +import opn = require('opn'); +opn('foo'); // $ExpectType Promise -import * as opn from "opn"; - -var errorCallback: (err: Error) => void; - -opn("foo"); -opn("foo", errorCallback); - -opn("foo", { app: "bar" }); -opn("foo", { app: ["bar", "--arg"] }); -opn("foo", { app: "bar", wait: false }); -opn("foo", { app: ["bar", "--arg"] , wait: false}); - -opn("foo", { app: "bar" }, errorCallback); -opn("foo", { app: ["bar", "--arg"] }, errorCallback); -opn("foo", { app: "bar", wait: false }, errorCallback); -opn("foo", { app: ["bar", "--arg"], wait: false }, errorCallback); +opn('foo', { app: 'bar' }); // $ExpectType Promise +opn('foo', { app: ['bar', '--arg'] }); // $ExpectType Promise +opn('foo', { app: 'bar', wait: false }); // $ExpectType Promise +opn('foo', { app: ['bar', '--arg'], wait: false }); // $ExpectType Promise diff --git a/types/opn/tsconfig.json b/types/opn/tsconfig.json index 9c2829989d..2a51fff8ca 100644 --- a/types/opn/tsconfig.json +++ b/types/opn/tsconfig.json @@ -1,23 +1,16 @@ { "compilerOptions": { "module": "commonjs", - "lib": [ - "es6" - ], + "lib": ["es6"], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", - "typeRoots": [ - "../" - ], + "typeRoots": ["../"], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, - "files": [ - "index.d.ts", - "opn-tests.ts" - ] -} \ No newline at end of file + "files": ["index.d.ts", "opn-tests.ts"] +} diff --git a/types/opn/tslint.json b/types/opn/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/opn/tslint.json +++ b/types/opn/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/otplib/index.d.ts b/types/otplib/index.d.ts new file mode 100644 index 0000000000..d9ae32ddfb --- /dev/null +++ b/types/otplib/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for otplib 7.0 +// Project: https://yeojz.github.io/otplib +// Definitions by: Soner Köksal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export namespace authenticator { + interface VerifyOptions { + token: string; + secret: string; + } + + function generateSecret(): string; + + function generate(secret: string): string; + + function check(token: string, secret: string): boolean; + + function verify(options: VerifyOptions): boolean; +} diff --git a/types/otplib/otplib-tests.ts b/types/otplib/otplib-tests.ts new file mode 100644 index 0000000000..231b16716f --- /dev/null +++ b/types/otplib/otplib-tests.ts @@ -0,0 +1,7 @@ +import * as otplib from "otplib"; + +const secretValue = otplib.authenticator.generateSecret(); +const tokenValue = otplib.authenticator.generate(secretValue); + +let isValid = otplib.authenticator.check(tokenValue, secretValue); +isValid = otplib.authenticator.verify({secret: secretValue, token: tokenValue}); diff --git a/types/otplib/tsconfig.json b/types/otplib/tsconfig.json new file mode 100644 index 0000000000..cfb2b07081 --- /dev/null +++ b/types/otplib/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "otplib-tests.ts" + ] +} diff --git a/types/otplib/tslint.json b/types/otplib/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/otplib/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/package-json/index.d.ts b/types/package-json/index.d.ts new file mode 100644 index 0000000000..e57902875b --- /dev/null +++ b/types/package-json/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for package-json 4.0 +// Project: https://github.com/sindresorhus/package-json#readme +// Definitions by: Jinwoo Lee +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface PackageJsonOptions { + version?: string; + fullMetadata?: boolean; + allVersions?: boolean; +} + +declare function packageJson(name: string, options?: PackageJsonOptions): Promise<{}>; + +export = packageJson; diff --git a/types/package-json/package-json-tests.ts b/types/package-json/package-json-tests.ts new file mode 100644 index 0000000000..98f14b1192 --- /dev/null +++ b/types/package-json/package-json-tests.ts @@ -0,0 +1,10 @@ +import packageJson = require('package-json'); + +let pkg: {}; +packageJson('package-json', { + version: '1.2.3', + fullMetadata: true, + allVersions: true, +}).then(x => { + pkg = x; +}); diff --git a/types/package-json/tsconfig.json b/types/package-json/tsconfig.json new file mode 100644 index 0000000000..52c1adb7d3 --- /dev/null +++ b/types/package-json/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "package-json-tests.ts" + ] +} diff --git a/types/package-json/tslint.json b/types/package-json/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/package-json/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index d24a5cddc9..f75661377a 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Paper.js v0.9.23 +// Type definitions for Paper.js v0.9.24 // Project: http://paperjs.org/ // Definitions by: Clark Stevenson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -927,20 +927,34 @@ declare module 'paper' { abs(): Size; /* - * Returns the new multiplied size - * @param point - The size you want to multiply with + * Returns a new size + * @param size - The size you want to add with */ - multiply(point: Size): Size; - multiply(point: number[]): Size; - multiply(point: number): Size; + add(size: Size): Size; + add(size: number[]): Size; + + /* + * Returns a new size + * @param size - The size you want to subtract with + */ + subtract(size: Size): Size; + subtract(size: number[]): Size; + + /* + * Returns the new multiplied size + * @param size - The size you want to multiply with + */ + multiply(size: Size): Size; + multiply(size: number[]): Size; + multiply(size: number): Size; /* * Returns the new divided size - * @param point - The size you want to divide with + * @param size - The size you want to divide with */ - divide(point: Size): Size; - divide(point: number[]): Size; - divide(point: number): Size; + divide(size: Size): Size; + divide(size: number[]): Size; + divide(size: number): Size; } export interface IFrameEvent { diff --git a/types/parsimmon/index.d.ts b/types/parsimmon/index.d.ts index 6bc93ae84a..dfbae05e23 100644 --- a/types/parsimmon/index.d.ts +++ b/types/parsimmon/index.d.ts @@ -41,7 +41,7 @@ * //=> {status: true, value: ['a', ['c', 'c', 'c', 'c', 'c']]} * ``` */ -declare function Parsimmon(fn: (input: string, i: number) => Parsimmon.Result): Parsimmon.Parser; +declare function Parsimmon(fn: (input: string, i: number) => Parsimmon.Reply): Parsimmon.Parser; declare namespace Parsimmon { type StreamType = string; @@ -169,21 +169,21 @@ declare namespace Parsimmon { /** * Alias of `Parsimmon(fn)` for backwards compatibility. */ - function Parser(fn: (input: string, i: number) => Parsimmon.Result): Parser; + function Parser(fn: (input: string, i: number) => Parsimmon.Reply): Parser; /** * To be used inside of Parsimmon(fn). Generates an object describing how * far the successful parse went (index), and what value it created doing * so. See documentation for Parsimmon(fn). */ - function makeSuccess(index: number, value: T): Success; + function makeSuccess(index: number, value: T): SuccessReply; /** * To be used inside of Parsimmon(fn). Generates an object describing how * far the unsuccessful parse went (index), and what kind of syntax it * expected to see (expectation). See documentation for Parsimmon(fn). */ - function makeFailure(furthest: number, expectation: string): Failure; + function makeFailure(furthest: number, expectation: string): FailureReply; /** * Returns true if obj is a Parsimmon parser, otherwise false. @@ -276,9 +276,27 @@ declare namespace Parsimmon { p1: Parser, p2: Parser, p3: Parser, p4: Parser, p5: Parser, p6: Parser, p7: Parser, p8: Parser, cb: (a1: T, a2: U, a3: V, a4: W, a5: X, a6: Y, a7: Z, a8: A) => B): Parser; - type SuccessFunctionType = (index: number, result: U) => Result; - type FailureFunctionType = (index: number, msg: string) => Result; - type ParseFunctionType = (stream: StreamType, index: number) => Result; + interface SuccessReply { + status: true; + index: number; + value: T; + furthest: -1; + expected: string[]; + } + + interface FailureReply { + status: false; + index: -1; + value: null; + furthest: number; + expected: string[]; + } + + type Reply = SuccessReply | FailureReply; + + type SuccessFunctionType = (index: number, result: U) => Reply; + type FailureFunctionType = (index: number, msg: string) => Reply; + type ParseFunctionType = (stream: StreamType, index: number) => Reply; /** * allows to add custom primitive parsers. */ diff --git a/types/parsimmon/parsimmon-tests.ts b/types/parsimmon/parsimmon-tests.ts index 4c8780f5fc..f89d2fda2f 100644 --- a/types/parsimmon/parsimmon-tests.ts +++ b/types/parsimmon/parsimmon-tests.ts @@ -1,5 +1,5 @@ import P = require('parsimmon'); -import { Parser, Mark, Result, Index } from "parsimmon"; +import { Parser, Mark, Result, Index, Reply } from "parsimmon"; // -- -- -- -- -- -- -- -- -- -- -- -- -- @@ -65,9 +65,10 @@ if (fooResult.status === true) { } // -- -- -- -- -- -- -- -- -- -- -- -- -- +let fooReply: Reply; -fooResult = P.makeSuccess(0, foo); -fooResult = P.makeFailure(0, ''); +fooReply = P.makeSuccess(0, foo); +fooReply = P.makeFailure(0, ''); fooPar = P((input: string, i: number) => P.makeSuccess(0, foo)); fooPar = P.Parser((input: string, i: number) => P.makeSuccess(0, foo)); diff --git a/types/passport-facebook-token/index.d.ts b/types/passport-facebook-token/index.d.ts index 9013910ee1..9877b84527 100644 --- a/types/passport-facebook-token/index.d.ts +++ b/types/passport-facebook-token/index.d.ts @@ -7,15 +7,17 @@ import * as passport from 'passport'; import * as express from 'express'; -declare class Strategy implements passport.Strategy { - constructor(options: Strategy.StrategyOptionsWithRequest, verify: Strategy.VerifyFunctionWithRequest) - constructor(options: Strategy.StrategyOptions, verify: Strategy.VerifyFunction); +declare namespace PassportFacebookToken { + interface StrategyStatic { + new(options: StrategyOptionsWithRequest, verify: VerifyFunctionWithRequest): StrategyInstance; + new(options: StrategyOptions, verify: VerifyFunction): StrategyInstance; + } - name: string; - authenticate: (req: express.Request, options?: any) => void; -} + interface StrategyInstance { + name: string; + authenticate: (req: express.Request, options?: any) => void; + } -declare namespace Strategy { interface ValueObject { value: string; } @@ -55,4 +57,5 @@ declare namespace Strategy { type VerifyFunctionWithRequest = (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void; } -export = Strategy; +declare const PassportFacebookToken: PassportFacebookToken.StrategyStatic; +export = PassportFacebookToken; diff --git a/types/passport-facebook-token/passport-facebook-token-tests.ts b/types/passport-facebook-token/passport-facebook-token-tests.ts index cb2f078e88..c926748286 100644 --- a/types/passport-facebook-token/passport-facebook-token-tests.ts +++ b/types/passport-facebook-token/passport-facebook-token-tests.ts @@ -1,8 +1,6 @@ import * as express from 'express'; import * as passport from 'passport'; -import * as FacebookStrategy from 'passport-facebook-token'; -// tslint:disable-next-line:no-duplicate-imports -import { StrategyOptions, StrategyOptionsWithRequest, VerifyFunction, VerifyFunctionWithRequest, Profile } from 'passport-facebook-token'; +import * as PassportFacebookToken from 'passport-facebook-token'; const User = { findOrCreate(id: string, provider: string, callback: (err: any, user: any) => void): void { @@ -10,18 +8,19 @@ const User = { } }; -const options: StrategyOptions = { +const options: PassportFacebookToken.StrategyOptions = { clientID: 'TEST_CLIENT_ID', clientSecret: 'TEST_CLIENT_SECRET' }; -const optionsWithRequest: StrategyOptionsWithRequest = { +const optionsWithRequest: PassportFacebookToken.StrategyOptionsWithRequest = { clientID: 'TEST_CLIENT_ID', clientSecret: 'TEST_CLIENT_SECRET', passReqToCallback: true }; -const verify: VerifyFunction = (accessToken: string, refreshToken: string, profile: Profile, done: (err: any, user?: any, info?: any) => void) => { +const verify: PassportFacebookToken.VerifyFunction = + (accessToken: string, refreshToken: string, profile: PassportFacebookToken.Profile, done: (err: any, user?: any, info?: any) => void) => { User.findOrCreate(profile.id, profile.provider, (err, user) => { if (err) { done(err); @@ -30,7 +29,8 @@ const verify: VerifyFunction = (accessToken: string, refreshToken: string, profi }); }; -const verifyWithRequest: VerifyFunctionWithRequest = (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (err: any, user?: any, info?: any) => void) => { +const verifyWithRequest: PassportFacebookToken.VerifyFunctionWithRequest = + (req: express.Request, accessToken: string, refreshToken: string, profile: PassportFacebookToken.Profile, done: (err: any, user?: any, info?: any) => void) => { User.findOrCreate(profile.id, profile.provider, (err, user) => { if (err) { done(err); @@ -39,5 +39,5 @@ const verifyWithRequest: VerifyFunctionWithRequest = (req: express.Request, acce }); }; -passport.use(new FacebookStrategy(options, verify)); -passport.use(new FacebookStrategy(optionsWithRequest, verifyWithRequest)); +passport.use(new PassportFacebookToken(options, verify)); +passport.use(new PassportFacebookToken(optionsWithRequest, verifyWithRequest)); diff --git a/types/pdfjs-dist/index.d.ts b/types/pdfjs-dist/index.d.ts index a40c612d5a..f72d70f44e 100644 --- a/types/pdfjs-dist/index.d.ts +++ b/types/pdfjs-dist/index.d.ts @@ -407,6 +407,12 @@ declare namespace PDF { * in browsers which support the fullscreen API. */ disableFullscreen: boolean; + + /** + * Disable the text layer of PDF when used PDF.js renders a canvas instead of div elements + * + */ + disableTextLayer: boolean; /** * Enables CSS only zooming. @@ -475,5 +481,11 @@ declare namespace PDF { : PDFPromise; PDFViewer(params: PDFViewerParams): void; + /** + * yet another viewer, this will render only one page at the time, reducing rendering time + * very important for mobile development + * @params {PDFViewerParams} + */ + PDFSinglePageViewer(params: PDFViewerParams): void; } } diff --git a/types/pg/index.d.ts b/types/pg/index.d.ts index 68fba5fb40..62208830b3 100644 --- a/types/pg/index.d.ts +++ b/types/pg/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for pg 7.1 +// Type definitions for pg 7.4 // Project: https://github.com/brianc/node-postgres // Definitions by: Phips Peter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -47,6 +47,7 @@ export interface QueryConfig { name?: string; text: string; values?: any[]; + rowMode?: string; } export interface QueryResult { diff --git a/types/pixelmatch/index.d.ts b/types/pixelmatch/index.d.ts new file mode 100644 index 0000000000..0a2e4277ac --- /dev/null +++ b/types/pixelmatch/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for pixelmatch 4.0 +// Project: https://github.com/mapbox/pixelmatch#readme +// Definitions by: Oleg Repin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare function Pixelmatch( + /** Image data of the first image to compare. Note: image dimensions must be equal. */ + img1: Buffer | Uint8Array, + /** Image data of the second image to compare. Note: image dimensions must be equal. */ + img2: Buffer | Uint8Array, + /** Image data to write the diff to, or null if don't need a diff image. */ + output: Buffer | Uint8Array | null, + /** Width of the images. Note that all three images need to have the same dimensions. */ + width: number, + /** Height of the images. Note that all three images need to have the same dimensions. */ + height: number, + /** Options. */ + options?: Options, +): number; + +interface Options { + /** Matching threshold, ranges from 0 to 1. Smaller values make the comparison more sensitive. 0.1 by default. */ + readonly threshold?: number; + /** If true, disables detecting and ignoring anti-aliased pixels. false by default. */ + readonly includeAA?: boolean; +} + +export = Pixelmatch; diff --git a/types/pixelmatch/pixelmatch-tests.ts b/types/pixelmatch/pixelmatch-tests.ts new file mode 100644 index 0000000000..dc49f7f326 --- /dev/null +++ b/types/pixelmatch/pixelmatch-tests.ts @@ -0,0 +1,27 @@ +/** + * This test code taken from pixelmatch example usage. + * https://github.com/mapbox/pixelmatch#example-usage + */ + +import * as fs from 'fs'; +import pixelmatch = require('pixelmatch'); +import { PNG } from 'pngjs'; + +const img1 = fs.createReadStream('img1.png') + .pipe(new PNG()) + .on('parsed', doneReading); + +const img2 = fs.createReadStream('img2.png') + .pipe(new PNG()) + .on('parsed', doneReading); + +let filesRead = 0; + +function doneReading() { + if (++filesRead < 2) return; + const diff = new PNG({width: img1.width, height: img1.height}); + + pixelmatch(img1.data, img2.data, diff.data, img1.width, img1.height, {threshold: 0.1}); + + diff.pack().pipe(fs.createWriteStream('diff.png')); +} diff --git a/types/pixelmatch/tsconfig.json b/types/pixelmatch/tsconfig.json new file mode 100644 index 0000000000..02115e3fdc --- /dev/null +++ b/types/pixelmatch/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pixelmatch-tests.ts" + ] +} diff --git a/types/pixelmatch/tslint.json b/types/pixelmatch/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pixelmatch/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pixi.js/index.d.ts b/types/pixi.js/index.d.ts index f33f0d502c..48b9583c0b 100644 --- a/types/pixi.js/index.d.ts +++ b/types/pixi.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Pixi.js 4.5 +// Type definitions for Pixi.js 4.6 // Project: https://github.com/pixijs/pixi.js/tree/dev // Definitions by: clark-stevenson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -372,7 +372,7 @@ declare namespace PIXI { on(event: interaction.InteractionEventTypes, fn: (event: interaction.InteractionEvent) => void, context?: any): this; once(event: interaction.InteractionEventTypes, fn: (event: interaction.InteractionEvent) => void, context?: any): this; removeListener(event: interaction.InteractionEventTypes, fn?: (event: interaction.InteractionEvent) => void, context?: any): this; - removeAllListeners(event: interaction.InteractionEventTypes): this; + removeAllListeners(event?: interaction.InteractionEventTypes): this; off(event: interaction.InteractionEventTypes, fn?: (event: interaction.InteractionEvent) => void, context?: any): this; addListener(event: interaction.InteractionEventTypes, fn: (event: interaction.InteractionEvent) => void, context?: any): this; } @@ -875,7 +875,7 @@ declare namespace PIXI { on(event: "prerender" | "postrender", fn: () => void, context?: any): this; once(event: "prerender" | "postrender", fn: () => void, context?: any): this; removeListener(event: "prerender" | "postrender", fn?: () => void, context?: any): this; - removeAllListeners(event: "prerender" | "postrender"): this; + removeAllListeners(event?: "prerender" | "postrender"): this; off(event: "prerender" | "postrender", fn?: () => void, context?: any): this; addListener(event: "prerender" | "postrender", fn: () => void, context?: any): this; } @@ -977,7 +977,7 @@ declare namespace PIXI { once(event: "context", fn: (gl: WebGLRenderingContext) => void, context?: any): this; removeListener(event: "prerender" | "postrender", fn?: () => void, context?: any): this; removeListener(event: "context", fn?: (gl: WebGLRenderingContext) => void, context?: any): this; - removeAllListeners(event: "prerender" | "postrender" | "context"): this; + removeAllListeners(event?: "prerender" | "postrender" | "context"): this; off(event: "prerender" | "postrender", fn?: () => void, context?: any): this; off(event: "context", fn?: (gl: WebGLRenderingContext) => void, context?: any): this; addListener(event: "prerender" | "postrender", fn: () => void, context?: any): this; @@ -1485,7 +1485,7 @@ declare namespace PIXI { on(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; once(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; removeListener(event: "update", fn?: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; - removeAllListeners(event: "update"): this; + removeAllListeners(event?: "update"): this; off(event: "update", fn?: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; addListener(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; } @@ -1542,7 +1542,7 @@ declare namespace PIXI { on(event: "update" | "loaded" | "error" | "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): this; once(event: "update" | "loaded" | "error" | "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): this; removeListener(event: "update" | "loaded" | "error" | "dispose", fn?: (baseTexture: BaseTexture) => void, context?: any): this; - removeAllListeners(event: "update" | "loaded" | "error" | "dispose"): this; + removeAllListeners(event?: "update" | "loaded" | "error" | "dispose"): this; off(event: "update" | "loaded" | "error" | "dispose", fn?: (baseTexture: BaseTexture) => void, context?: any): this; addListener(event: "update" | "loaded" | "error" | "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): this; } @@ -1568,7 +1568,7 @@ declare namespace PIXI { protected _uvs: TextureUvs; orig: Rectangle; protected _updateID: number; - transform: any; + transform: TextureMatrix; textureCacheIds: string[]; update(): void; @@ -1576,7 +1576,7 @@ declare namespace PIXI { protected onBaseTextureUpdated(baseTexture: BaseTexture): void; destroy(destroyBase?: boolean): void; clone(): Texture; - protected _updateUvs(): void; + _updateUvs(): void; static fromImage(imageUrl: string, crossOrigin?: boolean, scaleMode?: number, sourceScale?: number): Texture; static fromFrame(frameId: string): Texture; @@ -1604,10 +1604,27 @@ declare namespace PIXI { on(event: "update", fn: (texture: Texture) => void, context?: any): this; once(event: "update", fn: (texture: Texture) => void, context?: any): this; removeListener(event: "update", fn?: (texture: Texture) => void, context?: any): this; - removeAllListeners(event: "update"): this; + removeAllListeners(event?: "update"): this; off(event: "update", fn?: (texture: Texture) => void, context?: any): this; addListener(event: "update", fn: (texture: Texture) => void, context?: any): this; } + class TextureMatrix { + constructor(texture: Texture, clampMargin?: number); + + protected _texture: Texture; + mapCoord: Matrix; + uClampFrame: Float32Array; + uClampOffset: Float32Array; + protected _lastTextureID: number; + + clampOffset: number; + clampMargin: number; + + texture: Texture; + + update(forceUpdate?: boolean): boolean; + multiplyUvs(uvs: Float32Array, out?: Float32Array): Float32Array; + } class TextureUvs { x0: number; y0: number; @@ -1833,7 +1850,7 @@ declare namespace PIXI { static fromFrames(frame: string[]): AnimatedSprite; static fromImages(images: string[]): AnimatedSprite; } - class TextureTransform { + class TextureMatrix { constructor(texture: Texture, clampMargin?: number); protected _texture: Texture; @@ -1857,7 +1874,7 @@ declare namespace PIXI { protected _width: number; protected _height: number; protected _canvasPattern: CanvasPattern; - uvTransform: TextureTransform; + uvTransform: TextureMatrix; uvRespectAnchor: boolean; clampMargin: number; @@ -1986,6 +2003,8 @@ declare namespace PIXI { map: Texture; } class AlphaFilter extends Filter<{}> { + constructor(alpha?: number); + alpha: number; glShaderKey: number; } @@ -2409,7 +2428,7 @@ declare namespace PIXI { texture: Texture; tintRgb: Float32Array; protected _glDatas: { [n: number]: any; }; - protected _uvTransform: extras.TextureTransform; + protected _uvTransform: extras.TextureMatrix; uploadUvTransform: boolean; multiplyUvs(): void; refresh(forceUpdate?: boolean): void; @@ -2642,7 +2661,7 @@ declare namespace PIXI { ////////////////////////////////////////////////////////////////////////////// /////////////////////////////pixi-gl-core///////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - // pixi-gl-core https://github.com/pixijs/pixi-gl-core + // pixi-gl-core 1.1.2 https://github.com/pixijs/pixi-gl-core // sharedArrayBuffer as a type is not available yet. // need to fully define what an `Attrib` is. namespace glCore { @@ -2727,7 +2746,7 @@ declare namespace PIXI { uniforms: any; attributes: any; - bind(): void; + bind(): this; destroy(): void; } class GLTexture { @@ -3203,6 +3222,15 @@ declare namespace PIXI { type PRECISION = string; } + namespace GroupD8 { + /** + * @name PIXI.GroupD8.isSwapWidthHeight + * @see PIXI.GroupD8.isVertical + * @deprecated since version 4.6.0 + */ + function isSwapWidthHeight(rotation: number): boolean; + } + namespace extras { /** * @class @@ -3212,6 +3240,15 @@ declare namespace PIXI { * @deprecated since version 4.2.0 */ type MovieClip = extras.AnimatedSprite; + + /** + * @class + * @name TextureTransform + * @memberof PIXI.extras + * @see PIXI.TextureMatrix + * @deprecated since version 4.6.0 + */ + type TextureTranform = TextureMatrix; } namespace filters { diff --git a/types/pixi.js/pixi.js-tests.ts b/types/pixi.js/pixi.js-tests.ts index 53eaff46a3..48581e67fe 100644 --- a/types/pixi.js/pixi.js-tests.ts +++ b/types/pixi.js/pixi.js-tests.ts @@ -1235,6 +1235,67 @@ function demos() { } } + class TextureRotate { + private app: PIXI.Application; + private bol: boolean; + private texture: PIXI.Texture; + private secondTexture: PIXI.Texture; + private dude: PIXI.Sprite; + + constructor() { + this.app = new PIXI.Application(); + document.body.appendChild(this.app.view); + + this.bol = false; + + PIXI.loader.add("flowerTop", "required/assets/flowerTop.png"); + PIXI.loader.load((loader: PIXI.loaders.Loader, resources: any) => { + this.texture = resources.flowerTop.texture; + this.init(); + }); + } + + private init(): void { + const textures = [this.texture]; + const D8 = PIXI.GroupD8; + for (let rotate = 1; rotate < 16; rotate++) { + const h = D8.isVertical(rotate) ? this.texture.frame.width : this.texture.frame.height; + const w = D8.isVertical(rotate) ? this.texture.frame.height : this.texture.frame.width; + + const frame = this.texture.frame; + const crop = new PIXI.Rectangle(this.texture.frame.x, this.texture.frame.y, w, h); + const trim = crop; + let rotatedTexture: PIXI.Texture; + if (rotate % 2 === 0) { + rotatedTexture = new PIXI.Texture(this.texture.baseTexture, frame, crop, trim, rotate); + } else { + rotatedTexture = new PIXI.Texture(this.texture.baseTexture, frame, crop, trim, rotate - 1); + rotatedTexture.rotate++; + } + textures.push(rotatedTexture); + } + + const offsetX = this.app.renderer.width / 16 | 0; + const offsetY = this.app.renderer.height / 8 | 0; + const gridW = this.app.renderer.width / 4 | 0; + const gridH = this.app.renderer.height / 5 | 0; + + for (let i = 0; i < 16; i++) { + const dude = new PIXI.Sprite(textures[i < 8 ? i * 2 : (i - 8) * 2 + 1]); + dude.scale.x = 0.5; + dude.scale.y = 0.5; + dude.x = offsetX + gridW * (i % 4); + dude.y = offsetY + gridH * (i / 4 | 0); + this.app.stage.addChild(dude); + + const text = new PIXI.Text("rotate = " + dude.texture.rotate, { fontFamily: "Courier New", fontSize: "12px", fill: "white", align: "left" }); + text.x = dude.x; + text.y = dude.y - 20; + this.app.stage.addChild(text); + } + } + } + class TextureSwap { private app: PIXI.Application; private bol: boolean; diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index a34dbf2ab8..81286fe0a4 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -94,23 +94,30 @@ export function downloadImage(root: Root, opts: DownloadImgopts): Promise; autosize: boolean; showlegend: boolean; - xaxis: Partial; - yaxis: Partial; - yaxis2: Partial; - yaxis3: Partial; - yaxis4: Partial; - yaxis5: Partial; - yaxis6: Partial; - yaxis7: Partial; - yaxis8: Partial; - yaxis9: Partial; + paper_bgcolor: Color; + plot_bgcolor: Color; + separators: string; + hidesources: boolean; + xaxis: Partial; + yaxis: Partial; + yaxis2: Partial; + yaxis3: Partial; + yaxis4: Partial; + yaxis5: Partial; + yaxis6: Partial; + yaxis7: Partial; + yaxis8: Partial; + yaxis9: Partial; margin: Partial; height: number; width: number; - hovermode: "closest" | "x" | "y" | false; - 'xaxis.range': [Datum, Datum]; + hovermode: 'closest' | 'x' | 'y' | false; + hoverlabel: Partial