diff --git a/notNeededPackages.json b/notNeededPackages.json index 306865851b..7541a88848 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -60,6 +60,12 @@ "sourceRepoURL": "https://github.com/AlexTeixeira/Askmethat-Rating", "asOfVersion": "0.4.0" }, + { + "libraryName": "autobind-decorator", + "typingsPackageName": "autobind-decorator", + "sourceRepoURL": "https://github.com/andreypopp/autobind-decorator", + "asOfVersion": "2.1.0" + }, { "libraryName": "aws-sdk", "typingsPackageName": "aws-sdk", @@ -132,6 +138,12 @@ "sourceRepoURL": "https://github.com/mapbox/cheap-ruler", "asOfVersion": "2.5.0" }, + { + "libraryName": "commander", + "typingsPackageName": "commander", + "sourceRepoURL": "https://github.com/tj/commander.js", + "asOfVersion": "2.12.2" + }, { "libraryName": "constant-case", "typingsPackageName": "constant-case", @@ -558,6 +570,12 @@ "sourceRepoURL": "https://github.com/gpbl/react-day-picker", "asOfVersion": "5.3.0" }, + { + "libraryName": "react-native-elements", + "typingsPackageName": "react-native-elements", + "sourceRepoURL": "https://github.com/react-native-training/react-native-elements", + "asOfVersion": "0.18.0" + }, { "libraryName": "realm", "typingsPackageName": "realm", diff --git a/types/alexa-sdk/index.d.ts b/types/alexa-sdk/index.d.ts index 1c39755b2d..02def0b4d6 100644 --- a/types/alexa-sdk/index.d.ts +++ b/types/alexa-sdk/index.d.ts @@ -4,15 +4,85 @@ // Huw // pascalwhoop // Ben +// rk-7 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 export function handler(event: RequestBody, context: Context, callback?: (err: any, response: any) => void): AlexaObject; export function CreateStateHandler(state: string, obj: any): any; export let StateString: string; - export type ConfirmationStatuses = "NONE" | "DENIED" | "CONFIRMED"; export type DialogStates = "STARTED" | "IN_PROGRESS" | "COMPLETED"; +export type ListItemObjectStatus = "active" | "completed"; +export type ListObjectState = "active" | "archived"; +export type ImageSourceSize = "X_SMALL" | "SMALL" | "MEDIUM" | "LARGE" | "X_LARGE"; +export type TemplateBackButtonVisibility = "HIDDEN" | "VISIBLE"; +export type TemplateType = "BodyTemplate1" | "BodyTemplate2" | "BodyTemplate3" | "BodyTemplate6" | "BodyTemplate6" | "ListTemplate1" | "ListTemplate2"; +export type AudioPlayerActivity = "IDLE" | "PAUSED" | "PLAYING" | "BUFFER_UNDERRUN" | "FINISHED" | "STOPPED"; +export type CardType = "Standard" | "Simple" | "LinkAccount" | "AskForPermissionsConsent"; +export type HintType = "PlainText"; +export type DirectiveTypes = "AudioPlayer.Play" | "AudioPlayer.Stop" | "AudioPlayer.ClearQueue" | "Display.RenderTemplate" | "Hint" | "VideoApp.Launch"; +export type TextContentType = "PlainText" | "RichText"; + +//#region Types +export interface CardImage { + /** + * Recommended size (in px): 720w x 480h + */ + smallImageUrl: string; + /** + * Recommended size (in px): 1200w x 800h + */ + largeImageUrl: string; +} +export interface ImageSource { + url: string; + widthPixels?: number; + heightPixels?: number; + /** + * Recommended sizes for the following dimensions (in px): + * 480 x 320 for X_SMALL, + * 720 x 480 for SMALL, + * 960 x 640 for MEDIUM, + * 1200 x 800 for LARGE, + * 1920 x 1280 for X_LARGE + */ + size?: ImageSourceSize; +} +export interface Image { + contentDescription: string; + sources: ImageSource[]; +} +export interface TextField { + text: string; + type: string; +} +export interface TextContent { + primaryText?: TextField; + secondaryText?: TextField; + tertiaryText?: TextField; +} +export interface ListItem { + image?: Image; + token: string; + textContent?: TextContent; +} + +export interface Template { + title?: string; + token: string; + backgroundImage?: Image; + /** + * Visibility of the back button. + */ + backButton?: TemplateBackButtonVisibility; + /** + * Template type. + */ + type: TemplateType; + image?: Image; + listItems?: ListItem[]; +} export interface AlexaObject extends Handler { _event: any; @@ -38,12 +108,16 @@ export interface Handler { emitWithState: any; state: any; handler: any; + i18n: any; + locale: any; event: RequestBody; attributes: any; context: any; + callback: (param: any) => void; name: any; isOverriden: any; t: (token: string, ...args: any[]) => void; + response: ResponseBuilder; } export interface Context { @@ -55,8 +129,28 @@ export interface Context { functionVersion: string; invokeid: string; awsRequestId: string; + System?: System; + AudioPlayer?: AudioPlayer; +} +export interface Application { + applicationId: string; + [key: string]: string; +} +export interface System { + apiAccessToken: string; + apiEndpoint: string; + application: Application; + device: any; + user: any; +} +export interface AudioPlayer { + token: string; + offsetInMilliseconds: number; + /** + * Player activity + */ + playerActivity: AudioPlayerActivity; } - export interface RequestBody { version: string; session: Session; @@ -66,20 +160,22 @@ export interface RequestBody { export interface Session { new: boolean; sessionId: string; - attributes: any; - application: SessionApplication; + attributes: { [key: string]: any }; + application: Application; user: SessionUser; } - -export interface SessionApplication { - applicationId: string; -} - export interface SessionUser { userId: string; accessToken?: string; + permissions: Permissions; +} +export interface Permissions { + /** + * @deprecated + */ + consentToken: string; + [key: string]: string; } - export interface LaunchRequest extends Request { } export interface IntentRequest extends Request { @@ -144,7 +240,8 @@ export interface Response { outputSpeech?: OutputSpeech; card?: Card; reprompt?: Reprompt; - shouldEndSession: boolean; + directives?: any; + shouldEndSession?: boolean; } export interface OutputSpeech { @@ -154,18 +251,682 @@ export interface OutputSpeech { } export interface Card { - type: "Simple" | "Standard" | "LinkAccount"; + type: CardType; title?: string; content?: string; text?: string; - image?: Image; -} - -export interface Image { - smallImageUrl: string; - largeImageUrl: string; + image?: CardImage; } export interface Reprompt { outputSpeech: OutputSpeech; } + +export interface ApiClientOptions { + hostname: string; + port: string; + path: string; + protocol: string; + headers: string; + method: string; +} +export interface ApiClientResponse { + statusCode: string; + statusText: string; + body: object; + headers: object; +} +/** + * Todo-ListItem class + * Refer https://developer.amazon.com/docs/custom-skills/access-the-alexa-shopping-and-to-do-lists.html + */ +export interface ListItemObject { + /** + * item id (String, limit 60 characters) + */ + id: string; + /** + * item value (String, limit is 256 characters) + */ + value: string; + /** + * item status + */ + status?: ListItemObjectStatus; + /** + * item version (Positive integer) + */ + version?: number | string; + /** + * created time (ISO 8601 time format with time zone) + */ + createdTime: Date; + /** + * updated time (ISO 8601 time format with time zone) + */ + updatedTime: Date; + /** + * URL to retrieve the item (String) + */ + href?: string; +} +/** + * Todo-List class + * Refer https://developer.amazon.com/docs/custom-skills/access-the-alexa-shopping-and-to-do-lists.html + */ +export interface ListObject { + /** + * list id (String) + */ + listId: string; + /** + * list name (String) + */ + name: string; + /** + * state + * "active" or "archived" (Enum) + */ + state?: ListObjectState; + /** + * Possibly status of the list (or state?) + * Fetched from commit eebba0d at https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs/ + * File path: alexa-skills-kit-sdk-for-nodejs/lib/services/listManagementService.js + */ + status?: string; + /** + * list version (Positive integer) + */ + version?: number; + /** + * Urls to active and completed items + * href is lint to the items having certain status. + * The status can be "active" or "completed". + */ + statusMap: { href: string; status: ListItemObjectStatus; }; + /** + * Items that belong to this list. + */ + items: ListItemObject[]; +} +//#endregion + +//#region templateBuilders +/** + * Generates templates for Echo Show device. + */ +export namespace templateBuilders { + interface SetTextContent> { + setTextContent(primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): T; + } + interface SetListItems> { + setListItems(listItems: ListItem[]): T; + } + /** + * Refer https://developer.amazon.com/docs/custom-skills/display-interface-reference.html#image-sizes + */ + abstract class TemplateBuilder> { + template: Template; + constructor(); + + /** + * Sets the title of the template + * @param title title + * @returns TemplateBuilder + */ + setTitle(title: string): T; + + /** + * Sets the token of the template + * @param token token + * @returns TemplateBuilder + */ + setToken(token: string): T; + + /** + * Sets the background image of the template + * @param image image + * @returns TemplateBuilder + */ + setBackgroundImage(image: Image): T; + + /** + * Sets the backButton behavior + * @param backButtonBehavior "VISIBLE" or "HIDDEN" + * @returns TemplateBuilder + */ + setBackButtonBehavior(backButtonBehavior: string): T; + + /** + * Builds the template JSON object + * @returns Template + */ + build(): Template; + } + /** + * Used to build a list of ListItems for ListTemplate + */ + class ListItemBuilder { + constructor(); + items: ListItem[]; + /** + * Add an item to the list of template + * @param image image + * @param token token + * @param primaryText primaryText + * @param secondaryText secondaryText + * @param tertiaryText tertiaryText + */ + addItem(image: Image, token: string, primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): ListItemBuilder; + + build(): ListItem[]; + } + /** + * Used to create BodyTemplate1 objects + */ + class BodyTemplate1Builder extends TemplateBuilder implements SetTextContent { + constructor(); + /** + * Sets the text content for the template + * @param primaryText primaryText + * @param secondaryText secondaryText + * @param tertiaryText tertiaryText + * @returns BodyTemplate1Builder + */ + setTextContent(primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): BodyTemplate1Builder; + } + /** + * Used to create BodyTemplate2 objects + */ + class BodyTemplate2Builder extends TemplateBuilder implements SetTextContent { + constructor(); + + /** + * Sets the image for the template + * @param image image + * @returns BodyTemplate2Builder + */ + setImage(image: Image): BodyTemplate2Builder; + + /** + * Sets the text content for the template + * @param primaryText primaryText + * @param secondaryText secondaryText + * @param tertiaryText tertiaryText + * @returns BodyTemplate2Builder + */ + setTextContent(primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): BodyTemplate2Builder; + } + /** + * Used to create BodyTemplate3 objects + */ + class BodyTemplate3Builder extends TemplateBuilder implements SetTextContent { + constructor(); + + /** + * Sets the image for the template + * @param image image + * @returns BodyTemplate3Builder + */ + setImage(image: Image): BodyTemplate3Builder; + + /** + * Sets the text content for the template + * @param primaryText primaryText + * @param secondaryText secondaryText + * @param tertiaryText tertiaryText + * @returns BodyTemplate3Builder + */ + setTextContent(primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): BodyTemplate3Builder; + } + /** + * Used to create BodyTemplate6 objects + */ + class BodyTemplate6Builder extends TemplateBuilder implements SetTextContent { + constructor(); + + /** + * Sets the image for the template + * @param image image + * @returns BodyTemplate6Builder + */ + setImage(image: Image): BodyTemplate6Builder; + + /** + * Sets the text content for the template + * @param primaryText primaryText + * @param secondaryText secondaryText + * @param tertiaryText tertiaryText + * @returns BodyTemplate6Builder + */ + setTextContent(primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): BodyTemplate6Builder; + } + /** + * Used to create BodyTemplate7 objects + */ + class BodyTemplate7Builder extends TemplateBuilder { + constructor(); + + /** + * Sets the image for the template + * @param image image + * @returns BodyTemplate7Builder + */ + setImage(image: Image): BodyTemplate7Builder; + } + /** + * Used to create ListTemplate1 objects + */ + class ListTemplate1Builder extends TemplateBuilder implements SetListItems { + constructor(); + + /** + * Set the items for the list + * @param listItems listItems + * @returns ListTemplate1Builder + */ + setListItems(listItems: ListItem[]): ListTemplate1Builder; + } + /** + * Used to create ListTemplate2 objects + */ + class ListTemplate2Builder extends TemplateBuilder implements SetListItems { + constructor(); + + /** + * Set the items for the list + * @param listItems listItems + * @returns ListTemplate2Builder + */ + setListItems(listItems: ListItem[]): ListTemplate2Builder; + } +} +//#endregion + +//#region services +export namespace services { + interface ApiClient { + /** + * Make a POST API call to the specified uri with headers and optional body + * @param uri http(s?) endpoint to call + * @param headers Key value pair of headers + * @param body post body to send + * @returns Promise + */ + post(uri: string, headers: object, body?: string): Promise; + /** + * Make a PUT API call to the specified uri with headers and optional body + * @param uri http(s?) endpoint to call + * @param headers Key value pair of headers + * @param body post body to send + * @returns Promise + */ + put(uri: string, headers: object, body?: string): Promise; + /** + * Make a GET API call to the specified uri with headers + * @param uri http(s?) endpoint to call + * @param headers key value pair of headers + * @returns Promise + */ + get(uri: string, headers: object): Promise; + /** + * Make a DELETE API call to the specified uri with headers + * @param uri http(s?) endpoint to call + * @param headers key value pair of headers + * @returns Promise + */ + delete(uri: string, headers: object): Promise; + } + class DeviceAddressService { + /** + * Create an instance of DeviceAddressService + * @param [apiClient=new ApiClient()] ApiClient + */ + constructor(apiClient: ApiClient); + + /** + * Get full address information from Alexa Device Address API + * @param deviceId deviceId from Alexa request + * @param apiEndpoint API apiEndpoint from Alexa request + * @param token bearer token for device address permission + * @returns Promise + */ + getFullAddress(deviceId: string, apiEndpoint: string, token: string): Promise; + + /** + * Get country and postal information from Alexa Device Address API + * @param deviceId deviceId from Alexa request + * @param apiEndpoint API apiEndpoint from Alexa request + * @param token bearer token for device address permission + * @returns Promise + */ + getCountryAndPostalCode(deviceId: string, apiEndpoint: string, token: string): Promise; + } + class DirectiveService { + /** + * Creates an instance of DirectiveService. + * @param [apiClient=new ApiClient()] ApiClient + */ + constructor(apiClient: ApiClient); + + /** + * Send the specified directiveObj to Alexa directive service + * + * @param directive directive to send to service + * @param apiEndpoint API endpoint from Alexa request + * @param token bearer token for directive service + * @returns Promise + */ + enqueue(directive: object, apiEndpoint: string, token: string): Promise; + } + class ListManagementService { + /** + * Create an instance of ListManagementService + * @param apiClient apiClient + */ + constructor(apiClient: ApiClient); + + /** + * Set apiEndpoint address, default is "https://api.amazonalexa.com" + * @param apiEndpoint apiEndpoint + * @returns void + */ + setApiEndpoint(apiEndpoint: string): void; + + /** + * Get currently set apiEndpoint address + * @returns string + */ + getApiEndpoint(): string; + + /** + * Retrieve the metadata for all customer lists, including the customer's default lists + * @param token bearer token for list management permission + * @returns Promise + */ + getListsMetadata(token: string): Promise; + + /** + * Create a custom list. The new list name must be different than any existing list name + * @param listObject listObject + * @param token bearer token for list management permission + * @returns Promise + */ + createList(listObject: ListObject, token: string): Promise; + + /** + * Retrieve list metadata including the items in the list with requested status + * @param listId unique Id associated with the list + * @param itemStatus itemsStatus can be either "active" or "completed" + * @param token bearer token for list management permission + * @returns Promise + */ + getList(listId: string, itemStatus: ListItemObjectStatus, token: string): Promise; + + /** + * Update a custom list. Only the list name or state can be updated + * @param listId unique Id associated with the list + * @param listObject listObject + * @param token bearer token for list management permission + * @returns Promise + */ + updateList(listId: string, listObject: ListObject, token: string): Promise; + + /** + * Delete a custom list + * @param listId unique Id associated with the list + * @param token bearer token for list management permission + * @returns Promise + */ + deleteList(listId: string, token: string): Promise; + + /** + * Create an item in an active list or in a default list + * @param listId unique Id associated with the list + * @param listItemObject listItemObject + * @param token bearer token for list management permission + * @returns Promise + */ + createListItem(listId: string, listItemObject: ListItemObject, token: string): Promise; + + /** + * Retrieve single item within any list by listId and itemId + * @param listId unique Id associated with the list + * @param itemId unique Id associated with the item + * @param token bearer token for list management permission + * @returns Promise + */ + getListItem(listId: string, itemId: string, token: string): Promise; + + /** + * Update an item value or item status + * @param listId unique Id associated with the list + * @param itemId unique Id associated with the item + * @param listItemObject listItemObject + * @param token bearer token for list management permission + * @returns Promise + */ + updateListItem(listId: string, itemId: string, listItemObject: ListItemObject, token: string): Promise; + + /** + * Delete an item in the specified list + * @param listId unique Id associated with the list + * @param itemId unique Id associated with the item + * @param token bearer token for list management permission + * @returns Promise + */ + deleteListItem(listId: string, itemId: string, token: string): Promise; + } +} +//#endregion + +//#region ResponseBuilder +/** + * Responsible for building JSON responses as per the Alexa skills kit interface + * https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/alexa-skills-kit-interface-reference#response-body-syntax + */ +export class ResponseBuilder { + constructor(alexaHandler: Handler); + + /** + * Have Alexa say the provided speechOutput to the user + * @param speechOutput speechOutput + * @returns ResponseBuilder + */ + speak(speechOutput: string): ResponseBuilder; + + /** + * Have alexa listen for speech from the user. If the user doesn't respond within 8 seconds + * then have alexa reprompt with the provided reprompt speech + * @param repromptSpeech repromptSpeech + * @returns ResponseBuilder + */ + listen(repromptSpeech: string): ResponseBuilder; + + /** + * Render a card with the following title, content and image + * @param cardTitle cardTitle + * @param cardContent cardContent + * @param cardImage cardImage + * @returns ResponseBuilder + */ + cardRenderer(cardTitle: string, cardContent: string, cardImage: CardImage): ResponseBuilder; + + /** + * Render a link account card + * @returns ResponseBuilder + */ + linkAccountCard(): ResponseBuilder; + + /** + * Render a askForPermissionsConsent card + * @param permissions permissions + * @returns ResponseBuilder + */ + askForPermissionsConsentCard(permissions: [{ [key: string]: string }]): ResponseBuilder; + + /** + * Creates a play, stop or clearQueue audioPlayer directive depending on the directive type passed in. + * @deprecated - use audioPlayerPlay, audioPlayerStop, audioPlayerClearQueue instead + * @param directiveType directiveType + * @param behavior behavior + * @param url url + * @param token token + * @param expectedPreviousToken expectedPreviousToken + * @param offsetInMilliseconds offsetInMilliseconds + * @returns ResponseBuilder + */ + audioPlayer(directiveType: string, behavior: string, url: string, token: string, expectedPreviousToken: string, offsetInMilliseconds: number): ResponseBuilder; + + /** + * Creates an AudioPlayer play directive + * @param behavior Describes playback behavior. Accepted values: + * REPLACE_ALL: Immediately begin playback of the specified stream, and replace current and enqueued streams. + * ENQUEUE: Add the specified stream to the end of the current queue. This does not impact the currently playing stream. + * REPLACE_ENQUEUED: Replace all streams in the queue. This does not impact the currently playing stream. + * @param url Identifies the location of audio content at a remote HTTPS location. + * The audio file must be hosted at an Internet-accessible HTTPS endpoint. HTTPS is required, and the domain hosting the + * files must present a valid, trusted SSL certificate. Self-signed certificates cannot be used. + * The supported formats for the audio file include AAC/MP4, MP3, HLS, PLS and M3U. Bitrates: 16kbps to 384 kbps. + * @param token A token that represents the audio stream. This token cannot exceed 1024 characters + * @param expectedPreviousToken A token that represents the expected previous stream. + * This property is required and allowed only when the playBehavior is ENQUEUE. This is used to prevent potential race conditions + * if requests to progress through a playlist and change tracks occur at the same time. + * @param offsetInMilliseconds The timestamp in the stream from which Alexa should begin playback. + * Set to 0 to start playing the stream from the beginning. Set to any other value to start playback from that associated point in the stream + * @returns ResponseBuilder + */ + audioPlayerPlay(behavior: string, url: string, token: string, expectedPreviousToken: string, offsetInMilliseconds: number): ResponseBuilder; + + /** + * Creates an AudioPlayer Stop directive - Stops the current audio Playback + * @returns ResponseBuilder + */ + audioPlayerStop(): ResponseBuilder; + + /** + * Creates an AudioPlayer ClearQueue directive - clear the queue without stopping the currently playing stream, + * or clear the queue and stop any currently playing stream. + * @param clearBehavior Describes the clear queue behavior. Accepted values: + * CLEAR_ENQUEUED: clears the queue and continues to play the currently playing stream + * CLEAR_ALL: clears the entire playback queue and stops the currently playing stream (if applicable). + * @returns ResponseBuilder + */ + audioPlayerClearQueue(clearBehavior: string): ResponseBuilder; + + /** + * Creates a Display RenderTemplate Directive + * Use a template builder to generate a template object + * @param template template + * @returns ResponseBuilder + */ + renderTemplate(template: Template): ResponseBuilder; + + /** + * Creates a hint directive - show a hint on the screen of the echo show + * @param hintText text to show on the hint + * @param hintType (optional) Default value : PlainText + * @returns ResponseBuilder + */ + hint(hintText: string, hintType?: HintType): ResponseBuilder; + + /** + * Creates a VideoApp play directive to play a video + * @param source Identifies the location of video content at a remote HTTPS location. + * The video file must be hosted at an Internet-accessible HTTPS endpoint. + * @param metadata (optional) Contains an object that provides the + * information that can be displayed on VideoApp. + * @returns ResponseBuilder + */ + playVideo(source: string, metadata?: { title: string, subtitle: string }): ResponseBuilder; +} +//#endregion + +//#region directives +export namespace directives { + class VoicePlayerSpeakDirective { + header: { requestId: string }; + directive: { type: string, speech: string }; + /** + * Creates an instance of VoicePlayerSpeakDirective. + * @param requestId - requestId from which the call is originated from + * @param speechContent - Contents of the speech directive either in plain text or SSML. + */ + constructor(requestId: string, speechContent: string); + } +} +//#endregion + +//#region utils +export namespace utils { + namespace ImageUtils { + /** + * Creates an image object with a single source + * These images may be in either JPEG or PNG formats, with the appropriate file extensions. + * An image cannot be larger than 2 MB + * You must host the images at HTTPS URLs that are publicly accessible. + * widthPixels and heightPixels are optional - Do not include them unless they are exactly correct. + * By default, for Echo Show, size takes the value X_SMALL. If the other size values are included, + * then the order of precedence for displaying images begins with X_LARGE and proceeds downward, + * which means that larger images will be downscaled for display on Echo Show if provided. + * example : ImageUtils.makeImage("https://url/to/my/img.png", 300, 400, "SMALL", "image description") + * @param url url of the image + * @param widthPixels (optional) width of the image in pixels + * @param heightPixels (optional) height of the image in pixels + * @param size size of the image (X_SMALL, SMALL, MEDIUM, LARGE, X_LARGE) + * @param description text used to describe the image in a screen reader + * @returns Image + */ + function makeImage(url: string, widthPixels?: number, heightPixels?: number, size?: ImageSourceSize, description?: string): Image; + /** + * Creates an image object with a multiple sources, source images are provided as an array of image objects + * These images may be in either JPEG or PNG formats, with the appropriate file extensions. + * An image cannot be larger than 2 MB + * You must host the images at HTTPS URLs that are publicly accessible. + * widthPixels and heightPixels are optional - Do not include them unless they are exactly correct. + * By default, for Echo Show, size takes the value X_SMALL. If the other size values are included, + * then the order of precedence for displaying images begins with X_LARGE and proceeds downward, + * which means that larger images will be downscaled for display on Echo Show if provided. + * example : + * let imgArr = [ + * { "https://url/to/my/small.png", 300, 400, "SMALL" }, + * { "https://url/to/my/large.png", 900, 1200, "LARGE" }, + * ] + * ImageUtils.makeImage(imgArr, "image description") + * + * @param imgArr Array of Image + * @param description text used to describe the image in a screen reader + * @returns Image + */ + function makeImages(imgArr: Array<{ url: string, widthPixels?: number, heightPixels?: number, size: ImageSourceSize }>, description: string): Image; + } + /** + * Utility methods for building TextField objects + */ + namespace TextUtils { + /** + * Creates a plain TextField object with contents : text + * @param text contents of plain text object + * @returns TextField + */ + function makePlainText(text: string): TextField; + + /** + * Creates a rich TextField object with contents : text + * @param text text + * @returns TextField + */ + function makeRichText(text: string): TextField; + + /** + * Creates a textContent + * @param primaryText primary Text + * @param secondaryText secondary Text + * @param tertiaryText tertiary Text + * @returns TextContent + */ + function makeTextContent(primaryText: { type: TextContentType, text: string }, + secondaryText: { type: TextContentType, text: string }, tertiaryText: { type: TextContentType, text: string }): TextContent; + } +} +//#endregion diff --git a/types/alexa-sdk/tsconfig.json b/types/alexa-sdk/tsconfig.json index acc11c8263..d1932fa469 100644 --- a/types/alexa-sdk/tsconfig.json +++ b/types/alexa-sdk/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "alexa-sdk-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/alexa-sdk/tslint.json b/types/alexa-sdk/tslint.json index 78f1939ba2..32a9916641 100644 --- a/types/alexa-sdk/tslint.json +++ b/types/alexa-sdk/tslint.json @@ -1,10 +1,11 @@ -{ "extends": "dtslint/dt.json", - "rules": { - "object-literal-shorthand": false, - "object-literal-key-quote": false, - "no-empty-interface": false, - "prefer-method-signature": false, - "object-literal-key-quotes": false, - "no-any": false - } +{ + "extends": "dtslint/dt.json", + "rules": { + "object-literal-shorthand": false, + "object-literal-key-quote": false, + "no-empty-interface": false, + "prefer-method-signature": false, + "object-literal-key-quotes": false, + "no-any": false + } } diff --git a/types/angular-websocket/angular-websocket-tests.ts b/types/angular-websocket/angular-websocket-tests.ts index 1df77b7a2a..51246c529a 100644 --- a/types/angular-websocket/angular-websocket-tests.ts +++ b/types/angular-websocket/angular-websocket-tests.ts @@ -1,69 +1,62 @@ -let dummySocket: ng.websocket.IWebSocket; -let dummyPromise: ng.IPromise; -let dummyScope: ng.IScope; +import * as ng from 'angular'; -let provider: ng.websocket.IWebSocketProvider = (url: string, protocols?:string[] | ng.websocket.IWebSocketConfigOptions, options?: ng.websocket.IWebSocketConfigOptions) => { - return dummySocket; -} +(promise: angular.IPromise, scope: ng.IScope, provider: ng.websocket.IWebSocketProvider) => { + const socket = provider("wss://localhost"); + const socketWithProtocols = provider("wss://localhost", ["protocol-a", "protocol-b"]); -let socketWithProtocol = provider("wss://localhost", "protocol"); -let socketWithProtocols = provider("wss://localhost", ["protocol-a", "protocol-b"]); + const socketWithOptions = provider("wss://localhost", { + scope, + rootScopeFailOver: true, + useApplyAsync: true, + initialTimeout: 100, + maxTimeout: 300000, + reconnectIfNotNormalClose: true, + binaryType: "blob" + }); -let socketWithOptions = provider("wss://localhost", { - scope: dummyScope, - rootScopeFailOver: true, - useApplyAsync: true, - initialTimeout: 100, - maxTimeout: 300000, - reconnectIfNotNormalClose: true, - binaryType: "blob" -}); + const socketWithProtocolAndOptions = provider("wss://localhost", "protocol", { + scope, + rootScopeFailOver: true, + useApplyAsync: true, + initialTimeout: 100, + maxTimeout: 300000, + reconnectIfNotNormalClose: true, + binaryType: "blob" + }); -let socketWithProtocolAndOptions = provider("wss://localhost", "protocol", { - scope: dummyScope, - rootScopeFailOver: true, - useApplyAsync: true, - initialTimeout: 100, - maxTimeout: 300000, - reconnectIfNotNormalClose: true, - binaryType: "blob" -}); + socket.onOpen((event: Event) => {}) + .onClose((event: Event) => {}) + .onError((event: Event) => {}) + .onMessage((event: Event) => {}); -let socket = provider("wss://localhost"); + socket.onMessage((event: Event) => {}, { filter: /Some Filter/ }) + .onMessage((event: Event) => {}, { filter: 'Some Filter' }) + .onMessage((event: Event) => {}, { filter: 'Some Filter', autoApply: true }) + .onMessage((event: Event) => {}, { autoApply: false }); -socket.onOpen((event) => {}) - .onClose((event) => {}) - .onError((event) => {}) - .onMessage((event) => {}); + socket.close(true); + socket.close(); -socket.onMessage((event) => {}, { filter: /Some Filter/ }) - .onMessage((event) => {}, { filter: 'Some Filter' }) - .onMessage((event) => {}, { filter: 'Some Filter', autoApply: true }) - .onMessage((event) => {}, { autoApply: false }); + socket.send("Some great data here!").finally(() => {}); + socket.send({ list: [1, 2, 3, 4] }); -socket.close(true); -socket.close(); + socket.socket.send("data"); + socket.socket.close(); + socket.socket.close(1); + socket.socket.close(1, "reason"); -socket.send("Some great data here!").finally(() => {}); -socket.send({ list: [1, 2, 3, 4] }); + socket.sendQueue.push({ message: "msg", defered: promise }); -socket.socket.send("data"); -socket.socket.close(); -socket.socket.close(1); -socket.socket.close(1, "reason"); + socket.onOpenCallbacks.push((event: Event) => {}); + socket.onCloseCallbacks.push((event: CloseEvent) => {}); + socket.onErrorCallbacks.push((event: Event) => {}); + socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: 'Some Filter', autoApply: true }); + socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: /Some Filter/, autoApply: true }); + socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, autoApply: true }); -socket.sendQueue.push({ message: "msg", defered: dummyPromise }); + socket.readyState = 0; -socket.onOpenCallbacks.push((event: Event) => {}); -socket.onCloseCallbacks.push((event: CloseEvent) => {}); -socket.onErrorCallbacks.push((event: Event) => {}); -socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: 'Some Filter', autoApply: true }); -socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: /Some Filter/, autoApply: true }); -socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: undefined, autoApply: true }); - -socket.readyState = 0; - -socket.initialTimeout = 10; - -socket.maxTimeout = 5000; + socket.initialTimeout = 10; + socket.maxTimeout = 5000; +}; diff --git a/types/angular-websocket/index.d.ts b/types/angular-websocket/index.d.ts index b7b3f55093..0b26bd2cfd 100644 --- a/types/angular-websocket/index.d.ts +++ b/types/angular-websocket/index.d.ts @@ -1,39 +1,45 @@ -// Type definitions for angular-websocket v2.0 +// Type definitions for angular-websocket 2.0 // Project: https://github.com/AngularClass/angular-websocket // Definitions by: Nick Veys // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as ng from "angular"; +import * as angular from "angular"; + +export type IWebSocketConfigOptions = angular.websocket.IWebSocketConfigOptions; +export type IWebSocketProvider = angular.websocket.IWebSocketProvider; +export type IWebSocketMessageOptions = angular.websocket.IWebSocketMessageOptions; +export type IWebSocketMessageHandler = angular.websocket.IWebSocketMessageHandler; +export type IWebSocketQueueItem = angular.websocket.IWebSocketQueueItem; +export type IWebSocket = angular.websocket.IWebSocket; declare module "angular" { namespace websocket { - /** * Options available to be specified for IWebSocketProvider. */ - type IWebSocketConfigOptions = { - scope?: ng.IScope; - rootScopeFailOver?: boolean; - useApplyAsync?: boolean; - initialTimeout?: number; - maxTimeout?: number; - binaryType?: "blob" | "arraybuffer"; - reconnectIfNotNormalClose?: boolean; - } - interface IWebSocketProvider { - /** - * Creates and opens an IWebSocket instance. - * - * @param url url to connect to - * @return websocket instance - */ - (url: string, protocols?: string | string[] | IWebSocketConfigOptions, options?: IWebSocketConfigOptions): IWebSocket; + interface IWebSocketConfigOptions { + scope?: IScope; + rootScopeFailOver?: boolean; + useApplyAsync?: boolean; + initialTimeout?: number; + maxTimeout?: number; + binaryType?: "blob" | "arraybuffer"; + reconnectIfNotNormalClose?: boolean; } + /** + * Creates and opens an IWebSocket instance. + * + * @param url url to connect to + * @return websocket instance + */ + type IWebSocketProvider = + (url: string, protocols?: string | string[] | IWebSocketConfigOptions, + options?: IWebSocketConfigOptions) => IWebSocket; + /** Options available to be specified for IWebSocket.onMessage */ - type IWebSocketMessageOptions = { - + interface IWebSocketMessageOptions { /** * If specified, only messages that match the filter will cause the message event * to be fired. @@ -44,21 +50,20 @@ declare module "angular" { autoApply?: boolean; } - /** Type corresponding to onMessage callbaks stored in $Websocket#onMessageCallbacks instance. */ - type IWebSocketMessageHandler = { - fn: (evt: MessageEvent) => void; - pattern: string | RegExp; - autoApply: boolean; + /** Type corresponding to onMessage callbacks stored in $Websocket#onMessageCallbacks instance. */ + interface IWebSocketMessageHandler { + fn: (evt: MessageEvent) => void; + pattern?: string | RegExp; + autoApply: boolean; } /** Type corresponding to items stored in $WebSocket#sendQueue instance. */ - type IWebSocketQueueItem = { - message: any; - defered: ng.IPromise; + interface IWebSocketQueueItem { + message: any; + defered: IPromise; } interface IWebSocket { - /** * Adds a callback to be executed each time a socket connection is opened for * this instance. @@ -108,7 +113,7 @@ declare module "angular" { * * @param data data to send, if this is an object, it will be stringified before sending */ - send(data: string | {}): ng.IPromise; + send(data: string | {}): IPromise; /** * WebSocket instance. @@ -123,7 +128,7 @@ declare module "angular" { /** * List of callbacks to be executed when the socket is opened. */ - onOpenCallbacks: ((evt: Event) => void)[]; + onOpenCallbacks: Array<((evt: Event) => void)>; /** * List of callbacks to be executed when a message is received from the socket. @@ -133,12 +138,12 @@ declare module "angular" { /** * List of callbacks to be executed when an error is received from the socket. */ - onErrorCallbacks: ((evt: Event) => void)[]; + onErrorCallbacks: Array<((evt: Event) => void)>; /** * List of callbacks to be executed when the socket is closed. */ - onCloseCallbacks: ((evt: CloseEvent) => void)[]; + onCloseCallbacks: Array<((evt: CloseEvent) => void)>; /** * Returns either the readyState value from the underlying WebSocket instance diff --git a/types/angular-websocket/tsconfig.json b/types/angular-websocket/tsconfig.json index 96aab30ef0..89d5cb9dc3 100644 --- a/types/angular-websocket/tsconfig.json +++ b/types/angular-websocket/tsconfig.json @@ -1,8 +1,4 @@ { - "files": [ - "index.d.ts", - "angular-websocket-tests.ts" - ], "compilerOptions": { "module": "commonjs", "lib": [ @@ -11,8 +7,8 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": false, + "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" @@ -20,5 +16,9 @@ "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true - } -} \ No newline at end of file + }, + "files": [ + "index.d.ts", + "angular-websocket-tests.ts" + ] +} diff --git a/types/angular-websocket/tslint.json b/types/angular-websocket/tslint.json index a41bf5d19a..2c7c1bed53 100644 --- a/types/angular-websocket/tslint.json +++ b/types/angular-websocket/tslint.json @@ -1,79 +1,6 @@ { "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 + "interface-name": false } } 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/react-native-elements/tslint.json b/types/ansi-regex/tslint.json similarity index 100% rename from types/react-native-elements/tslint.json rename to types/ansi-regex/tslint.json diff --git a/types/applepayjs/applepayjs-tests.ts b/types/applepayjs/applepayjs-tests.ts index 505dbd2daf..99b323453b 100644 --- a/types/applepayjs/applepayjs-tests.ts +++ b/types/applepayjs/applepayjs-tests.ts @@ -22,7 +22,7 @@ describe("ApplePaySession", () => { }); it("can create a new instance", () => { const version = 1; - const paymentRequest = { + const paymentRequest: ApplePayJS.ApplePayPaymentRequest = { countryCode: "US", currencyCode: "USD", supportedNetworks: [ @@ -57,8 +57,8 @@ describe("ApplePaySession", () => { }); }); it("can call instance methods", () => { - const version = 1; - const paymentRequest = { + const version = 3; + const paymentRequest: ApplePayJS.ApplePayPaymentRequest = { countryCode: "US", currencyCode: "USD", supportedNetworks: [ @@ -66,7 +66,9 @@ describe("ApplePaySession", () => { "visa" ], merchantCapabilities: [ - "supports3DS" + "supports3DS", + "supportsCredit", + "supportsDebit" ], total: { label: "My Store", @@ -80,15 +82,29 @@ describe("ApplePaySession", () => { session.completeMerchantValidation({ foo: "bar" }); + session.completePayment(ApplePaySession.STATUS_SUCCESS); - const total = { + const authorizationResult: ApplePayJS.ApplePayPaymentAuthorizationResult = { + status: ApplePaySession.STATUS_FAILURE, + errors: [ + { + code: "addressUnserviceable", + contactField: "postalCode", + message: "The specified postal code cannot be delivered to." + } + ] + }; + + session.completePayment(authorizationResult); + + const total: ApplePayJS.ApplePayLineItem = { label: "Subtotal", type: "final", amount: "35.00" }; - const lineItems = [ + const lineItems: ApplePayJS.ApplePayLineItem[] = [ { label: "Subtotal", type: "final", @@ -97,11 +113,12 @@ describe("ApplePaySession", () => { { label: "Free Shipping", amount: "0.00", - type: "pending" + type: "final" }, { label: "Estimated Tax", - amount: "3.06" + amount: "3.06", + type: "pending" } ]; @@ -120,17 +137,35 @@ describe("ApplePaySession", () => { session.completePaymentMethodSelection(total, lineItems); + const paymentUpdate = { + newTotal: total + }; + + session.completePaymentMethodSelection(paymentUpdate); + session.completeShippingContactSelection( ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS, shippingMethods, total, lineItems); + const contactUpdate = { + newTotal: total + }; + + session.completeShippingContactSelection(contactUpdate); + session.completeShippingMethodSelection( ApplePaySession.STATUS_SUCCESS, total, lineItems); + const shippingUpdate = { + newTotal: total + }; + + session.completeShippingMethodSelection(shippingUpdate); + session.oncancel = (event: ApplePayJS.Event): void => { event.cancelBubble = true; }; @@ -201,7 +236,9 @@ describe("ApplePayPaymentRequest", () => { "1 Infinite Loop" ], locality: "Cupertino", + subLocality: "", administrativeArea: "CA", + subAdministrativeArea: "", postalCode: "95014", country: "United States", countryCode: "US" @@ -233,7 +270,7 @@ describe("ApplePayPaymentRequest", () => { "postalAddress", "name", "phone", - "email" + "name" ]; paymentRequest.shippingContact = { @@ -241,11 +278,15 @@ describe("ApplePayPaymentRequest", () => { familyName: "Patel", givenName: "Ravi", phoneNumber: "(408) 555-5555", + phoneticFamilyName: "Patel", + phoneticGivenName: "Ravi", addressLines: [ "1 Infinite Loop" ], locality: "Cupertino", + subLocality: "", administrativeArea: "CA", + subAdministrativeArea: "", postalCode: "95014", country: "United States", countryCode: "US" @@ -265,5 +306,6 @@ describe("ApplePayPaymentRequest", () => { ]; paymentRequest.shippingType = "storePickup"; + paymentRequest.shippingType = "delivery"; }); }); diff --git a/types/applepayjs/index.d.ts b/types/applepayjs/index.d.ts index f705a4fad2..a37f60b6fd 100644 --- a/types/applepayjs/index.d.ts +++ b/types/applepayjs/index.d.ts @@ -1,26 +1,26 @@ -// Type definitions for Apple Pay JS 1.0 +// Type definitions for Apple Pay JS 3.0 // Project: https://developer.apple.com/reference/applepayjs -// Definitions by: Martin Costello +// Definitions by: Martin Costello // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** - * A session object for managing the payment process on the web. + * ApplePaySession is the entry point for Apple Pay on the web. */ declare class ApplePaySession extends EventTarget { /** - * Creates a new instance of the ApplePaySession class. - * @param version - The version of the ApplePay JS API you are using. - * @param paymentRequest - An ApplePayPaymentRequest object that contains the information that is displayed on the Apple Pay payment sheet. + * The entry point for Apple Pay on the web. + * @param version - The version number of the ApplePay JS API you are using. The current API version number is 3. + * @param paymentRequest - An ApplePayPaymentRequest object that contains the information to be displayed on the Apple Pay payment sheet. */ constructor(version: number, paymentRequest: ApplePayJS.ApplePayPaymentRequest); /** - * A callback function that is automatically called when the payment UI is dismissed with an error. + * A callback function that is automatically called when the payment UI is dismissed. */ oncancel: (event: ApplePayJS.Event) => void; /** - * A callback function that is automatically called when the user has authorized the Apple Pay payment, typically via TouchID. + * A callback function that is automatically called when the user has authorized the Apple Pay payment with Touch ID, Face ID, or passcode. */ onpaymentauthorized: (event: ApplePayJS.ApplePayPaymentAuthorizedEvent) => void; @@ -45,28 +45,28 @@ declare class ApplePaySession extends EventTarget { onvalidatemerchant: (event: ApplePayJS.ApplePayValidateMerchantEvent) => void; /** - * Indicates whether or not the device supports Apple Pay. + * Indicates whether the device supports Apple Pay. * @returns true if the device supports making payments with Apple Pay; otherwise, false. */ static canMakePayments(): boolean; /** - * Indicates whether or not the device supports Apple Pay and if the user has an active card in Wallet. - * @param merchantIdentifier - The merchant ID received when the merchant enrolled in Apple Pay. - * @returns true if the device supports Apple Pay and there is at least one active card in Wallet; otherwise, false. + * Indicates whether the device supports Apple Pay and whether the user has an active card in Wallet. + * @param merchantIdentifier - The merchant ID created when the merchant enrolled in Apple Pay. + * @returns true if the device supports Apple Pay and there is at least one active card in Wallet that is qualified for payments on the web; otherwise, false. */ static canMakePaymentsWithActiveCard(merchantIdentifier: string): Promise; /** * Displays the Set up Apple Pay button. - * @param merchantIdentifier - The merchant ID received when the merchant enrolled in Apple Pay. + * @param merchantIdentifier - The merchant ID created when the merchant enrolled in Apple Pay. * @returns A boolean value indicating whether setup was successful. */ static openPaymentSetup(merchantIdentifier: string): Promise; /** - * Verifies if a web browser supports a given Apple Pay JS API version. - * @param version - A number representing the Apple Pay JS API version being checked. The initial version is 1. + * Verifies whether a web browser supports a given Apple Pay JS API version. + * @param version - A number representing the Apple Pay JS API version being checked. The initial version is 1. The latest version is 3. * @returns A boolean value indicating whether the web browser supports the given API version. Returns false if the web browser does not support the specified version. */ static supportsVersion(version: number): boolean; @@ -82,26 +82,33 @@ declare class ApplePaySession extends EventTarget { begin(): void; /** - * Call after the merchant has been validated. + * Completes the validation for a merchant session. * @param merchantSession - An opaque message session object. */ completeMerchantValidation(merchantSession: any): void; /** - * Call when a payment has been authorized. - * @param status - The status of the payment. + * Completes the payment authorization with a result. + * @param result - The status of the payment, whether it succeeded or failed for Apple Pay JS versions 1 and 2, + * or the result of the payment authorization, including its status and list of errors for Apple Pay JS version 3. */ - completePayment(status: number): void; + completePayment(result: number | ApplePayJS.ApplePayPaymentAuthorizationResult): void; /** - * Call after a payment method has been selected. + * Call after a payment method has been selected for Apple Pay JS versions 1 and 2. * @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase. * @param newLineItems - A sequence of ApplePayLineItem dictionaries. */ completePaymentMethodSelection(newTotal: ApplePayJS.ApplePayLineItem, newLineItems: ApplePayJS.ApplePayLineItem[]): void; /** - * Call after a shipping contact has been selected. + * Completes the selection of a payment method with an update for Apple Pay JS version 3. + * @param update - The updated payment method. + */ + completePaymentMethodSelection(update: ApplePayJS.ApplePayPaymentMethodUpdate): void; + + /** + * Completes the selection of a shipping contact with an update for Apple Pay JS versions 1 and 2. * @param status - The status of the shipping contact update. * @param newShippingMethods - A sequence of ApplePayShippingMethod dictionaries. * @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase. @@ -114,13 +121,25 @@ declare class ApplePaySession extends EventTarget { newLineItems: ApplePayJS.ApplePayLineItem[]): void; /** - * Call after the shipping method has been selected. + * Completes the selection of a shipping contact with an update for Apple Pay JS version 3. + * @param update - The updated shipping contact. + */ + completeShippingContactSelection(update: ApplePayJS.ApplePayShippingContactUpdate): void; + + /** + * Call after the shipping method has been selected for Apple Pay JS versions 1 and 2. * @param status - The status of the shipping method update. * @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase. * @param newLineItems - A sequence of ApplePayLineItem dictionaries. */ completeShippingMethodSelection(status: number, newTotal: ApplePayJS.ApplePayLineItem, newLineItems: ApplePayJS.ApplePayLineItem[]): void; + /** + * Completes the selection of a shipping method with an update for Apple Pay JS version 3. + * @param update - The updated shipping method. + */ + completeShippingMethodSelection(update: ApplePayJS.ApplePayShippingMethodUpdate): void; + /** * The requested action succeeded. */ @@ -163,6 +182,78 @@ declare class ApplePaySession extends EventTarget { } declare namespace ApplePayJS { + /** + * Field names used for requesting contact information in a payment request. + */ + type ApplePayContactField = + 'email' | + 'name' | + 'phone' | + 'postalAddress' | + 'phoneticName'; + + /** + * A customizable error type that you create to indicate problems with the address or contact information on an Apple Pay sheet. + */ + interface ApplePayError { + /** + * The error code for this instance. + */ + code: ApplePayErrorCode; + + /** + * The name of the field that contains the error. + */ + contactField?: ApplePayErrorContactField; + + /** + * A localized, user-facing string that describes the error. + */ + message: string; + } + + /** + * The error code that indicates whether an error on the payment sheet is for shipping or billing information, or for another kind of error. + */ + type ApplePayErrorCode = + /** + * Shipping address or contact information is invalid or missing. + */ + 'shippingContactInvalid' | + + /** + * Billing address information is invalid or missing. + */ + 'billingContactInvalid' | + + /** + * The merchant cannot provide service to the shipping address (for example, can't deliver to a P.O. Box). + */ + 'addressUnserviceable' | + + /** + * An unknown but nonfatal error occurred during payment processing. The user can attempt authorization again. + */ + 'unknown'; + + /** + * Names of the fields in the shipping or billing contact information, used to locate errors in the payment sheet. + */ + type ApplePayErrorContactField = + 'phoneNumber' | + 'emailAddress' | + 'name' | + 'phoneticName' | + 'postalAddress' | + 'addressLines' | + 'locality' | + 'subLocality' | + 'postalCode' | + 'administrativeArea' | + 'subAdministrativeArea' | + 'country' | + 'countryCode'; + /** * Defines a line item in a payment request - for example, total, tax, discount, or grand total. */ @@ -180,15 +271,53 @@ declare namespace ApplePayJS { /** * A value that indicates if the line item is final or pending. */ - type?: string; + type?: ApplePayLineItemType; } + /** + * A type that indicates whether a line item is final or pending. + */ + type ApplePayLineItemType = + /** + * A line item representing the known, final cost. + */ + 'final' | + + /** + * A line item representing an estimated or unknown cost. + */ + 'pending'; + + /** + * The payment capabilities supported by the merchant. + */ + type ApplePayMerchantCapability = + /** + * Required. This value must be supplied. + */ + 'supports3DS' | + + /** + * Include this value only if you support China Union Pay transactions. + */ + 'supportsEMV' | + + /** + * Optional. If present, only transactions that are categorized as credit cards are allowed. + */ + 'supportsCredit' | + + /** + * Optional. If present, only transactions that are categorized as debit cards are allowed. + */ + 'supportsDebit'; + /** * Represents the result of authorizing a payment request and contains encrypted payment information. */ interface ApplePayPayment { /** - * The encrypted token for an authorized payment. + * The encrypted information for an authorized payment. */ token: ApplePayPaymentToken; @@ -208,11 +337,26 @@ declare namespace ApplePayJS { */ abstract class ApplePayPaymentAuthorizedEvent extends Event { /** - * The payment token used to authorize a payment. + * The authorized payment information for this transaction. */ readonly payment: ApplePayPayment; } + /** + * The result of payment authorization, including status and errors. + */ + interface ApplePayPaymentAuthorizationResult { + /** + * The status code for the authorization result. + */ + status: number; + + /** + * A list of custom errors to display on the payment sheet. + */ + errors?: ApplePayError[]; + } + /** * Encapsulates contact information needed for billing and shipping. */ @@ -220,56 +364,76 @@ declare namespace ApplePayJS { /** * An email address for the contact. */ - emailAddress: string; + emailAddress?: string; /** * The contact's family name. */ - familyName: string; + familyName?: string; /** * The contact's given name. */ - givenName: string; + givenName?: string; /** * A phone number for the contact. */ - phoneNumber: string; + phoneNumber?: string; /** - * The address for the contact. + * The phonetic spelling of the contact's family name. */ - addressLines: string[]; + phoneticFamilyName?: string; + + /** + * The phonetic spelling of the contact's given name. + */ + phoneticGivenName?: string; + + /** + * The street portion of the address for the contact. + */ + addressLines?: string[]; /** * The city for the contact. */ - locality: string; + locality?: string; + + /** + * Additional information associated with the location, typically defined at the city or town level (such as district or neighborhood), in a postal address. + */ + subLocality?: string; /** * The state for the contact. */ - administrativeArea: string; + administrativeArea?: string; /** - * The zip code, where applicable, for the contact. + * The subadministrative area (such as a county or other region) in a postal address. */ - postalCode: string; + subAdministrativeArea?: string; /** - * The colloquial country name for the contact. + * The zip code or postal code, where applicable, for the contact. */ - country: string; + postalCode?: string; /** - * The contact's ISO country code. + * The name of the country for the contact. */ - countryCode: string; + country?: string; + + /** + * The contact’s two-letter ISO 3166 country code. + */ + countryCode?: string; } /** - * Contains information about an Apple Pay payment card. + * A dictionary that describes an Apple Pay payment card. */ interface ApplePayPaymentMethod { /** @@ -279,21 +443,29 @@ declare namespace ApplePayJS { /** * A string, suitable for display, that is the name of the payment network backing the card. - * The value is one of the supported networks specified in the supportedNetworks property of the ApplePayPaymentRequest. */ network: string; /** * A value representing the card's type of payment. */ - type: string; + type: ApplePayPaymentMethodType; /** - * The payment pass object associated with the payment. + * The payment pass object currently selected to complete the payment. */ paymentPass: ApplePayPaymentPass; } + /** + * A payment card's type of payment. + */ + type ApplePayPaymentMethodType = + 'debit' | + 'credit' | + 'prepaid' | + 'store'; + /** * The ApplePayPaymentMethodSelectedEvent class defines the attributes contained by the ApplePaySession.onpaymentmethodselected callback function. */ @@ -304,6 +476,21 @@ declare namespace ApplePayJS { readonly paymentMethod: ApplePayPaymentMethod; } + /** + * Updated transaction details resulting from a change in payment method. + */ + interface ApplePayPaymentMethodUpdate { + /** + * An optional list of line items. + */ + newLineItems?: ApplePayLineItem[]; + + /** + * The new total resulting from a change in the payment method. + */ + newTotal: ApplePayLineItem; + } + /** * Represents a provisioned payment card for Apple Pay payments. */ @@ -331,9 +518,38 @@ declare namespace ApplePayJS { /** * The activation state of the pass. */ - activationState: string; + activationState: ApplePayPaymentPassActivationState; } + /** + * Payment pass activation states. + */ + type ApplePayPaymentPassActivationState = + /** + * Active and ready to be used for payment. + */ + 'activated' | + + /** + * Not active but may be activated by the issuer. + */ + 'requiresActivation' | + + /** + * Not ready for use but activation is in progress. + */ + 'activating' | + + /** + * Not active and can't be activated. + */ + 'suspended' | + + /** + * Not active because the issuer has disabled the account associated with the device. + */ + 'deactivated'; + /** * Encapsulates a request for payment, including information about payment processing capabilities, the payment amount, and shipping information. */ @@ -357,7 +573,7 @@ declare namespace ApplePayJS { * The payment capabilities supported by the merchant. * The value must at least contain ApplePayMerchantCapability.supports3DS. */ - merchantCapabilities: string[]; + merchantCapabilities: ApplePayMerchantCapability[]; /** * The payment networks supported by the merchant. @@ -377,12 +593,12 @@ declare namespace ApplePayJS { /** * The billing information that you require from the user in order to process the transaction. */ - requiredBillingContactFields?: string[]; + requiredBillingContactFields?: ApplePayContactField[]; /** * The shipping information that you require from the user in order to fulfill the order. */ - requiredShippingContactFields?: string[]; + requiredShippingContactFields?: ApplePayContactField[]; /** * Shipping contact information for the user. @@ -397,7 +613,12 @@ declare namespace ApplePayJS { /** * How the items are to be shipped. */ - shippingType?: string; + shippingType?: ApplePayShippingType; + + /** + * A list of ISO 3166 country codes for limiting payments to cards from specific countries. + */ + supportedCountries?: string[]; /** * Optional user-defined data. @@ -406,7 +627,7 @@ declare namespace ApplePayJS { } /** - * Contains the user's payment credentials. + * An object that contains the user's payment credentials. */ interface ApplePayPaymentToken { /** @@ -426,7 +647,7 @@ declare namespace ApplePayJS { } /** - * The ApplePayShippingContactSelectedEvent class defines the attributes contained by the ApplePaySession.onshippingcontactselected callback function. + * Encapsulates the attributes contained by the onshippingcontactselected callback function. */ abstract class ApplePayShippingContactSelectedEvent extends Event { /** @@ -435,6 +656,31 @@ declare namespace ApplePayJS { readonly shippingContact: ApplePayPaymentContact; } + /** + * Updated transaction details resulting from a change in shipping contact, including any errors. + */ + class ApplePayShippingContactUpdate { + /** + * List of custom errors to display on the payment sheet. + */ + errors?: ApplePayError[]; + + /** + * An optional list of updated line items. + */ + newLineItems?: ApplePayLineItem[]; + + /** + * A list of shipping methods that are available to the updated shipping contact. + */ + newShippingMethods?: ApplePayShippingMethod[]; + + /** + * The new total resulting from a change in the shipping contact. + */ + newTotal: ApplePayLineItem; + } + /** * Defines a shipping method for delivering physical goods. */ @@ -471,11 +717,35 @@ declare namespace ApplePayJS { } /** - * The ApplePayValidateMerchantEvent class defines the attributes contained by the ApplePaySession.onvalidatemerchant callback function. + * Updated transaction details resulting from a change in shipping method. + */ + interface ApplePayShippingMethodUpdate { + /** + * An optional list of updated line items. + */ + newLineItems?: ApplePayLineItem[]; + + /** + * The new total resulting from a change in the shipping method. + */ + newTotal: ApplePayLineItem; + } + + /** + * A type that indicates how purchased items are to be shipped. + */ + type ApplePayShippingType = + 'shipping' | + 'delivery' | + 'storePickup' | + 'servicePickup'; + + /** + * The attributes contained by the onvalidatemerchant callback function. */ abstract class ApplePayValidateMerchantEvent extends Event { /** - * The URL used to validate the merchant server. + * The URL your server must use to validate itself and obtain a merchant session object. */ readonly validationURL: string; } diff --git a/types/auth0-js/auth0-js-tests.ts b/types/auth0-js/auth0-js-tests.ts index 06d428de20..d425cca21a 100644 --- a/types/auth0-js/auth0-js-tests.ts +++ b/types/auth0-js/auth0-js-tests.ts @@ -109,7 +109,9 @@ webAuth.renewAuth({}, (err, authResult) => {}); webAuth.renewAuth({ nonce: '123', state: '456', - postMessageDataType: 'auth0:silent-authentication' + postMessageDataType: 'auth0:silent-authentication', + usePostMessage: true, + timeout: 30 * 1000 }, (err, authResult) => { // Renewed tokens or error }); diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index 76a2c5f319..340f14e15b 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for Auth0.js 8.10 +// Type definitions for Auth0.js 8.11 // Project: https://github.com/auth0/auth0.js // Definitions by: Adrian Chia // Matt Durrant +// Peter Blazejewicz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace auth0; @@ -525,14 +526,19 @@ export interface Auth0Error { statusText?: string; } +/** + * The contents of the authResult object returned by {@link WebAuth#parseHash } + */ export interface Auth0DecodedHash { accessToken?: string; idToken?: string; idTokenPayload?: any; + appState?: any; refreshToken?: string; state?: string; expiresIn?: number; tokenType?: string; + scope?: string; } /** Represents the response from an API Token Delegation request. */ @@ -667,17 +673,72 @@ export interface ParseHashOptions { } export interface RenewAuthOptions { + /** + * your Auth0 domain + */ domain?: string; + /** + * your Auth0 client identifier obtained when creating the client in the Auth0 Dashboard + */ clientID?: string; + /** + * url that the Auth0 will redirect after Auth with the Authorization Response + */ redirectUri?: string; + /** + * type of the response used by OAuth 2.0 flow. It can be any space separated + * list of the values `code`, `token`, `id_token`. + * {@link https://openid.net/specs/oauth-v2-multiple-response-types-1_0} + */ responseType?: string; + /** + * how the Auth response is encoded and redirected back to the client. + * Supported values are `query`, `fragment` and `form_post`. + * The `query` value is only supported when `responseType` is `code`. + * {@link https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes} + */ responseMode?: string; + /** + * value used to mitigate XSRF attacks. + * {@link https://auth0.com/docs/protocols/oauth2/oauth-state} + */ state?: string; + /** + * value used to mitigate replay attacks when using Implicit Grant. + * {@link https://auth0.com/docs/api-auth/tutorials/nonce} + */ nonce?: string; + /** + * scopes to be requested during Auth. e.g. `openid email` + */ scope?: string; + /** + * identifier of the resource server who will consume the access token issued after Auth + */ audience?: string; - usePostMessage?: boolean; + /** + * identifier data type to look for in postMessage event data, where events are initiated + * from silent callback urls, before accepting a message event is the event expected. + * A value of false means any postMessage event will trigger a callback. + */ postMessageDataType?: string; + /** + * origin of redirectUri to expect postMessage response from. + * Defaults to the origin of the receiving window. Only used if usePostMessage is truthy. + */ + postMessageOrigin?: string; + /** + * value in milliseconds used to timeout when the `/authorize` call is failing + * as part of the silent authentication with postmessage enabled due to a configuration. + */ + timeout?: number; + /** + * use postMessage to comunicate between the silent callback and the SPA. + * When false the SDK will attempt to parse the url hash should ignore the url hash + * and no extra behaviour is needed + * @default false + */ + usePostMessage?: boolean; } export interface AuthorizeOptions { 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/autobind-decorator/autobind-decorator-tests.ts b/types/autobind-decorator/autobind-decorator-tests.ts deleted file mode 100644 index f5a0c76328..0000000000 --- a/types/autobind-decorator/autobind-decorator-tests.ts +++ /dev/null @@ -1,42 +0,0 @@ - -import autobind = require('autobind-decorator'); - -class Test { - public static what: string = 'static'; - - @autobind - public static test(): void { - console.log(this.what); - } - - public constructor(public what: string) { - this.what = what; - } - - @autobind - public test(): void { - console.warn(this.what); - } -} - -const tester: Test = new Test('bind'); -const { test } = tester; -tester.test(); // warns 'bind'. -test(); // warns 'bind'. -Test.test(); // logs 'static'. - -@autobind -class Component { - public constructor(private someMember: string) { - this.someMember = someMember; - } - - public someMethod(): void { - console.error(this.someMember); - } -} - -const component: Component = new Component('React vs Angular2'); -const { someMethod } = component; -component.someMethod(); // errors 'React vs Angular2' -someMethod(); // errors 'React vs Angular2' diff --git a/types/autobind-decorator/index.d.ts b/types/autobind-decorator/index.d.ts deleted file mode 100644 index d8d74bbfec..0000000000 --- a/types/autobind-decorator/index.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Type definitions for autobind-decorator v1.3.3 -// Project: https://github.com/andreypopp/autobind-decorator -// Definitions by: Ivo Stratev -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module 'autobind-decorator' { - function autobind(target: TFunction): TFunction | void; - function autobind(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void; - export = autobind; -} diff --git a/types/autobind-decorator/tslint.json b/types/autobind-decorator/tslint.json deleted file mode 100644 index a41bf5d19a..0000000000 --- a/types/autobind-decorator/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/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index ebd31429de..d21f477be0 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -294,6 +294,9 @@ function callback(cb: AWSLambda.Callback) { cb(null); cb(error); cb(null, anyObj); + cb(null, b); + cb(null, str); + cb(null, num); } /* Proxy Callback */ diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index 3b9e31f14c..d6b50ff5e6 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -9,6 +9,7 @@ // wwwy3y3 // Ishaan Malhi // Daniel Cottone +// Kostya Misura // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -364,7 +365,7 @@ export type CustomAuthorizerHandler = (event: CustomAuthorizerEvent, context: Co * @param error – an optional parameter that you can use to provide results of the failed Lambda function execution. * @param result – an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible. */ -export type Callback = (error?: Error | null, result?: object) => void; +export type Callback = (error?: Error | null, result?: object | boolean | number | string) => void; export type ProxyCallback = (error?: Error | null, result?: ProxyResult) => void; export type CustomAuthorizerCallback = (error?: Error | null, result?: AuthResponse) => void; 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/index.d.ts b/types/backbone/index.d.ts index 1a186d9924..3d4c90d369 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -392,7 +392,7 @@ declare namespace Backbone { decodeFragment(fragment: string): string; getSearch(): string; stop(): void; - route(route: string, callback: Function): number; + route(route: string|RegExp, callback: Function): number; checkUrl(e?: any): void; getPath(): string; matchRoot(): boolean; diff --git a/types/better-scroll/index.d.ts b/types/better-scroll/index.d.ts index 559b21bba2..3f48fed9db 100644 --- a/types/better-scroll/index.d.ts +++ b/types/better-scroll/index.d.ts @@ -1,12 +1,14 @@ -// Type definitions for better-scroll.js 1.3 +// Type definitions for better-scroll.js 1.4 // Project: https://github.com/ustbhuangyi/better-scroll // Definitions by: linxiaowu66 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 interface WheelOption { - selectedIndex?: number; + selectedIndex: number; rotate?: number; adjustTime?: number; + wheelWrapperClass?: string; + wheelItemClass?: string; } interface SlideOption { @@ -16,6 +18,7 @@ interface SlideOption { stepX?: number; stepY?: number; listenFlick?: boolean; + speed?: number; } interface ScrollBarOption { fade?: boolean; @@ -27,6 +30,12 @@ interface PullDownOption { interface PullUpOption { threshold?: number; } +interface PageOption { + x: number; + y: number; + pageX: number; + pageY: number; +} interface BsOption { startX?: number; startY?: number; @@ -62,10 +71,12 @@ interface BsOption { * wheel: { * selectedIndex: 0; * rotate: 25; - * adjustTime: 400 + * adjustTime: 400; + * wheelWrapperClass: 'wheel-scroll'; + * wheelItemClass: 'wheel-item'; * } */ - wheel?: WheelOption | boolean; + wheel?: Partial | boolean; /** * for slide * snap: { @@ -77,14 +88,14 @@ interface BsOption { * listenFlick: true * } */ - snap?: SlideOption | boolean; + snap?: Partial | boolean; /** * for scrollbar * scrollbar: { * fade: true * } */ - scrollbar?: ScrollBarOption | boolean; + scrollbar?: Partial | boolean; /** * for pull down and refresh * pullDownRefresh: { @@ -92,20 +103,30 @@ interface BsOption { * stop: 20 * } */ - pullDownRefresh?: PullDownOption | boolean; + pullDownRefresh?: Partial | boolean; /** * for pull up and load * pullUpLoad: { * threshold: 50 * } */ - pullUpLoad?: PullUpOption | boolean; + pullUpLoad?: Partial | boolean; } declare class BScroll { constructor(element: Element | string, options?: BsOption); // 重新计算 better-scroll,当 DOM 结构发生变化的时候务必要调用确保滚动的效果正常 x: number; y: number; + maxScrollX: number; + maxScrollY: number; + movingDirectionX: number; + movingDirectionY: number; + directionX: number; + directionY: number; + enabled: boolean; + isInTransition: boolean; + isAnimating: boolean; + options: BsOption; refresh(): void; // 启用 better-scroll; 默认 开启 @@ -130,11 +151,11 @@ declare class BScroll { // 滚动到上一个页面 prev(time: number, easing: object): void; // 获取当前页面的信息 - getCurrentPage(): void; + getCurrentPage(): PageOption; // 当我们做 picker 组件的时候,调用该方法可以滚动到索引对应的位置 wheelTo(index: number): void; // 获取当前选中的索引值 - getSelectedIndex(): void; + getSelectedIndex(): number; // 当下拉刷新数据加载完毕后,需要调用此方法告诉 better-scroll 数据已加载 finishPullDown(): void; // 当上拉加载数据加载完毕后,需要调用此方法告诉 better-scroll 数据已加载 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/chai/chai-tests.ts b/types/chai/chai-tests.ts index 0076396422..fba32ec840 100644 --- a/types/chai/chai-tests.ts +++ b/types/chai/chai-tests.ts @@ -1,3 +1,4 @@ +/// import * as chai from "chai"; const expect = chai.expect; @@ -132,7 +133,9 @@ function _typeof() { expect(5).to.be.a('number'); (5).should.be.a('number'); + // tslint:disable-next-line:no-construct expect(new Number(1)).to.be.a('number'); + // tslint:disable-next-line:no-construct (new Number(1)).should.be.a('number'); expect(Number(1)).to.be.a('number'); Number(1).should.be.a('number'); @@ -348,10 +351,6 @@ function eql() { (4).should.eql(3, 'blah'); } -class Buffer { - constructor(arr: number[]) { - } -} function buffer() { expect(new Buffer([1])).to.eql(new Buffer([1])); (new Buffer([1])).should.eql(new Buffer([1])); @@ -726,7 +725,6 @@ function frozen() { Object.freeze({}).should.be.frozen; } - class PoorlyConstructedError { } function _throw() { // See GH-45: some poorly-constructed custom errors don't have useful names @@ -736,11 +734,11 @@ function _throw() { const specificError = new RangeError('boo'); - const goodFn = () => { } - , badFn = () => { throw new Error('testing'); } - , refErrFn = () => { throw new ReferenceError('hello'); } - , ickyErrFn = () => { throw new PoorlyConstructedError(); } - , specificErrFn = () => { throw specificError; }; + const goodFn = () => { }; + const badFn = () => { throw new Error('testing'); }; + const refErrFn = () => { throw new ReferenceError('hello'); }; + const ickyErrFn = () => { throw new PoorlyConstructedError(); }; + const specificErrFn = () => { throw specificError; }; expect(goodFn).to.not.throw(); goodFn.should.not.throw(); @@ -891,7 +889,7 @@ function use() { _chai.can.use.any(); }); - let expect = chai + const expect = chai .use((_chai, util) => {}) .use((_chai, util) => {}) .expect; @@ -1090,7 +1088,7 @@ function oneOf() { expect(obj).to.not.be.oneOf([{ z: 3 }]); } -//tdd +// tdd declare function suite(description: string, action: Function): void; declare function test(description: string, action: Function): void; @@ -1105,9 +1103,8 @@ class CrashyObject { } suite('assert', () => { - test('assert', () => { - const foo: string = 'bar'; + const foo = 'bar' as string; assert(foo === 'bar', 'expected foo to equal `bar`'); assert(foo === 'baz', 'expected foo to equal `bar`'); @@ -1207,26 +1204,26 @@ suite('assert', () => { assert.deepEqual({ tea: 'chai' }, { tea: 'chai' }); assert.deepEqual({ tea: 'chai' }, { tea: 'black' }); - const obja = Object.create({ tea: 'chai' }) - , objb = Object.create({ tea: 'chai' }); + const obja = Object.create({ tea: 'chai' }); + const objb = Object.create({ tea: 'chai' }); assert.deepEqual(obja, objb); - const obj1 = Object.create({ tea: 'chai' }) - , obj2 = Object.create({ tea: 'black' }); + const obj1 = Object.create({ tea: 'chai' }); + const obj2 = Object.create({ tea: 'black' }); assert.deepEqual(obj1, obj2); }); test('deepEqual (ordering)', () => { - const a = { a: 'b', c: 'd' } - , b = { c: 'd', a: 'b' }; + const a = { a: 'b', c: 'd' }; + const b = { c: 'd', a: 'b' }; assert.deepEqual(a, b); }); test('deepEqual (circular)', () => { - const circularObject: any = {} - , secondCircularObject: any = {}; + const circularObject: any = {}; + const secondCircularObject: any = {}; circularObject.field = circularObject; secondCircularObject.field = secondCircularObject; @@ -1242,8 +1239,8 @@ suite('assert', () => { }); test('notDeepEqual (circular)', () => { - const circularObject: any = {} - , secondCircularObject: any = { tea: 'jasmine' }; + const circularObject: any = {}; + const secondCircularObject: any = { tea: 'jasmine' }; circularObject.field = circularObject; secondCircularObject.field = secondCircularObject; @@ -1309,6 +1306,7 @@ suite('assert', () => { test('isString', () => { assert.isString('Foo'); + // tslint:disable-next-line:no-construct assert.isString(new String('foo')); assert.isString(1); }); @@ -1357,6 +1355,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); @@ -1498,7 +1546,6 @@ suite('assert', () => { assert.sameMembers([1, 54], [6, 1, 54]); }); - test('isAbove', () => { assert.isAbove(10, 5); assert.isAbove(1, 5); @@ -1688,7 +1735,7 @@ suite('assert', () => { 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 Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); assert.hasAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); }); @@ -1697,8 +1744,8 @@ suite('assert', () => { 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 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']); }); @@ -1706,21 +1753,21 @@ suite('assert', () => { 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 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 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 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'}]); @@ -1728,28 +1775,28 @@ suite('assert', () => { 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 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 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 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 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 340d69f7cd..8c19f1f54a 100644 --- a/types/chai/index.d.ts +++ b/types/chai/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for chai 4.0.0 +// Type definitions for chai 4.0 // Project: http://chaijs.com/ // Definitions by: Jed Mao , // Bart van der Schoor , @@ -7,12 +7,12 @@ // Matt Wistrand , // Josh Goldberg // Shaun Luttin +// Gintautas Miselis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // declare namespace Chai { - interface ChaiStatic { expect: ExpectStatic; should(): Should; @@ -54,8 +54,7 @@ declare namespace Chai { } interface ShouldThrow { - (actual: Function): void; - (actual: Function, expected: string|RegExp, message?: string): void; + (actual: Function, expected?: string|RegExp, message?: string): void; (actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void; } @@ -218,9 +217,7 @@ declare namespace Chai { } interface Include { - (value: Object, message?: string): Assertion; - (value: string, message?: string): Assertion; - (value: number, message?: string): Assertion; + (value: Object | string | number, message?: string): Assertion; keys: Keys; deep: Deep; ordered: Ordered; @@ -235,18 +232,12 @@ declare namespace Chai { interface Keys { (...keys: string[]): Assertion; - (keys: any[]): Assertion; - (keys: Object): Assertion; + (keys: any[]|Object): Assertion; } interface Throw { - (): Assertion; - (expected: string, message?: string): Assertion; - (expected: RegExp, message?: string): Assertion; - (constructor: Error, expected?: string, message?: string): Assertion; - (constructor: Error, expected?: RegExp, message?: string): Assertion; - (constructor: Function, expected?: string, message?: string): Assertion; - (constructor: Function, expected?: RegExp, message?: string): Assertion; + (expected?: string|RegExp, message?: string): Assertion; + (constructor: Error|Function, expected?: string|RegExp, message?: string): Assertion; } interface RespondTo { @@ -697,21 +688,134 @@ declare namespace Chai { /** * Asserts that haystack does not include needle. * + * @param haystack Container string or array. + * @param needle Potential expected substring of haystack. + * @param message Message to display on error. + */ + notInclude(haystack: string | 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. */ - notInclude(haystack: string, needle: any, message?: string): void; + deepInclude(haystack: string, needle: string, message?: string): void; /** - * Asserts that haystack does not include needle. + * 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. * - * @type T Type of values in haystack. - * @param haystack Container array. - * @param needle Potential value contained in haystack. + * @param haystack + * @param needle * @param message Message to display on error. */ - notInclude(haystack: any[], needle: any, message?: string): void; + 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 or array. + * @param needle Potential expected substring of haystack. + * @param message Message to display on error. + */ + notDeepInclude(haystack: string | 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. @@ -881,19 +985,10 @@ declare namespace Chai { * Asserts that function will throw an error with message matching regexp. * * @param fn Function that may throw. - * @param regExp Potential expected message match. + * @param errType Potential expected message match or error constructor. * @param message Message to display on error. */ - throws(fn: Function, regExp: RegExp, message?: string): void; - - /** - * Asserts that function will throw an error that is an instance of constructor. - * - * @param fn Function that may throw. - * @param constructor Potential expected error constructor. - * @param message Message to display on error. - */ - throws(fn: Function, errType: Function, message?: string): void; + throws(fn: Function, errType: RegExp|Function, message?: string): void; /** * Asserts that function will throw an error that is an instance of constructor @@ -1156,7 +1251,7 @@ declare namespace Chai { * @param property Property of object expected to be modified. * @param message Message to display on error. */ - changes(modifier: Function, object: T, property: string /* keyof T */, message?: string): void + changes(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; /** * Asserts that a function does not change the value of a property. @@ -1167,7 +1262,7 @@ declare namespace Chai { * @param property Property of object expected not to be modified. * @param message Message to display on error. */ - doesNotChange(modifier: Function, object: T, property: string /* keyof T */, message?: string): void + doesNotChange(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; /** * Asserts that a function increases an object property. @@ -1178,7 +1273,7 @@ declare namespace Chai { * @param property Property of object expected to be increased. * @param message Message to display on error. */ - increases(modifier: Function, object: T, property: string /* keyof T */, message?: string): void + increases(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; /** * Asserts that a function does not increase an object property. @@ -1189,7 +1284,7 @@ declare namespace Chai { * @param property Property of object expected not to be increased. * @param message Message to display on error. */ - doesNotIncrease(modifier: Function, object: T, property: string /* keyof T */, message?: string): void + doesNotIncrease(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; /** * Asserts that a function decreases an object property. @@ -1200,7 +1295,7 @@ declare namespace Chai { * @param property Property of object expected to be decreased. * @param message Message to display on error. */ - decreases(modifier: Function, object: T, property: string /* keyof T */, message?: string): void + decreases(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; /** * Asserts that a function does not decrease an object property. @@ -1211,7 +1306,7 @@ declare namespace Chai { * @param property Property of object expected not to be decreased. * @param message Message to display on error. */ - doesNotDecrease(modifier: Function, object: T, property: string /* keyof T */, message?: string): void + doesNotDecrease(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; /** * Asserts if value is not a false value, and throws if it is a true value. diff --git a/types/chai/tslint.json b/types/chai/tslint.json index a41bf5d19a..f99183c97d 100644 --- a/types/chai/tslint.json +++ b/types/chai/tslint.json @@ -1,79 +1,14 @@ { "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 + "strict-export-declare-modifiers": false } } diff --git a/types/chart.js/chart.js-tests.ts b/types/chart.js/chart.js-tests.ts index 9ec7fde23f..d1e86fd317 100644 --- a/types/chart.js/chart.js-tests.ts +++ b/types/chart.js/chart.js-tests.ts @@ -44,7 +44,8 @@ const chart: Chart = new Chart(new CanvasRenderingContext2D(), { zeroLineBorderDashOffset: 2 } }] - } + }, + plugins: { arbitraryPlugin: {option: "value"} } } }); chart.update(); diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index f4f4bda40d..7d18eb39a8 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -159,6 +159,7 @@ declare namespace Chart { interface ChartOptions { responsive?: boolean; responsiveAnimationDuration?: number; + aspectRatio?: number; maintainAspectRatio?: boolean; events?: string[]; onClick?(event?: MouseEvent, activeElements?: Array<{}>): any; @@ -175,6 +176,8 @@ declare namespace Chart { cutoutPercentage?: number; circumference?: number; rotation?: number; + // Plugins can require any options + plugins?: any; } interface ChartFontOptions { 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/codemirror/index.d.ts b/types/codemirror/index.d.ts index 8fd9f59148..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. 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/commander/commander-tests.ts b/types/commander/commander-tests.ts deleted file mode 100644 index 46aa77d92c..0000000000 --- a/types/commander/commander-tests.ts +++ /dev/null @@ -1,99 +0,0 @@ -import * as program from 'commander'; - -interface ExtendedOptions extends program.CommandOptions { - isNew: any; -} - -const commandInstance = new program.Command('-f'); -const optionsInstance = new program.Option('-f'); - -const name = program.name(); - -program - .name('set name') - .version('0.0.1') - .option('-p, --peppers', 'Add peppers') - .option('-P, --pineapple', 'Add pineapple') - .option('-b, --bbq', 'Add bbq sauce') - .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') - .parse(process.argv); - -console.log('you ordered a pizza with:'); -if (program['peppers']) console.log(' - peppers'); -if (program['pineapple']) console.log(' - pineapple'); -if (program['bbq']) console.log(' - bbq'); -console.log(' - %s cheese', program['cheese']); - -function range(val: string) { - return val.split('..').map(Number); -} - -function list(val: string) { - return val.split(','); -} - -function collect(val: string, memo: string[]) { - memo.push(val); - return memo; -} - -function increaseVerbosity(v: any, total: number) { - return total + 1; -} - -program - .version('0.0.1') - .usage('[options] ') - .option('-i, --integer ', 'An integer argument', parseInt) - .option('-f, --float ', 'A float argument', parseFloat) - .option('-r, --range ..', 'A range', range) - .option('-l, --list ', 'A list', list) - .option('-o, --optional [value]', 'An optional value') - .option('-c, --collect [value]', 'A repeatable value', collect, []) - .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0) - .parse(process.argv); - -console.log(' int: %j', program['integer']); -console.log(' float: %j', program['float']); -console.log(' optional: %j', program['optional']); -program['range'] = program['range'] || []; -console.log(' range: %j..%j', program['range'][0], program['range'][1]); -console.log(' list: %j', program['list']); -console.log(' collect: %j', program['collect']); -console.log(' verbosity: %j', program['verbose']); -console.log(' args: %j', program['args']); - -program - .version('0.0.1') - .option('-f, --foo', 'enable some foo') - .option('-b, --bar', 'enable some bar') - .option('-B, --baz', 'enable some baz'); - -// must be before .parse() since -// node's emit() is immediate - -program.on('--help', () => { - console.log(' Examples:'); - console.log(''); - console.log(' $ custom-help --help'); - console.log(' $ custom-help -h'); - console.log(''); -}); - -program - .command('allow-unknown-option') - .allowUnknownOption() - .action(() => { - console.log('unknown option is allowed'); - }); - -program - .version('0.0.1') - .arguments(' [env]') - .action((cmd, env) => { - console.log(cmd, env); - }); - -program.parse(process.argv); - -console.log('stuff'); diff --git a/types/commander/index.d.ts b/types/commander/index.d.ts deleted file mode 100644 index c732d43c7c..0000000000 --- a/types/commander/index.d.ts +++ /dev/null @@ -1,299 +0,0 @@ -// Type definitions for commander 2.11 -// Project: https://github.com/visionmedia/commander.js -// Definitions by: Alan Agius , Marcelo Dezem , vvakame -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare class Option { - flags: string; - required: boolean; - optional: boolean; - bool: boolean; - short?: string; - long: string; - description: string; - - /** - * Initialize a new `Option` with the given `flags` and `description`. - * - * @param {string} flags - * @param {string} [description] - */ - constructor(flags: string, description?: string); -} - -declare class Command extends NodeJS.EventEmitter { - [key: string]: any; - - args: string[]; - - /** - * Initialize a new `Command`. - * - * @param {string} [name] - */ - constructor(name?: string); - - /** - * Set the program version to `str`. - * - * This method auto-registers the "-V, --version" flag - * which will print the version number when passed. - * - * @param {string} str - * @param {string} [flags] - * @returns {Command} for chaining - */ - version(str: string, flags?: string): Command; - - /** - * Add command `name`. - * - * The `.action()` callback is invoked when the - * command `name` is specified via __ARGV__, - * and the remaining arguments are applied to the - * function for access. - * - * When the `name` is "*" an un-matched command - * will be passed as the first arg, followed by - * the rest of __ARGV__ remaining. - * - * @example - * program - * .version('0.0.1') - * .option('-C, --chdir ', 'change the working directory') - * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') - * .option('-T, --no-tests', 'ignore test hook') - * - * program - * .command('setup') - * .description('run remote setup commands') - * .action(function() { - * console.log('setup'); - * }); - * - * program - * .command('exec ') - * .description('run the given remote command') - * .action(function(cmd) { - * console.log('exec "%s"', cmd); - * }); - * - * program - * .command('teardown [otherDirs...]') - * .description('run teardown commands') - * .action(function(dir, otherDirs) { - * console.log('dir "%s"', dir); - * if (otherDirs) { - * otherDirs.forEach(function (oDir) { - * console.log('dir "%s"', oDir); - * }); - * } - * }); - * - * program - * .command('*') - * .description('deploy the given env') - * .action(function(env) { - * console.log('deploying "%s"', env); - * }); - * - * program.parse(process.argv); - * - * @param {string} name - * @param {string} [desc] for git-style sub-commands - * @param {CommandOptions} [opts] command options - * @returns {Command} the new command - */ - command(name: string, desc?: string, opts?: commander.CommandOptions): Command; - - /** - * Define argument syntax for the top-level command. - * - * @param {string} desc - * @returns {Command} for chaining - */ - arguments(desc: string): Command; - - /** - * Parse expected `args`. - * - * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. - * - * @param {string[]} args - * @returns {Command} for chaining - */ - parseExpectedArgs(args: string[]): Command; - /** - * Register callback `fn` for the command. - * - * @example - * program - * .command('help') - * .description('display verbose help') - * .action(function() { - * // output help here - * }); - * - * @param {(...args: any[]) => void} fn - * @returns {Command} for chaining - */ - action(fn: (...args: any[]) => void): Command; - - /** - * Define option with `flags`, `description` and optional - * coercion `fn`. - * - * The `flags` string should contain both the short and long flags, - * separated by comma, a pipe or space. The following are all valid - * all will output this way when `--help` is used. - * - * "-p, --pepper" - * "-p|--pepper" - * "-p --pepper" - * - * @example - * // simple boolean defaulting to false - * program.option('-p, --pepper', 'add pepper'); - * - * --pepper - * program.pepper - * // => Boolean - * - * // simple boolean defaulting to true - * program.option('-C, --no-cheese', 'remove cheese'); - * - * program.cheese - * // => true - * - * --no-cheese - * program.cheese - * // => false - * - * // required argument - * program.option('-C, --chdir ', 'change the working directory'); - * - * --chdir /tmp - * program.chdir - * // => "/tmp" - * - * // optional argument - * program.option('-c, --cheese [type]', 'add cheese [marble]'); - * - * @param {string} flags - * @param {string} [description] - * @param {((arg1: any, arg2: any) => void) | RegExp} [fn] function or default - * @param {*} [defaultValue] - * @returns {Command} for chaining - */ - option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command; - option(flags: string, description?: string, defaultValue?: any): Command; - - /** - * Allow unknown options on the command line. - * - * @param {boolean} [arg] if `true` or omitted, no error will be thrown for unknown options. - * @returns {Command} for chaining - */ - allowUnknownOption(arg?: boolean): Command; - - /** - * Parse `argv`, settings options and invoking commands when defined. - * - * @param {string[]} argv - * @returns {Command} for chaining - */ - parse(argv: string[]): Command; - - /** - * Parse options from `argv` returning `argv` void of these options. - * - * @param {string[]} argv - * @returns {ParseOptionsResult} - */ - parseOptions(argv: string[]): commander.ParseOptionsResult; - - /** - * Return an object containing options as key-value pairs - * - * @returns {{[key: string]: string}} - */ - opts(): { [key: string]: string }; - - /** - * Set the description to `str`. - * - * @param {string} str - * @return {(Command | string)} - */ - description(str: string): Command; - description(): string; - - /** - * Set an alias for the command. - * - * @param {string} alias - * @return {(Command | string)} - */ - alias(alias: string): Command; - alias(): string; - - /** - * Set or get the command usage. - * - * @param {string} str - * @return {(Command | string)} - */ - usage(str: string): Command; - usage(): string; - - /** - * Set the name of the command. - * - * @param {string} str - * @return {Command} - */ - name(str: string): Command; - - /** - * Get the name of the command. - * - * @return {string} - */ - name(): string; - - /** - * Output help information for this command. - * - * @param {(str: string) => string} [cb] - */ - outputHelp(cb?: (str: string) => string): void; - - /** Output help information and exit. */ - help(): void; -} - -declare namespace commander { - - interface CommandOptions { - noHelp?: boolean; - isDefault?: boolean; - } - - interface ParseOptionsResult { - args: string[]; - unknown: string[]; - } - - interface CommanderStatic extends Command { - Command: typeof Command; - Option: typeof Option; - CommandOptions: CommandOptions; - ParseOptionsResult: ParseOptionsResult; - } - -} - -declare const commander: commander.CommanderStatic; -export = commander; diff --git a/types/commander/tslint.json b/types/commander/tslint.json deleted file mode 100644 index a41bf5d19a..0000000000 --- a/types/commander/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/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 806443474a..9502f1a63d 100644 --- a/types/cypress/cypress-tests.ts +++ b/types/cypress/cypress-tests.ts @@ -12,6 +12,8 @@ cy .get('.query-button') .contains('Save Form').should('have.class', 'btn'); +cy.location('host'); + cy .get('form') .find('input') diff --git a/types/cypress/index.d.ts b/types/cypress/index.d.ts index 808c765e24..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 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/v3/d3-tests.ts b/types/d3/v3/d3-tests.ts index 87b57e8261..8704448c9b 100644 --- a/types/d3/v3/d3-tests.ts +++ b/types/d3/v3/d3-tests.ts @@ -1051,7 +1051,7 @@ namespace forceCollapsable { var force = d3.layout.force() .on("tick", tick) .charge(function (d) { return d._children ? -d.size / 100 : -30; } ) - .linkDistance(function (d) { return d.target._children ? 80 : 30; } ) + .linkDistance(function (d) { return (d.target as Node)._children ? 80 : 30; } ) .size([w, h - 160]); var vis = d3.select("body").append("svg:svg") @@ -1083,10 +1083,10 @@ namespace forceCollapsable { // Enter any new links. link.enter().insert("svg:line", ".node") .attr("class", "link") - .attr("x1", function (d) { return d.source.x; } ) - .attr("y1", function (d) { return d.source.y; } ) - .attr("x2", function (d) { return d.target.x; } ) - .attr("y2", function (d) { return d.target.y; } ); + .attr("x1", function (d) { return (d.source as Node).x; } ) + .attr("y1", function (d) { return (d.source as Node).y; } ) + .attr("x2", function (d) { return (d.target as Node).x; } ) + .attr("y2", function (d) { return (d.target as Node).y; } ); // Exit any old links. link.exit().remove(); @@ -1114,10 +1114,10 @@ namespace forceCollapsable { } function tick() { - link.attr("x1", function (d) { return d.source.x; } ) - .attr("y1", function (d) { return d.source.y; } ) - .attr("x2", function (d) { return d.target.x; } ) - .attr("y2", function (d) { return d.target.y; } ); + link.attr("x1", function (d) { return (d.source as Node).x; } ) + .attr("y1", function (d) { return (d.source as Node).y; } ) + .attr("x2", function (d) { return (d.target as Node).x; } ) + .attr("y2", function (d) { return (d.target as Node).y; } ); node.attr("cx", function (d) { return d.x; } ) .attr("cy", function (d) { return d.y; } ); @@ -1738,7 +1738,7 @@ namespace forceCollapsable2 { var force = d3.layout.force() .on("tick", tick) .charge(function (d) { return d._children ? -d.size / 100 : -30; } ) - .linkDistance(function (d) { return d.target._children ? 80 : 30; } ) + .linkDistance(function (d) { return (d.target as Node)._children ? 80 : 30; } ) .size([w, h - 160]); var vis = d3.select("body").append("svg:svg") @@ -1770,10 +1770,10 @@ namespace forceCollapsable2 { // Enter any new links. link.enter().insert("svg:line", ".node") .attr("class", "link") - .attr("x1", function (d) { return d.source.x; } ) - .attr("y1", function (d) { return d.source.y; } ) - .attr("x2", function (d) { return d.target.x; } ) - .attr("y2", function (d) { return d.target.y; } ); + .attr("x1", function (d) { return (d.source as Node).x; } ) + .attr("y1", function (d) { return (d.source as Node).y; } ) + .attr("x2", function (d) { return (d.target as Node).x; } ) + .attr("y2", function (d) { return (d.target as Node).y; } ); // Exit any old links. link.exit().remove(); @@ -1801,11 +1801,11 @@ namespace forceCollapsable2 { } function tick() { - link.attr("x1", function (d) { return d.source.x; } ) - .attr("y1", function (d) { return d.source.y; } ) - .attr("x2", function (d) { return d.target.x; } ) - .attr("y2", function (d) { return d.target.y; } ); - + link.attr("x1", function (d) { return (d.source as Node).x; } ) + .attr("y1", function (d) { return (d.source as Node).y; } ) + .attr("x2", function (d) { return (d.target as Node).x; } ) + .attr("y2", function (d) { return (d.target as Node).y; } ); + node.attr("cx", function (d) { return d.x; } ) .attr("cy", function (d) { return d.y; } ); } @@ -2720,3 +2720,34 @@ function testEnterSizeEmpty() { selectionSize = newNodes.size(); } + +// Example from Matthias Jobst http://github.com/MatthiasJobst +// Checks the brush with different Axis types +class BrushAxisTest { + brush: d3.svg.Brush; + constructor() { + let scale = d3.time.scale(); + this.brush = d3.svg.brush() + .x(scale) // the x accessor accepts time scales + .y(scale); // as does y + } + brushes = () => { + let extent = this.brush.extent(); + let brush = d3.svg.brush(); + brush.x(d3.scale.linear()); // Linear scale + brush.y(d3.scale.log()); // Logarithmic scale + // Does not work: + // brush.extent(this.brush.extent()); + // From https://github.com/d3/d3-3.x-api-reference/blob/master/Ordinal-Scales.md#ordinal_rangePoints + let ordinalScale = d3.scale.ordinal() + .domain([1, 2, 3, 4]) + .rangePoints([0, 100]); + let ordinalBrush = d3.svg.brush() + .x(ordinalScale) // Ordinal scale + .y(d3.scale.linear()); + let colorScale = d3.scale.category10(); + let colorBrush = d3.svg.brush() + .x(colorScale) // Color scale + .y(d3.scale.pow()); + } +} \ No newline at end of file diff --git a/types/d3/v3/index.d.ts b/types/d3/v3/index.d.ts index 0fbc7502b0..9a2f9ae34a 100644 --- a/types/d3/v3/index.d.ts +++ b/types/d3/v3/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for d3JS 3.5 // Project: http://d3js.org/ -// Definitions by: Alex Ford , Boris Yankov +// Definitions by: Alex Ford +// Boris Yankov +// Matthias Jobst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Latest patch version of module validated against: 3.5.17 @@ -233,28 +235,30 @@ declare namespace d3 { * @param name the element name to append. May be prefixed (see d3.ns.prefix). * @param before the selector to determine position (e.g., ":first-child") */ - insert(name: string, before: string): Update; + // https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#insert + insert(name: string, before?: string): Update; /** * Inserts a new child to each node in the selection. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. * @param name the element name to append. May be prefixed (see d3.ns.prefix). * @param before a function to determine the node to use as the next sibling */ - insert(name: string, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Update; + // https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#insert + insert(name: string, before?: (datum: Datum, index: number, outerIndex: number) => EventTarget): Update; /** * Inserts a new child to the end of each node in the selection by computing a new node. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. * @param name the function to compute a new child * @param before the selector to determine position (e.g., ":first-child") */ - insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: string): Update; + insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before?: string): Update; /** * Inserts a new child to the end of each node in the selection by computing a new node. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. * @param name the function to compute a new child * @param before a function to determine the node to use as the next sibling */ - insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Update; + insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before?: (datum: Datum, index: number, outerIndex: number) => EventTarget): Update; /** * Removes the elements from the DOM. They are in a detached state and may be re-added (though there is currently no dedicated API for doing so). @@ -429,7 +433,7 @@ declare namespace d3 { /** * Administrivia: JavaScript primitive types, or "things that toString() predictably". */ - export type Primitive = number | string | boolean; + export type Primitive = number | string | boolean ; /** * Administrivia: anything with a valueOf(): number method is comparable, so we allow it in numeric operations @@ -626,28 +630,28 @@ declare namespace d3 { * @param name the element name to append. May be prefixed (see d3.ns.prefix). * @param before the selector to determine position (e.g., ":first-child") */ - insert(name: string, before: string): Selection; + insert(name: string, before?: string): Selection; /** * Inserts a new child to each node in the selection. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. * @param name the element name to append. May be prefixed (see d3.ns.prefix). * @param before a function to determine the node to use as the next sibling */ - insert(name: string, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; + insert(name: string, before?: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; /** * Inserts a new child to the end of each node in the selection by computing a new node. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. * @param name the function to compute a new child * @param before the selector to determine position (e.g., ":first-child") */ - insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: string): Selection; + insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before?: string): Selection; /** * Inserts a new child to the end of each node in the selection by computing a new node. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. * @param name the function to compute a new child * @param before a function to determine the node to use as the next sibling */ - insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; + insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before?: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; /** * Removes the elements from the DOM. They are in a detached state and may be re-added (though there is currently no dedicated API for doing so). @@ -928,28 +932,28 @@ declare namespace d3 { export function flush(): void; } - interface BaseEvent { - type: string; - sourceEvent?: Event; - } + interface BaseEvent { + type: string; + sourceEvent?: Event; + } - /** - * Define a D3-specific ZoomEvent per https://github.com/mbostock/d3/wiki/Zoom-Behavior#event - */ - interface ZoomEvent extends BaseEvent { - scale: number; - translate: [number, number]; - } + /** + * Define a D3-specific ZoomEvent per https://github.com/mbostock/d3/wiki/Zoom-Behavior#event + */ + interface ZoomEvent extends BaseEvent { + scale: number; + translate: [number, number]; + } - /** - * Define a D3-specific DragEvent per https://github.com/mbostock/d3/wiki/Drag-Behavior#on - */ - interface DragEvent extends BaseEvent { - x: number; - y: number; - dx: number; - dy: number; - } + /** + * Define a D3-specific DragEvent per https://github.com/mbostock/d3/wiki/Drag-Behavior#on + */ + interface DragEvent extends BaseEvent { + x: number; + y: number; + dx: number; + dy: number; + } /** * The current event's value. Use this variable in a handler registered with `selection.on`. @@ -1387,8 +1391,8 @@ declare namespace d3 { export function requote(string: string): string; export var rgb: { - new (r: number, g: number, b: number): Rgb; - new (color: string): Rgb; + new(r: number, g: number, b: number): Rgb; + new(color: string): Rgb; (r: number, g: number, b: number): Rgb; (color: string): Rgb; @@ -1408,8 +1412,8 @@ declare namespace d3 { } export var hsl: { - new (h: number, s: number, l: number): Hsl; - new (color: string): Hsl; + new(h: number, s: number, l: number): Hsl; + new(color: string): Hsl; (h: number, s: number, l: number): Hsl; (color: string): Hsl; @@ -1429,8 +1433,8 @@ declare namespace d3 { } export var hcl: { - new (h: number, c: number, l: number): Hcl; - new (color: string): Hcl; + new(h: number, c: number, l: number): Hcl; + new(color: string): Hcl; (h: number, c: number, l: number): Hcl; (color: string): Hcl; @@ -1446,8 +1450,8 @@ declare namespace d3 { } export var lab: { - new (l: number, a: number, b: number): Lab; - new (color: string): Lab; + new(l: number, a: number, b: number): Lab; + new(color: string): Lab; (l: number, a: number, b: number): Lab; (color: string): Lab; @@ -1467,7 +1471,7 @@ declare namespace d3 { export var color: { (): Color; - new (): Color; + new(): Color; }; interface Color { @@ -1681,7 +1685,7 @@ declare namespace d3 { export function category20(): Ordinal; export function category20b(): Ordinal; export function category20b(): Ordinal; - export function category20c(): Ordinal; + export function category20c(): Ordinal; export function category20c(): Ordinal; interface Ordinal { @@ -1818,10 +1822,10 @@ declare namespace d3 { export function format(specifier: string): Format; export module format { - export function multi(formats: Array<[string, (d: Date) => boolean|number]>): Format; + export function multi(formats: Array<[string, (d: Date) => boolean | number]>): Format; export function utc(specifier: string): Format; namespace utc { - export function multi(formats: Array<[string, (d: Date) => boolean|number]>): Format; + export function multi(formats: Array<[string, (d: Date) => boolean | number]>): Format; } export var iso: Format; @@ -2574,42 +2578,47 @@ declare namespace d3 { tickFormat(): (t: any) => string; tickFormat(format: (t: any) => string): Axis; - tickFormat(format:string): Axis; + tickFormat(format: string): Axis; } - export function brush(): Brush; - export function brush(): Brush; + export function brush(): Brush; + export function brush(): Brush; + export function brush(): Brush; + export function brush(): Brush; namespace brush { - interface Scale { - domain(): number[]; - domain(domain: number[]): Scale; + interface Scale { + domain(): S[]; + domain(domain: S[]): Scale; - range(): number[]; - range(range: number[]): Scale; + range(): S[]; + range(range: number[]): Scale; - invert?(y: number): number; + invert?(y: number): S; } } - interface Brush { + interface Brush { (selection: Selection): void; (selection: Transition): void; event(selection: Selection): void; event(selection: Transition): void; - x(): brush.Scale; - x(x: brush.Scale): Brush; + x(): brush.Scale; + x(x: brush.Scale): Brush; + x(x: d3.scale.Ordinal | d3.time.Scale): Brush; - y(): brush.Scale; - y(y: brush.Scale): Brush; + y(): brush.Scale; + y(y: brush.Scale): Brush; + y(x: d3.scale.Ordinal | d3.time.Scale): Brush; - extent(): [number, number] | [[number, number], [number, number]]; - extent(extent: [number, number] | [[number, number], [number, number]]): Brush; + // https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Controls.md#brush_extent + extent(): [X, X] | [Y, Y] | [[X, Y], [X, Y]] | null; + extent(extent: [X, X] | [Y, Y] | [[X, Y], [X, Y]]): Brush; clamp(): boolean | [boolean, boolean]; - clamp(clamp: boolean | [boolean, boolean]): Brush; + clamp(clamp: boolean | [boolean, boolean]): Brush; clear(): void; @@ -2620,10 +2629,10 @@ declare namespace d3 { on(type: 'brushend'): (datum: T, index: number) => void; on(type: string): (datum: T, index: number) => void; - on(type: 'brushstart', listener: (datum: T, index: number) => void): Brush; - on(type: 'brush', listener: (datum: T, index: number) => void): Brush; - on(type: 'brushend', listener: (datum: T, index: number) => void): Brush; - on(type: string, listener: (datum: T, index: number) => void): Brush; + on(type: 'brushstart', listener: (datum: T, index: number) => void): Brush; + on(type: 'brush', listener: (datum: T, index: number) => void): Brush; + on(type: 'brushend', listener: (datum: T, index: number) => void): Brush; + on(type: string, listener: (datum: T, index: number) => void): Brush; } } @@ -2759,7 +2768,7 @@ declare namespace d3 { timeFormat: { (specifier: string): time.Format; utc(specifier: string): time.Format; - multi(formats: Array<[string, (d: Date) => boolean|number]>): time.Format; + multi(formats: Array<[string, (d: Date) => boolean | number]>): time.Format; } } @@ -2874,10 +2883,12 @@ declare namespace d3 { export function force(): Force, Node>; export function force, Node extends force.Node>(): Force; + // https://github.com/d3/d3-3.x-api-reference/blob/master/Force-Layout.md#links + // Read the note at the end of the section where it talks about initial numbering namespace force { interface Link { - source: T; - target: T; + source: T | number; + target: T | number; } interface Node { diff --git a/types/datatables.net/datatables.net-tests.ts b/types/datatables.net/datatables.net-tests.ts index af722ab74f..e5cb5184fd 100644 --- a/types/datatables.net/datatables.net-tests.ts +++ b/types/datatables.net/datatables.net-tests.ts @@ -21,7 +21,13 @@ const lang: DataTables.LanguageSettings = { }, aria: { sortAscending: ": activate to sort column ascending", - sortDescending: ": activate to sort column descending" + sortDescending: ": activate to sort column descending", + paginate: { + first: "First", + last: "Last", + next: "Next", + previous: "Previous" + } } }; @@ -98,6 +104,7 @@ let col: DataTables.ColumnSettings = { orderable: true, orderData: 10, orderDataType: "dom-checkbox", + orderFixed: [[0, 'asc'], [1, 'desc']], orderSequence: ['asc', 'desc'], render: 1, searchable: true, @@ -118,6 +125,20 @@ col = { data: colDataFunc, render: colRenderFunc, }; +col = { + data: "salary", + render: $.fn.dataTable.render.number('\'', '.', 0, '$'), +}; +col = { + data: "url", + render: $.fn.dataTable.render.text(), +}; +col = { + orderFixed: { + pre: [[0, 'asc'], [1, 'desc']], + post: [[0, 'asc'], [1, 'desc']] + } +}; //#endregion "Column" @@ -135,6 +156,7 @@ let colDef: DataTables.ColumnDefsSettings = { orderable: true, orderData: 10, orderDataType: "dom-checkbox", + orderFixed: [[0, 'asc'], [1, 'desc']], orderSequence: ['asc', 'desc'], render: 1, searchable: true, @@ -353,6 +375,9 @@ let order_set = dt.order([0, "asc"]); order_set = dt.order([0, "asc"], [1, "desc"]); // TODO: Fíx that order_set = dt.order([[0, "asc"], [1, "desc"]]); +const fixed_get: DataTables.ObjectOrderFixed = dt.order.fixed(); +const fixed_set: DataTables.Api = dt.order.fixed({pre: [0, "asc"], post: [1, "desc"]}); + const orderListerner = order_set.order.listener("node", 1, () => { }); const page_get = dt.page(); @@ -791,6 +816,11 @@ dt.columns.adjust().draw(false); // adjust column sizing and redraw dt.columns().every(() => { }); dt.columns().every((colIdx, tableLoop, colLoop) => { }); +$('#example').on('column-visibility.dt', (e: object, settings: DataTables.Settings, column: number, state: boolean, recalc: boolean | undefined) => { + const widthRecalced = (recalc || recalc === undefined); + console.log(`Column ${column} has changed to ${(state ? 'visible' : 'hidden')} and width ${(widthRecalced) ? 'was' : 'was not'} recalculated.`); +}); + //#endregion "Methods-Column" //#region "Methods-Row" diff --git a/types/datatables.net/index.d.ts b/types/datatables.net/index.d.ts index 7cd4b8589b..cdddc98789 100644 --- a/types/datatables.net/index.d.ts +++ b/types/datatables.net/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for JQuery DataTables 1.10 // Project: http://www.datatables.net -// Definitions by: Kiarash Ghiaseddin , Omid Rad , Armin Sander +// Definitions by: Kiarash Ghiaseddin +// Omid Rad +// Armin Sander +// Craig Boland // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -329,6 +332,16 @@ declare namespace DataTables { (order?: Array<(string | number)> | Array>): Api; (order: Array<(string | number)>, ...args: any[]): Api; + /** + * Get the fixed ordering that is applied to the table. If there is more than one table in the API's context, + * the ordering of the first table will be returned only (use table() if you require the ordering of a different table in the API's context). + */ + fixed(): ObjectOrderFixed; + /** + * Set the table's fixed ordering. Note this doesn't actually perform the order, but rather queues it up - use draw() to perform the ordering. + */ + fixed(order: ObjectOrderFixed): Api; + /** * Add an ordering listener to an element, for a given column. * @@ -1085,6 +1098,14 @@ declare namespace DataTables { */ isDataTable(table: string): boolean; + /** + * Helpers for `columns.render`. + * + * The options defined here can be used with the `columns.render` initialisation + * option to provide a display renderer. + */ + render: StaticRenderFunctions; + /** * Get all DataTable tables that have been initialised - optionally you can select to get only currently visible tables and / or retrieve the tables as API instances. * @@ -1125,6 +1146,42 @@ declare namespace DataTables { ext: ExtSettings; } + interface ObjectColumnRender { + display(d?: number | string | object): string | object; + } + + interface ObjectOrderFixed { + /** + * Two-element array: + * 0: Column index to order upon. + * 1: Direction so order to apply ("asc" for ascending order or "desc" for descending order). + */ + pre?: any[]; + /** + * Two-element array: + * 0: Column index to order upon. + * 1: Direction so order to apply ("asc" for ascending order or "desc" for descending order). + */ + post?: any[]; + } + + interface StaticRenderFunctions { + /** + * Will format numeric data (defined by `columns.data`) for display, retaining the original unformatted data for sorting and filtering. + * + * @param thousands Thousands grouping separator. + * @param decimal Decimal point indicator. + * @param precision Integer number of decimal points to show. + * @param prefix Prefix (optional). + * @param postfix Postfix (/suffix) (optional). + */ + number(thousands: string, decimal: string, precision: number, prefix?: string, postfix?: string): ObjectColumnRender; + /** + * Escape HTML to help prevent XSS attacks. It has no optional parameters. + */ + text(): ObjectColumnRender; + } + interface StaticUtilFunctions { /** * Escape special characters in a regular expression string. Since: 1.10.4 @@ -1563,6 +1620,15 @@ declare namespace DataTables { */ orderDataType?: string; + /** + * Ordering to always be applied to the table. Since 1.10 + * + * Array type is prefix ordering only and is a two-element array: + * 0: Column index to order upon. + * 1: Direction so order to apply ("asc" for ascending order or "desc" for descending order). + */ + orderFixed?: any[] | ObjectOrderFixed; + /** * Order direction application sequence. Since: 1.10 */ @@ -1571,7 +1637,7 @@ declare namespace DataTables { /** * Render (process) the data for use in the table. Since: 1.10 */ - render?: number | string | ObjectColumnData | FunctionColumnRender; + render?: number | string | ObjectColumnData | FunctionColumnRender | ObjectColumnRender; /** * Enable or disable filtering on the data in this column. Since: 1.10 @@ -1727,6 +1793,7 @@ declare namespace DataTables { interface LanguageAriaSettings { sortAscending: string; sortDescending: string; + paginate?: LanguagePaginateSettings; } //#endregion "language-settings" 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/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 index bf273f2f20..0e0678e7d7 100644 --- a/types/ember-data/index.d.ts +++ b/types/ember-data/index.d.ts @@ -993,6 +993,7 @@ declare namespace DS { * 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. @@ -1032,6 +1033,14 @@ declare namespace DS { * 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. diff --git a/types/ember-data/test/adapter.ts b/types/ember-data/test/adapter.ts index d648f73310..5d9d45fd4b 100644 --- a/types/ember-data/test/adapter.ts +++ b/types/ember-data/test/adapter.ts @@ -23,3 +23,34 @@ const AuthTokenHeader = DS.JSONAPIAdapter.extend({ }; }) }); + +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/events/events-tests.ts b/types/events/events-tests.ts new file mode 100644 index 0000000000..ccf89c1402 --- /dev/null +++ b/types/events/events-tests.ts @@ -0,0 +1,60 @@ +import { EventEmitter } from 'events'; + +const emitter = new EventEmitter(); +const listener = () => { + console.log('once'); +}; +const listener1 = () => { + console.log('listener1'); +}; +const listener2 = () => { + console.log('listener2'); +}; +const listener3 = (arg1: string) => { + console.log('listener3', arg1); +}; +const listener4 = () => { + console.log('type of number'); +}; + +emitter.setMaxListeners(100); + +emitter.addListener('send', listener1); + +emitter.on('send', listener2); + +emitter.on('send', listener3); + +emitter.once('send', listener); + +emitter.once(1, listener4); + +emitter.listeners('send'); +emitter.listenerCount('send'); + +EventEmitter.defaultMaxListeners = 100; +console.log(`count(static): ${EventEmitter.listenerCount(emitter, 'send')}`); +console.log(`ncount: ${emitter.listenerCount('send')}`); + +setTimeout(() => { + console.log('\n'); + emitter.emit('send'); +}, 1000); + +setTimeout(() => { + console.log('\n'); + emitter.emit('send'); + emitter.removeListener('send', listener2); +}, 2000); + +setTimeout(() => { + console.log('\n'); + emitter.emit('send', 'params1'); + emitter.removeAllListeners('send'); +}, 3000); + +setTimeout(() => { + console.log('\n'); + emitter.emit(1); + emitter.emit('send'); +}, 3000); diff --git a/types/events/index.d.ts b/types/events/index.d.ts new file mode 100644 index 0000000000..85ce0a7b0e --- /dev/null +++ b/types/events/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for events 1.1 +// Project: https://github.com/Gozala/events +// Definitions by: Yasunori Ohoka +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Listener = (...args: any[]) => void; + +export class EventEmitter { + static listenerCount(emitter: EventEmitter, type: string | number): number; + static defaultMaxListeners: number; + + setMaxListeners(n: number): this; + emit(type: string | number, ...args: any[]): boolean; + addListener(type: string | number, listener: Listener): this; + on(type: string | number, listener: Listener): this; + once(type: string | number, listener: Listener): this; + removeListener(type: string | number, listener: Listener): this; + removeAllListeners(type: string | number): this; + listeners(type: string | number): Listener[]; + listenerCount(type: string | number): number; +} diff --git a/types/events/tsconfig.json b/types/events/tsconfig.json new file mode 100644 index 0000000000..f43a926ad8 --- /dev/null +++ b/types/events/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "events-tests.ts" + ] +} diff --git a/types/events/tslint.json b/types/events/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/events/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fb/index.d.ts b/types/fb/index.d.ts index a968d9f3c0..d48aedee8a 100644 --- a/types/fb/index.d.ts +++ b/types/fb/index.d.ts @@ -83,12 +83,20 @@ interface FeedDialogParams { ref?: any; } -declare type FBUIParams = ShareDialogParams - | PageTabDialogParams - | RequestsDialogParams - | SendDialogParams - | PayDialogParams - | FeedDialogParams; +interface LiveDialogParams { + redirect_uri?: string; + method: string; + display: string; + phase: string; + broadcast_data?: LiveDialogResponse; +} + +interface LiveDialogResponse { + id: string; + stream_url: string; + secure_stream_url: string; + status: string; +} interface FBLoginOptions{ auth_type?: string; @@ -201,8 +209,14 @@ interface FBSDK{ api(path: string, params: any, callback: (response: any) => void): void; api(path: string, method: ApiMethod, params: any, callback: (response: any) => void): void; - /* This method is used to trigger different forms of Facebook created UI dialogs. */ - ui(params : FBUIParams, handler : (fbResponseObject : Object) => any) : void; + /* These methods are used to trigger different forms of Facebook-created UI dialogs. */ + ui(params : ShareDialogParams, handler : (fbResponseObject : Object) => any) : void; + ui(params : PageTabDialogParams, handler : (fbResponseObject : Object) => any) : void; + ui(params : RequestsDialogParams, handler : (fbResponseObject : Object) => any) : void; + ui(params : SendDialogParams, handler : (fbResponseObject : Object) => any) : void; + ui(params : PayDialogParams, handler : (fbResponseObject : Object) => any) : void; + ui(params : FeedDialogParams, handler : (fbResponseObject : Object) => any) : void; + ui(params : LiveDialogParams, handler : (fbResponseObject : LiveDialogResponse) => any) : void; /* Allows you to determine if a user is logged in to Facebook and has authenticated your app */ getLoginStatus(handler : (fbResponseObject : FB.LoginStatusResponse) => any, force?: Boolean) : void; diff --git a/types/format-duration/format-duration-tests.ts b/types/format-duration/format-duration-tests.ts new file mode 100644 index 0000000000..4a08b33119 --- /dev/null +++ b/types/format-duration/format-duration-tests.ts @@ -0,0 +1,5 @@ +import formatDuration = require("format-duration"); + +const milliseconds = 12345; + +const duration: string = formatDuration(milliseconds); diff --git a/types/format-duration/index.d.ts b/types/format-duration/index.d.ts new file mode 100644 index 0000000000..06682200b2 --- /dev/null +++ b/types/format-duration/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for format-duration 1.0 +// Project: https://github.com/ungoldman/format-duration +// Definitions by: Giles Roadnight +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function formatDuration(ms: number): string; + +export = formatDuration; diff --git a/types/autobind-decorator/tsconfig.json b/types/format-duration/tsconfig.json similarity index 69% rename from types/autobind-decorator/tsconfig.json rename to types/format-duration/tsconfig.json index 0b05ea04fb..f17a4f7c6c 100644 --- a/types/autobind-decorator/tsconfig.json +++ b/types/format-duration/tsconfig.json @@ -1,17 +1,14 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", - "experimentalDecorators": true, "typeRoots": [ "../" ], @@ -21,6 +18,6 @@ }, "files": [ "index.d.ts", - "autobind-decorator-tests.ts" + "format-duration-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/format-duration/tslint.json b/types/format-duration/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/format-duration/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fuzzaldrin/fuzzaldrin-tests.ts b/types/fuzzaldrin/fuzzaldrin-tests.ts new file mode 100644 index 0000000000..90ec26e3e0 --- /dev/null +++ b/types/fuzzaldrin/fuzzaldrin-tests.ts @@ -0,0 +1,20 @@ +import { match, filter, score } from 'fuzzaldrin'; + +let number = 0; +const string = '' as string; +let strings: string[] = []; +let objects: Array<{name: string, speed: number}> = []; + +strings = filter(strings, string); +strings = filter(strings, string, {maxResults: number}); +objects = filter(objects, string, {key: 'name'}); +objects = filter(objects, string, {key: 'name', maxResults: number}); + +number = score(string, string); + +match(string, string); + +// These should be type errors! Uncomment to verify. +// objects = filter(objects, string); +// objects = filter(objects, string, {key: 'speed'}); +// strings = filter(strings, string, {key: 'speed'}); diff --git a/types/fuzzaldrin/index.d.ts b/types/fuzzaldrin/index.d.ts index 1e1427c08f..ca9a64e819 100644 --- a/types/fuzzaldrin/index.d.ts +++ b/types/fuzzaldrin/index.d.ts @@ -2,7 +2,9 @@ // Project: https://github.com/atom/fuzzaldrin // Definitions by: Mohamed Hegazy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 -export function filter(candidates: T[], query: string, options?: { key?: string, maxResults?: number }): T[]; +export function filter(candidates: string[], query: string, options?: {maxResults?: number}): string[]; +export function filter(candidates: T[], query: string & T[K], options: {key: K, maxResults?: number}): T[]; export function match(string: string, query: string): any; export function score(string: string, query: string): number; diff --git a/types/fuzzaldrin/tsconfig.json b/types/fuzzaldrin/tsconfig.json index abf333c6bf..2e1263faf8 100644 --- a/types/fuzzaldrin/tsconfig.json +++ b/types/fuzzaldrin/tsconfig.json @@ -17,6 +17,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts" + "index.d.ts", + "fuzzaldrin-tests.ts" ] -} \ No newline at end of file +} 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/glob-stream/glob-stream-tests.ts b/types/glob-stream/glob-stream-tests.ts index 617246799c..ca436746cc 100644 --- a/types/glob-stream/glob-stream-tests.ts +++ b/types/glob-stream/glob-stream-tests.ts @@ -2,9 +2,24 @@ import gs = require('glob-stream'); var read: NodeJS.ReadableStream; -read = gs.create('xx'); -read = gs.create('xx', {}); -read = gs.create(['xx'], {}); -read = gs.create(['xx'], {cwd: 'xx'}); -read = gs.create(['xx'], {base: 'xx'}); -read = gs.create(['xx'], {cwdbase: true}); +// Types +var strPredicate: gs.UniqueByStringPredicate = 'base'; +var fnPredicate: gs.UniqueByFunctionPredicate = (entry) => entry.path; + +// Base cases +read = gs('xx'); +read = gs('xx', {}); +read = gs(['xx'], {}); + +// Package options +read = gs(['xx'], { allowEmpty: true }); +read = gs(['xx'], { base: 'xx' }); +read = gs(['xx'], { cwdbase: true }); +read = gs(['xx'], { uniqueBy: 'path' }); +read = gs(['xx'], { uniqueBy: 'base' }); +read = gs(['xx'], { uniqueBy: 'cwd' }); +read = gs(['xx'], { uniqueBy: (entry: gs.Entry) => entry.path }); + +// Glob options +read = gs(['xx'], { root: 'root' }); +read = gs(['xx'], { debug: true }); diff --git a/types/glob-stream/index.d.ts b/types/glob-stream/index.d.ts index 36a5d9fb92..d9d9c6d7c6 100644 --- a/types/glob-stream/index.d.ts +++ b/types/glob-stream/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for glob-stream v3.1.12 +// Type definitions for glob-stream v6.1.0 // Project: https://github.com/wearefractal/glob-stream // Definitions by: Bart van der Schoor +// mrmlnc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -8,17 +9,40 @@ import glob = require('glob'); -export interface Options extends glob.IOptions { - cwd?: string; - base?: string; - cwdbase?: boolean; +declare function GlobStream(glob: string | string[]): NodeJS.ReadableStream; +declare function GlobStream(glob: string | string[], options: GlobStream.Options): NodeJS.ReadableStream; + +declare namespace GlobStream { + export interface Entry { + cwd: string; + base: string; + path: string; + } + + export type UniqueByStringPredicate = 'cwd' | 'base' | 'path'; + export type UniqueByFunctionPredicate = (entry: Entry) => string; + + export interface Options extends glob.IOptions { + /** + * Whether or not to error upon an empty singular glob. + */ + allowEmpty?: boolean; + /** + * The absolute segment of the glob path that isn't a glob. This value is attached + * to each globobject and is useful for relative pathing. + */ + base?: string; + /** + * Whether or not the `cwd` and `base` should be the same. + */ + cwdbase?: boolean; + /** + * Filters stream to remove duplicates based on the string property name or the result of function. + * When using a function, the function receives the streamed + * data (objects containing `cwd`, `base`, `path` properties) to compare against. + */ + uniqueBy?: UniqueByStringPredicate | UniqueByFunctionPredicate; + } } -export interface Element { - cwd: string; - base: string; - path: string; -} - -export declare function create(glob: string, opts?: Options): NodeJS.ReadableStream; -export declare function create(globs: string[], opts?: Options): NodeJS.ReadableStream; +export = GlobStream; 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/hapi-auth-basic/hapi-auth-basic-tests.ts b/types/hapi-auth-basic/hapi-auth-basic-tests.ts index 7f78fe9f65..1a7192af6f 100644 --- a/types/hapi-auth-basic/hapi-auth-basic-tests.ts +++ b/types/hapi-auth-basic/hapi-auth-basic-tests.ts @@ -22,21 +22,22 @@ const users: {[index: string]: User} = { } }; -const validate: Basic.ValidateFunc = function (request, username, password, callback) { +const validate: Basic.Validate = async (request, username, password, h) => { const user = users[username]; if (!user) { - return callback(null, false); + return { isValid: false, credentials: null }; } - Bcrypt.compare(password, user.password, (err, isValid) => { + let isValid = await Bcrypt.compare(password, user.password) - callback(err, isValid, { id: user.id, name: user.name }); - }); + return { isValid, credentials: { id: user.id, name: user.name } }; }; -server.register(Basic, (err) => { +server.register(Basic).then(() => { + + server.auth.strategy('simple', 'basic', { validate }); + server.auth.default('simple'); - server.auth.strategy('simple', 'basic', { validateFunc: validate }); server.route({ method: 'GET', path: '/', config: { auth: 'simple' } }); }); diff --git a/types/hapi-auth-basic/index.d.ts b/types/hapi-auth-basic/index.d.ts index 54d463c2b3..ddf05c348a 100644 --- a/types/hapi-auth-basic/index.d.ts +++ b/types/hapi-auth-basic/index.d.ts @@ -1,18 +1,24 @@ -// Type definitions for hapi 4.2 +// Type definitions for hapi-bauth-basic 5.0.0 // Project: https://github.com/hapijs/hapi-auth-basic // Definitions by: AJP +// Rodrigo Saboya // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 import * as Hapi from 'hapi'; declare namespace Basic { - interface ValidateFuncCallback { - (err: Error | null, isValid: boolean, userCredentials?: any): void; + interface ValidateCustomResponse { + response: any, } - interface ValidateFunc { - (request: Hapi.Request, username: string, password: string, callback: ValidateFuncCallback): void; + interface ValidateResponse { + isValid: boolean, + credentials?: any, + } + + interface Validate { + (request: Hapi.Request, username: string, password: string, h: object): Promise; } } 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/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/ignore-styles/ignore-styles-tests.ts b/types/ignore-styles/ignore-styles-tests.ts new file mode 100644 index 0000000000..1a7dbc74c1 --- /dev/null +++ b/types/ignore-styles/ignore-styles-tests.ts @@ -0,0 +1,15 @@ +import register, { DEFAULT_EXTENSIONS, oldHandlers, noOp, restore } from 'ignore-styles'; + +register(['.css'], (module, filename) => {}); // $ExpectType void +register(['.css']); // $ExpectType void +register(undefined, (module, filename) => {}); // $ExpectType void +register([1], (module, filename) => {}); // $ExpectError +register(['.css'], 1); // $ExpectError + +DEFAULT_EXTENSIONS[0]; // $ExpectType string + +oldHandlers['.css']; // $ExpectType Handler + +noOp(); // $ExpectType void + +restore(); // $ExpectType void diff --git a/types/ignore-styles/index.d.ts b/types/ignore-styles/index.d.ts new file mode 100644 index 0000000000..2eab90b591 --- /dev/null +++ b/types/ignore-styles/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for ignore-styles 5.0 +// Project: https://github.com/bkonkle/ignore-styles +// Definitions by: Taiju Muto +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +export type Handler = (m: NodeModule, filename: string) => any; + +export const DEFAULT_EXTENSIONS: string[]; + +export let oldHandlers: { + [ext: string]: Handler +}; + +export function noOp(): void; + +export function restore(): void; + +export default function register( + extensions?: string[], + handler?: Handler +): void; diff --git a/types/ignore-styles/tsconfig.json b/types/ignore-styles/tsconfig.json new file mode 100644 index 0000000000..aed3487cf4 --- /dev/null +++ b/types/ignore-styles/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", + "ignore-styles-tests.ts" + ] +} diff --git a/types/ignore-styles/tslint.json b/types/ignore-styles/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ignore-styles/tslint.json @@ -0,0 +1 @@ +{ "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/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/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/commander/tsconfig.json b/types/jschannel/tsconfig.json similarity index 86% rename from types/commander/tsconfig.json rename to types/jschannel/tsconfig.json index dcb92cc920..83727a281c 100644 --- a/types/commander/tsconfig.json +++ b/types/jschannel/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "commander-tests.ts" + "jschannel-tests.ts" ] -} \ No newline at end of file +} 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/json-schema/index.d.ts b/types/json-schema/index.d.ts index 016db75a25..7f02b671a0 100644 --- a/types/json-schema/index.d.ts +++ b/types/json-schema/index.d.ts @@ -1,10 +1,10 @@ -// Type definitions for json-schema 4.0 +// Type definitions for json-schema 4.0 and 6.0 // Project: https://www.npmjs.com/package/json-schema -// Definitions by: Boris Cherny +// Definitions by: Boris Cherny , Cyrille Tuzi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -/// +/* JSON Schema 4 */ /** * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1 @@ -198,3 +198,276 @@ export interface JSONSchema4 { */ [k: string]: any } + +/* JSON Schema 6 */ + +export type JSONSchema6TypeName = 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array' | 'null' | 'any' + +export type JSONSchema6Type = any[] | boolean | number | null | object | string + +/** + * JSON Schema V6 + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01 + */ +export interface JSONSchema6 { + $id?: string + $ref?: string + $schema?: 'http://json-schema.org/schema#' | 'http://json-schema.org/hyper-schema#' | + 'http://json-schema.org/draft-06/schema#' | 'http://json-schema.org/draft-06/hyper-schema#' + + /** + * Must be strictly greater than 0. + * A numeric instance is valid only if division by this keyword's value results in an integer. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.1 + */ + multipleOf?: number + + /** + * Representing an inclusive upper limit for a numeric instance. + * This keyword validates only if the instance is less than or exactly equal to "maximum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.2 + */ + maximum?: number + + /** + * Representing an exclusive upper limit for a numeric instance. + * This keyword validates only if the instance is strictly less than (not equal to) to "exclusiveMaximum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.3 + */ + exclusiveMaximum?: number + + /** + * Representing an inclusive lower limit for a numeric instance. + * This keyword validates only if the instance is greater than or exactly equal to "minimum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.4 + */ + minimum?: number + + /** + * Representing an exclusive lower limit for a numeric instance. + * This keyword validates only if the instance is strictly greater than (not equal to) to "exclusiveMinimum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.5 + */ + exclusiveMinimum?: number + + /** + * Must be a non-negative integer. + * A string instance is valid against this keyword if its length is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.6 + */ + maxLength?: number + + /** + * Must be a non-negative integer. + * A string instance is valid against this keyword if its length is greater than, or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.7 + */ + minLength?: number + + /** + * Should be a valid regular expression, according to the ECMA 262 regular expression dialect. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.8 + */ + pattern?: string + + /** + * This keyword determines how child instances validate for arrays, and does not directly validate the immediate instance itself. + * Omitting this keyword has the same behavior as an empty schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.9 + */ + items?: boolean | JSONSchema6 | JSONSchema6[] + + /** + * This keyword determines how child instances validate for arrays, and does not directly validate the immediate instance itself. + * If "items" is an array of schemas, validation succeeds if every instance element + * at a position greater than the size of "items" validates against "additionalItems". + * Otherwise, "additionalItems" MUST be ignored, as the "items" schema + * (possibly the default value of an empty schema) is applied to all elements. + * Omitting this keyword has the same behavior as an empty schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.10 + */ + additionalItems?: boolean | JSONSchema6 + + /** + * Must be a non-negative integer. + * An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.11 + */ + maxItems?: number + + /** + * Must be a non-negative integer. + * An array instance is valid against "maxItems" if its size is greater than, or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.12 + */ + minItems?: number + + /** + * If this keyword has boolean value false, the instance validates successfully. + * If it has boolean value true, the instance validates successfully if all of its elements are unique. + * Omitting this keyword has the same behavior as a value of false. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.13 + */ + uniqueItems?: boolean + + /** + * An array instance is valid against "contains" if at least one of its elements is valid against the given schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.14 + */ + contains?: boolean | JSONSchema6 + + /** + * Must be a non-negative integer. + * An object instance is valid against "maxProperties" if its number of properties is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.15 + */ + maxProperties?: number + + /** + * Must be a non-negative integer. + * An object instance is valid against "maxProperties" if its number of properties is greater than, + * or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.16 + */ + minProperties?: number + + /** + * Elements of this array must be unique. + * An object instance is valid against this keyword if every item in the array is the name of a property in the instance. + * Omitting this keyword has the same behavior as an empty array. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.17 + */ + required?: string[] + + /** + * This keyword determines how child instances validate for objects, and does not directly validate the immediate instance itself. + * Validation succeeds if, for each name that appears in both the instance and as a name within this keyword's value, + * the child instance for that name successfully validates against the corresponding schema. + * Omitting this keyword has the same behavior as an empty object. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.18 + */ + properties?: { + [k: string]: boolean | JSONSchema6 + } + + /** + * This attribute is an object that defines the schema for a set of property names of an object instance. + * The name of each property of this attribute's object is a regular expression pattern in the ECMA 262, while the value is a schema. + * If the pattern matches the name of a property on the instance object, the value of the instance's property + * MUST be valid against the pattern name's schema value. + * Omitting this keyword has the same behavior as an empty object. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.19 + */ + patternProperties?: { + [k: string]: boolean | JSONSchema6 + } + + /** + * This attribute defines a schema for all properties that are not explicitly defined in an object type definition. + * If specified, the value MUST be a schema or a boolean. + * If false is provided, no additional properties are allowed beyond the properties defined in the schema. + * The default value is an empty schema which allows any value for additional properties. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.20 + */ + additionalProperties?: boolean | JSONSchema6 + + /** + * This keyword specifies rules that are evaluated if the instance is an object and contains a certain property. + * Each property specifies a dependency. + * If the dependency value is an array, each element in the array must be unique. + * Omitting this keyword has the same behavior as an empty object. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.21 + */ + dependencies?: { + [k: string]: boolean | JSONSchema6 | string[] + } + + /** + * Takes a schema which validates the names of all properties rather than their values. + * Note the property name that the schema is testing will always be a string. + * Omitting this keyword has the same behavior as an empty schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.22 + */ + propertyNames?: boolean | JSONSchema6 + + /** + * This provides an enumeration of all possible values that are valid + * for the instance property. This MUST be an array, and each item in + * the array represents a possible value for the instance value. If + * this attribute is defined, the instance value MUST be one of the + * values in the array in order for the schema to be valid. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.23 + */ + enum?: JSONSchema6Type[] + + /** + * More readible form of a one-element "enum" + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.24 + */ + const?: JSONSchema6Type + + /** + * A single type, or a union of simple types + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.25 + */ + type?: JSONSchema6TypeName | JSONSchema6TypeName[] + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.26 + */ + allOf?: JSONSchema6[] + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.27 + */ + anyOf?: JSONSchema6[] + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.28 + */ + oneOf?: JSONSchema6[] + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.29 + */ + not?: boolean | JSONSchema6 + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.1 + */ + definitions?: { + [k: string]: boolean | JSONSchema6 + } + + /** + * This attribute is a string that provides a short description of the instance property. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.2 + */ + title?: string + + /** + * This attribute is a string that provides a full description of the of purpose the instance property. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.2 + */ + description?: string + + /** + * This keyword can be used to supply a default JSON value associated with a particular schema. + * It is RECOMMENDED that a default value be valid against the associated schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.3 + */ + default?: JSONSchema6Type + + /** + * Array of examples with no validation effect the value of "default" is usable as an example without repeating it under this keyword + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.4 + */ + examples?: JSONSchema6Type[] +} diff --git a/types/json-schema/json-schema-tests.ts b/types/json-schema/json-schema-tests.ts index 58264668b0..0fd15f5de9 100644 --- a/types/json-schema/json-schema-tests.ts +++ b/types/json-schema/json-schema-tests.ts @@ -1,4 +1,6 @@ -import { JSONSchema4, JSONSchema4Type, JSONSchema4TypeName } from 'json-schema' +import { JSONSchema4, JSONSchema4Type, JSONSchema4TypeName, JSONSchema6, JSONSchema6Type, JSONSchema6TypeName } from 'json-schema' + +/* JSON Schema 4 */ // SimpleType () => { @@ -56,7 +58,7 @@ import { JSONSchema4, JSONSchema4Type, JSONSchema4TypeName } from 'json-schema' baz: { type: 'integer' } }, enum: ['foo', 42], - type: ['string', 'array'], + type: 'string', allOf: [{}], anyOf: [{}], oneOf: [{}], @@ -65,3 +67,73 @@ import { JSONSchema4, JSONSchema4Type, JSONSchema4TypeName } from 'json-schema' bar: 4 } } + +/* JSON Schema 6 */ + +// SimpleType +() => { + const a: JSONSchema6TypeName = 'string' + const b: JSONSchema6TypeName = 'null' + const c: JSONSchema6TypeName = 'any' +} + +// Type +() => { + const a: JSONSchema6Type = 'foo' + const b: JSONSchema6Type = null + const c: JSONSchema6Type = [1, 2] +} + +// JSONSchema4 +() => { + const a: JSONSchema6 = {} + const b: JSONSchema6 = { + $id: 'foo', + $ref: 'foo/bar', + $schema: 'http://json-schema.org/schema#', + title: 'foo', + description: 'bar', + default: 42, + multipleOf: 3, + maximum: 4, + exclusiveMaximum: 4, + minimum: 5, + exclusiveMinimum: 5, + maxLength: 6, + minLength: 7, + pattern: 'baz', + additionalItems: true, + items: [ + { items: [{ minLength: 4 }] } + ], + maxItems: 4, + minItems: 5, + uniqueItems: true, + maxProperties: 10, + minProperties: 11, + required: ['foo', 'bar'], + additionalProperties: false, + definitions: { + foo: { type: 'string' } + }, + properties: { + bar: { type: 'boolean' } + }, + patternProperties: { + foo: { type: 'integer' } + }, + dependencies: { + baz: { type: 'integer' } + }, + enum: ['foo', 42], + type: 'string', + allOf: [{}], + anyOf: [{}], + oneOf: [{}], + not: {}, + const: 'foo', + contains: {}, + examples: [{}], + propertyNames: {} + } +} diff --git a/types/jsonstream/index.d.ts b/types/jsonstream/index.d.ts index cf0f0fdd43..3e9bdd4b12 100644 --- a/types/jsonstream/index.d.ts +++ b/types/jsonstream/index.d.ts @@ -14,7 +14,25 @@ export interface Options { export declare function parse(pattern: any): NodeJS.ReadWriteStream; export declare function parse(patterns: any[]): NodeJS.ReadWriteStream; + +/** + * Create a writable stream. + * you may pass in custom open, close, and seperator strings. But, by default, + * JSONStream.stringify() will create an array, + * (with default options open='[\n', sep='\n,\n', close='\n]\n') + */ export declare function stringify(): NodeJS.ReadWriteStream; + +/** If you call JSONStream.stringify(false) the elements will only be seperated by a newline. */ +export declare function stringify(newlineOnly: NewlineOnlyIndicator): NodeJS.ReadWriteStream; +type NewlineOnlyIndicator = false + +/** + * Create a writable stream. + * you may pass in custom open, close, and seperator strings. But, by default, + * JSONStream.stringify() will create an array, + * (with default options open='[\n', sep='\n,\n', close='\n]\n') + */ export declare function stringify(open: string, sep: string, close: string): NodeJS.ReadWriteStream; export declare function stringifyObject(): NodeJS.ReadWriteStream; diff --git a/types/jsonstream/jsonstream-tests.ts b/types/jsonstream/jsonstream-tests.ts index d42ab0d845..68c8e858ac 100644 --- a/types/jsonstream/jsonstream-tests.ts +++ b/types/jsonstream/jsonstream-tests.ts @@ -8,6 +8,7 @@ read = read.pipe(json.parse('*')); read = read.pipe(json.parse(['foo/*', 'bar/*'])); read = json.stringify(); +read = json.stringify(false); read = json.stringify('{', ',', '}'); read = json.stringifyObject(); diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index aaee0b27f7..e96dfbefd8 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -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; diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index dec1bf055f..c7c99813f1 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -672,6 +672,9 @@ knex.transaction<{ length: number }>(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/koa-router/index.d.ts b/types/koa-router/index.d.ts index 4ad96140eb..ab61772835 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -219,7 +219,7 @@ declare class Router { /** * Returns router middleware which dispatches a route matching the request. */ - middlewares(): Router.IMiddleware; + middleware(): Router.IMiddleware; /** * Returns separate middleware for responding to `OPTIONS` requests with diff --git a/types/koa/index.d.ts b/types/koa/index.d.ts index d4f339aa32..64bd8ed41a 100644 --- a/types/koa/index.d.ts +++ b/types/koa/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for Koa 2.x // Project: http://koajs.com -// Definitions by: DavidCai1993 , jKey Lu +// Definitions by: DavidCai1993 +// jKey Lu +// Brice Bernard // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -15,20 +17,22 @@ =============================================== */ /// -import { EventEmitter } from 'events'; -import { IncomingMessage, ServerResponse, Server } from 'http'; -import { Socket, ListenOptions } from 'net'; -import * as compose from 'koa-compose'; -import * as Keygrip from 'keygrip'; -import * as httpAssert from 'http-assert'; -import * as Cookies from 'cookies'; -import * as accepts from 'accepts'; +import * as accepts from "accepts"; +import * as Cookies from "cookies"; +import { EventEmitter } from "events"; +import { IncomingMessage, ServerResponse, Server } from "http"; +import * as httpAssert from "http-assert"; +import * as Keygrip from "keygrip"; +import * as compose from "koa-compose"; +import { Socket, ListenOptions } from "net"; +import * as url from "url"; declare interface ContextDelegatedRequest { /** * Return request header. */ header: any; + /** * Return request header, alias as request.header */ @@ -80,7 +84,6 @@ declare interface ContextDelegatedRequest { */ search: string; - /** * Parse the "Host" header field host * and support X-Forwarded-Host when a @@ -95,6 +98,11 @@ declare interface ContextDelegatedRequest { */ hostname: string; + /** + * Get WHATWG parsed URL object. + */ + URL: url.URL; + /** * Check if the request is fresh, aka * Last-Modified and/or the ETag @@ -388,7 +396,7 @@ declare interface ContextDelegatedResponse { * this.set('Accept', 'application/json'); * this.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); */ - set(field: { [key: string]: string; }): void; + set(field: { [key: string]: string }): void; set(field: string, val: string | string[]): void; /** @@ -440,15 +448,36 @@ declare class Application extends EventEmitter { * * http.createServer(app.callback()).listen(...) */ - listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): Server; - listen(port: number, hostname?: string, listeningListener?: () => void): Server; + listen( + port?: number, + hostname?: string, + backlog?: number, + listeningListener?: () => void, + ): Server; + listen( + port: number, + hostname?: string, + listeningListener?: () => void, + ): Server; /* tslint:disable:unified-signatures */ - listen(port: number, backlog?: number, listeningListener?: () => void): Server; + listen( + port: number, + backlog?: number, + listeningListener?: () => void, + ): Server; listen(port: number, listeningListener?: () => void): Server; - listen(path: string, backlog?: number, listeningListener?: () => void): Server; + listen( + path: string, + backlog?: number, + listeningListener?: () => void, + ): Server; listen(path: string, listeningListener?: () => void): Server; listen(options: ListenOptions, listeningListener?: () => void): Server; - listen(handle: any, backlog?: number, listeningListener?: () => void): Server; + listen( + handle: any, + backlog?: number, + listeningListener?: () => void, + ): Server; listen(handle: any, listeningListener?: () => void): Server; /* tslint:enable:unified-signatures*/ @@ -482,7 +511,10 @@ declare class Application extends EventEmitter { * * @api private */ - createContext(req: IncomingMessage, res: ServerResponse): Application.Context; + createContext( + req: IncomingMessage, + res: ServerResponse, + ): Application.Context; /** * Default error handler. @@ -578,7 +610,9 @@ declare namespace Application { toJSON(): any; } - interface BaseContext extends ContextDelegatedRequest, ContextDelegatedResponse { + interface BaseContext + extends ContextDelegatedRequest, + ContextDelegatedResponse { /** * util.inspect() implementation, which * just returns the JSON output. @@ -626,6 +660,8 @@ declare namespace Application { * Default error handling. */ onerror(err: Error): void; + + [key: string]: any; } interface Request extends BaseRequest { diff --git a/types/koa/koa-tests.ts b/types/koa/koa-tests.ts index 1b261fdf44..6dbc073bea 100644 --- a/types/koa/koa-tests.ts +++ b/types/koa/koa-tests.ts @@ -1,21 +1,27 @@ - import * as Koa from "koa"; const app = new Koa(); +app.context.db = () => {}; + +app.use(async ctx => { + console.log(ctx.db); +}); + app.use((ctx, next) => { - const start: any = new Date(); - return next().then(() => { - const end: any = new Date(); - const ms = end - start; - console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); - ctx.assert(true, 404, 'Yep!'); - }); + const start: any = new Date(); + return next().then(() => { + const end: any = new Date(); + const ms = end - start; + console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); + ctx.assert(true, 404, "Yep!"); + }); }); // response app.use(ctx => { - ctx.body = "Hello World"; + ctx.body = "Hello World"; + ctx.body = ctx.URL.toString(); }); app.listen(3000); diff --git a/types/kolite/knockout.dirtyFlag.d.ts b/types/kolite/knockout.dirtyFlag.d.ts index 2f63a110e0..3999f833ae 100644 --- a/types/kolite/knockout.dirtyFlag.d.ts +++ b/types/kolite/knockout.dirtyFlag.d.ts @@ -10,9 +10,14 @@ // DirtyFlag ///////////////////////////////////////////// interface DirtyFlag { - isDirty: KnockoutComputed; new (objectToTrack: any, isInitiallyDirty?: boolean, hashFunction?: () => any): any; + (): DirtyFlagResult; +} + +interface DirtyFlagResult { + isDirty: KnockoutComputed; reset(): void; + forceDirty(): void; } interface KnockoutStatic { diff --git a/types/leaflet.heat/index.d.ts b/types/leaflet.heat/index.d.ts new file mode 100644 index 0000000000..224b6f7c35 --- /dev/null +++ b/types/leaflet.heat/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for Leaflet.heat 0.2 +// Project: https://github.com/Leaflet/Leaflet.heat +// Definitions by: Önder Ceylan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as L from 'leaflet'; + +declare module 'leaflet' { + type HeatLatLngTuple = [number, number, number]; + + interface ColorGradientConfig { + [key: number]: string; + } + + interface HeatMapOptions { + minOpacity?: number; + maxZoom?: number; + max?: number; + radius?: number; + blur?: number; + gradient?: ColorGradientConfig; + } + + interface HeatLayer extends TileLayer { + setOptions(options: HeatMapOptions): HeatLayer; + addLatLng(latlng: LatLng | HeatLatLngTuple): HeatLayer; + setLatLngs(latlngs: Array): HeatLayer; + } + + function heatLayer(latlngs: Array, options: HeatMapOptions): HeatLayer; +} diff --git a/types/leaflet.heat/leaflet.heat-tests.ts b/types/leaflet.heat/leaflet.heat-tests.ts new file mode 100644 index 0000000000..b715255e78 --- /dev/null +++ b/types/leaflet.heat/leaflet.heat-tests.ts @@ -0,0 +1,43 @@ +import * as L from 'leaflet'; +import 'leaflet.heat'; + +const osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; +const osmAttrib = '© OpenStreetMap contributors'; +const osm = L.tileLayer(osmUrl, {maxZoom: 18, attribution: osmAttrib}); +const map = new L.Map('map', { + layers: [osm], + center: new L.LatLng(50.5, 30.5), + zoom: 15, +}); + +// Each point in the input array can be either an array like [50.5, 30.5, 0.5], or a Leaflet LatLng object. +const heat: L.HeatLayer = L.heatLayer([ + [50.5, 30.5, 0.2], // lat, lng, intensity + [50.6, 30.4, 0.5], + new L.LatLng(50.7, 30.3), +], {radius: 25}).addTo(map); + +// Set options on the heat layer +heat.setOptions({ + minOpacity: 0.05, + maxZoom: 18, + max: 1.0, + radius: 25, + blur: 15, + gradient: {0.4: 'blue', 0.65: 'lime', 1: 'red'}, +}); + +// Add new point to heat layer +const newLatLng = new L.LatLng(50.8, 30.2); +heat.addLatLng(newLatLng); + +// Set new latLng list to the heat layer +heat.setLatLngs([ + newLatLng, + newLatLng, + newLatLng, + [50.6, 30.4, 0.5], +]); + +// Redraw the heat layer +heat.redraw(); diff --git a/types/leaflet.heat/tsconfig.json b/types/leaflet.heat/tsconfig.json new file mode 100644 index 0000000000..482c984b8c --- /dev/null +++ b/types/leaflet.heat/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", + "leaflet.heat-tests.ts" + ] +} diff --git a/types/leaflet.heat/tslint.json b/types/leaflet.heat/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/leaflet.heat/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/leaflet.markercluster/index.d.ts b/types/leaflet.markercluster/index.d.ts index f60a7a2891..e2f317dd46 100644 --- a/types/leaflet.markercluster/index.d.ts +++ b/types/leaflet.markercluster/index.d.ts @@ -29,7 +29,7 @@ declare module 'leaflet' { getBounds(): LatLngBounds; } - interface MarkerClusterGroupOptions { + interface MarkerClusterGroupOptions extends LayerOptions { /* * When you mouse over a cluster it shows the bounds of its markers. */ diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index b1e7ead796..71c6ea4adf 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -241,20 +241,22 @@ export abstract class Evented extends Class { */ on(eventMap: LeafletEventHandlerFnMap): this; - /* tslint:disable:unified-signatures */ // With an eventMap there are no additional arguments allowed /** * Removes a previously added listener function. If no function is specified, * it will remove all the listeners of that particular event from the object. * Note that if you passed a custom context to on, you must pass the same context * to off in order to remove the listener. */ + // With an eventMap there are no additional arguments allowed + // tslint:disable-next-line:unified-signatures off(type: string, fn?: LeafletEventHandlerFn, context?: any): this; /** * Removes a set of type/listener pairs. */ + // With an eventMap there are no additional arguments allowed + // tslint:disable-next-line:unified-signatures off(eventMap: LeafletEventHandlerFnMap): this; - /* tslint:enable */ /** * Removes all listeners to all events on the object. */ @@ -667,7 +669,8 @@ export function canvas(options?: RendererOptions): Canvas; * added/removed on the map as well. Extends Layer. */ export class LayerGroup

extends Layer { - constructor(layers?: Layer[]); + constructor(layers?: Layer[], options?: LayerOptions); + /** * Returns a GeoJSON representation of the layer group (as a GeoJSON GeometryCollection, GeoJSONFeatureCollection or Multipoint). */ @@ -729,9 +732,9 @@ export class LayerGroup

extends Layer { } /** - * Create a layer group, optionally given an initial set of layers. + * Create a layer group, optionally given an initial set of layers and an `options` object. */ -export function layerGroup(layers: Layer[]): LayerGroup; +export function layerGroup(layers?: Layer[], options?: LayerOptions): LayerGroup; /** * Extended LayerGroup that also has mouse events (propagated from @@ -1128,9 +1131,8 @@ export interface PanOptions { noMoveStart?: boolean; } -/* tslint:disable:no-empty-interface */ // This is not empty, it extends two interfaces into one... +// This is not empty, it extends two interfaces into one... export interface ZoomPanOptions extends ZoomOptions, PanOptions {} -/* tslint:enable */ export interface FitBoundsOptions extends ZoomOptions, PanOptions { paddingTopLeft?: PointExpression; diff --git a/types/leaflet/leaflet-tests.ts b/types/leaflet/leaflet-tests.ts index fc84a78267..a39ea761b1 100644 --- a/types/leaflet/leaflet-tests.ts +++ b/types/leaflet/leaflet-tests.ts @@ -496,3 +496,17 @@ interface MyProperties { iconUrl: 'my-icon.png' }) }) as L.Marker).feature.properties.testProperty = "test"; + +let lg = L.layerGroup(); +lg = L.layerGroup([new L.Layer(), new L.Layer()]); +lg = L.layerGroup([new L.Layer(), new L.Layer()], { + pane: 'overlayPane', + attribution: 'test' +}); + +lg = new L.LayerGroup(); +lg = new L.LayerGroup([new L.Layer(), new L.Layer()]); +lg = new L.LayerGroup([new L.Layer(), new L.Layer()], { + pane: 'overlayPane', + attribution: 'test' +}); diff --git a/types/lodash/conformsTo.d.ts b/types/lodash/conformsTo.d.ts new file mode 100644 index 0000000000..320b1806e0 --- /dev/null +++ b/types/lodash/conformsTo.d.ts @@ -0,0 +1,2 @@ +import { conformsTo } from "./index"; +export = conformsTo; diff --git a/types/lodash/defaultTo.d.ts b/types/lodash/defaultTo.d.ts new file mode 100644 index 0000000000..89fb56505f --- /dev/null +++ b/types/lodash/defaultTo.d.ts @@ -0,0 +1,2 @@ +import { defaultTo } from "./index"; +export = defaultTo; diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index f038846d22..76c3c7a115 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 */ @@ -16566,21 +16635,21 @@ declare namespace _ { * @param predicates The predicates to check. * @return Returns the new function. */ - overEvery(...predicates: Array any>>): (...args: any[]) => boolean; + overEvery(...predicates: Array boolean>>): (...args: T[]) => boolean; } interface LoDashImplicitWrapper { /** * @see _.overEvery */ - overEvery(...predicates: Array any>>): LoDashImplicitWrapper<(...args: any[]) => boolean>; + overEvery(...predicates: Array boolean>>): LoDashImplicitWrapper<(...args: T[]) => boolean>; } interface LoDashExplicitWrapper { /** * @see _.overEvery */ - overEvery(...predicates: Array any>>): LoDashExplicitWrapper<(...args: any[]) => boolean>; + overEvery(...predicates: Array boolean>>): LoDashExplicitWrapper<(...args: T[]) => boolean>; } //_.overSome @@ -16592,21 +16661,21 @@ declare namespace _ { * @param predicates The predicates to check. * @return Returns the new function. */ - overSome(...predicates: Array any>>): (...args: any[]) => boolean; + overSome(...predicates: Array boolean>>): (...args: T[]) => boolean; } interface LoDashImplicitWrapper { /** * @see _.overSome */ - overSome(...predicates: Array any>>): LoDashImplicitWrapper<(...args: any[]) => boolean>; + overSome(...predicates: Array boolean>>): LoDashImplicitWrapper<(...args: T[]) => boolean>; } interface LoDashExplicitWrapper { /** * @see _.overSome */ - overSome(...predicates: Array any>>): LoDashExplicitWrapper<(...args: any[]) => boolean>; + overSome(...predicates: Array boolean>>): LoDashExplicitWrapper<(...args: T[]) => boolean>; } //_.property @@ -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..a4c01223ea 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 @@ -13744,60 +13689,60 @@ namespace TestOver { // _.overEvery namespace TestOverEvery { { - let result: (...args: any[]) => boolean; + let result: (...args: number[]) => boolean; - result = _.overEvery(() => true); - result = _.overEvery(() => true, () => true); - result = _.overEvery([() => true]); - result = _.overEvery([() => true], [() => true]); + result = _.overEvery((number) => true); + result = _.overEvery((number) => true, (number) => true); + result = _.overEvery([(number) => true]); + result = _.overEvery([(number) => true], [(number) => true]); } { - let result: _.LoDashImplicitObjectWrapper<(...args: any[]) => boolean>; + let result: _.LoDashImplicitObjectWrapper<(...args: number[]) => boolean>; result = _(Math.max).overEvery(); - result = _(Math.max).overEvery(() => true); + result = _(Math.max).overEvery((number) => true); result = _([Math.max]).overEvery(); - result = _([Math.max]).overEvery([() => true]); + result = _([Math.max]).overEvery([(number) => true]); } { - let result: _.LoDashExplicitObjectWrapper<(...args: any[]) => boolean>; + let result: _.LoDashExplicitObjectWrapper<(...args: number[]) => boolean>; result = _(Math.max).chain().overEvery(); - result = _(Math.max).chain().overEvery(() => true); + result = _(Math.max).chain().overEvery((number) => true); result = _([Math.max]).chain().overEvery(); - result = _([Math.max]).chain().overEvery([() => true]); + result = _([Math.max]).chain().overEvery([(number) => true]); } } // _.overSome namespace TestOverSome { { - let result: (...args: any[]) => boolean; + let result: (...args: number[]) => boolean; - result = _.overSome(() => true); - result = _.overSome(() => true, () => true); - result = _.overSome([() => true]); - result = _.overSome([() => true], [() => true]); + result = _.overSome((n: number) => true); + result = _.overSome((n: number) => true, (n: number) => true); + result = _.overSome([(n: number) => true]); + result = _.overSome([(n: number) => true], [(n: number) => true]); } { - let result: _.LoDashImplicitObjectWrapper<(...args: any[]) => boolean>; + let result: _.LoDashImplicitObjectWrapper<(...args: number[]) => boolean>; result = _(Math.max).overSome(); - result = _(Math.max).overSome(() => true); + result = _(Math.max).overSome((n: number) => true); result = _([Math.max]).overSome(); - result = _([Math.max]).overSome([() => true]); + result = _([Math.max]).overSome([(n: number) => true]); } { - let result: _.LoDashExplicitObjectWrapper<(...args: any[]) => boolean>; + let result: _.LoDashExplicitObjectWrapper<(...args: number[]) => boolean>; result = _(Math.max).chain().overSome(); - result = _(Math.max).chain().overSome(() => true); + result = _(Math.max).chain().overSome((n: number) => true); result = _([Math.max]).chain().overSome(); - result = _([Math.max]).chain().overSome([() => true]); + result = _([Math.max]).chain().overSome([(n: number) => true]); } } diff --git a/types/lodash/tsconfig.json b/types/lodash/tsconfig.json index 2c4aa57c54..af6ba5e2e9 100644 --- a/types/lodash/tsconfig.json +++ b/types/lodash/tsconfig.json @@ -6,8 +6,8 @@ ], "noImplicitAny": true, "noImplicitThis": true, + "strictFunctionTypes": true, "strictNullChecks": true, - "strictFunctionTypes": false, "baseUrl": "../", "typeRoots": [ "../" @@ -46,6 +46,7 @@ "compact.d.ts", "concat.d.ts", "cond.d.ts", + "conformsTo.d.ts", "constant.d.ts", "countBy.d.ts", "create.d.ts", @@ -55,6 +56,7 @@ "deburr.d.ts", "defaults.d.ts", "defaultsDeep.d.ts", + "defaultTo.d.ts", "defer.d.ts", "delay.d.ts", "difference.d.ts", @@ -316,4 +318,4 @@ "zipObjectDeep.d.ts", "zipWith.d.ts" ] -} \ No newline at end of file +} diff --git a/types/lokijs/index.d.ts b/types/lokijs/index.d.ts index f250786778..74f1b6f09e 100644 --- a/types/lokijs/index.d.ts +++ b/types/lokijs/index.d.ts @@ -1,854 +1,1431 @@ -// Type definitions for lokijs v1.2.5 +// Type definitions for lokijs v1.5.1 // Project: https://github.com/techfort/LokiJS // Definitions by: TeamworkGuy2 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -// NOTE: definition last updated (2016-3-13) based on latest code as of https://github.com/techfort/LokiJS/commit/3d2cf9546cd22556444deeabc4df314f227ecf5c +// NOTE: definition last updated (2017-11-25) based on latest code as of https://github.com/techfort/LokiJS/commit/f6c8f1c362cfc9ed63d93cd165ef0ac3bad131bf -/** LokiJS +/** + * LokiJS * A lightweight document oriented javascript database * @author Joe Minichino */ - -/** Loki: The main database class - * @constructor - * @param {string} filename - name of the file to be saved to - * @param {object} options - config object +/** comparison operators + * a is the value in the collection + * b is the query value */ -interface Loki extends LokiEventEmitter { - // autosave support (disabled by default) - autosave: boolean; - autosaveInterval: number; // milliseconds between auto-saves - autosaveHandle: number; // ID from setInterval(...) - collections: LokiCollection[]; - databaseVersion: number; - engineVersion: number; - ENV: string;/*NODEJS, CORDOVA, BROWSER*/ - events: { [id: string]: ((...args: any[]) => void)[] }; /*{ - 'init': ((...args) => void)[]; - 'loaded': ((...args) => void)[]; - 'flushChanges': ((...args) => void)[]; - 'close': ((...args) => void)[]; - 'changes': ((...args) => void)[]; - 'warning': ((...args) => void)[]; - };*/ - filename: string; - options: LokiConfigureOptions; - persistenceAdapter: LokiPersistenceInterface; - // persistenceMethod could be 'fs', 'localStorage', or 'adapter' - // this is optional option param, otherwise environment detection will be used - // if user passes their own adapter we will force this method to 'adapter' later, so no need to pass method option. - persistenceMethod: string; /*'fs', 'localStorage', 'adapter'*/ - verbose: boolean; +declare var LokiOps: { + $eq(a: any, b: any): boolean; + // abstract/loose equality + $aeq(a: any, b: any): boolean; + $ne(a: any, b: any): boolean; + // date equality / loki abstract equality test + $dteq(a: any, b: any): boolean; + $gt(a: any, b: any): boolean; + $gte(a: any, b: any): boolean; + $lt(a: any, b: any): boolean; + $lte(a: any, b: any): boolean; + /** ex : coll.find({'orderCount': {$between: [10, 50]}}); */ + $between(a: any, vals: any/*[any, any]*/): boolean; + $in(a: any, b: any): boolean; + $nin(a: any, b: any): boolean; + $keyin(a: any, b: any): boolean; + $nkeyin(a: any, b: any): boolean; + $definedin(a: any, b: any): boolean; + $undefinedin(a: any, b: any): boolean; + $regex(a: any, b: any): boolean; + $containsString(a: any, b: any): boolean; + $containsNone(a: any, b: any): boolean; + $containsAny(a: any, b: any): boolean; + $contains(a: any, b: any): boolean; + $type(a: any, b: any): boolean; + $finite(a: any, b: any): boolean; + $size(a: any, b: any): boolean; + $len(a: any, b: any): boolean; + $where(a: any, b: any): boolean; + // field-level logical operators + // a is the value in the collection + // b is the nested query operation (for '$not') + // or an array of nested query operations (for '$and' and '$or') + $not(a: any, b: any): boolean; + $and(a: any, b: any): boolean; + $or(a: any, b: any): boolean; +}; +declare type LokiOps = typeof LokiOps; - new (filename: string, options: LokiConfigureOptions): Loki; - - // experimental support for browserify's abstract syntax scan to pick up dependency of indexed adapter. - // Hopefully, once this hits npm a browserify require of lokijs should scan the main file and detect this indexed adapter reference. - getIndexedAdapter(): LokiPersistenceInterface; // require("./loki-indexed-adapter.js") +/** if an op is registered in this object, our 'calculateRange' can use it with our binary indices. + * if the op is registered to a function, we will run that function/op as a 2nd pass filter on results. + * those 2nd pass filter functions should be similar to LokiOps functions, accepting 2 vals to compare. + */ +declare var indexedOps: { + $eq: LokiOps["$eq"], + $aeq: true, + $dteq: true, + $gt: true, + $gte: true, + $lt: true, + $lte: true, + $in: true, + $between: true +}; - /** configureOptions - allows reconfiguring database options - * - * @param {object} options - configuration options to apply to loki db object - * @param {boolean} initialConfig - (optional) if this is a reconfig, don't pass this - */ - configureOptions(options: LokiConfigureOptions, initialConfig?: boolean): void; +type PartialModel = { [P in keyof E]?: T | E[P] }; - /** anonym() - shorthand method for quickly creating and populating an anonymous collection. - * This collection is not referenced internally so upon losing scope it will be garbage collected. - * - * Example : var results = new loki().anonym(myDocArray).find({'age': {'$gt': 30} }); - * - * @param {Array} docs - document array to initialize the anonymous collection with - * @param {Array} indexesArray - (Optional) array of property names to index - * @returns {Collection} New collection which you can query or chain - */ - anonym(docs: T | T[], indexesArray?: LokiCollectionOptions): LokiCollection; +type LokiQuery = PartialModel; - addCollection(name: string, options?: LokiCollectionOptions): LokiCollection; - - loadCollection(collection: LokiCollection): void; - - getCollection(collectionName: string): LokiCollection; - - listCollections(): { name: string; type: string; count: number }[]; - - removeCollection(collectionName: string): void; - - getName(): string; - - /** serializeReplacer - used to prevent certain properties from being serialized - */ - serializeReplacer(key: "autosaveHandle", value: T): T; - serializeReplacer(key: "persistenceAdapter", value: T): T; - serializeReplacer(key: "constraints", value: T): T; - serializeReplacer(key: string, value: T): T; - - // toJson - serialize(): string; - - // alias of serialize - toJson(): string; - - /** loadJSON - inflates a loki database from a serialized JSON string - * - * @param {string} serializedDb - a serialized loki database string - * @param {object} options - apply or override collection level settings - */ - loadJSON(serializedDb: string, options?: { [collectionName: string]: { inflate?: (src: any, dst: any) => void; proto: any; } }): void; - - /** loadJSONObject - inflates a loki database from a JS object - * - * @param {object} dbObject - a serialized loki database string - * @param {object} options - apply or override collection level settings - */ - loadJSONObject(dbObject: Loki, options?: { [collectionName: string]: { inflate?: (src: any, dst: any) => void; proto: any; } }): void; - - /** close(callback) - emits the close event with an optional callback. Does not actually destroy the db - * but useful from an API perspective - */ - close(callback?: (...args: any[]) => void): void; - - /**-------------------------+ - | Changes API | - +--------------------------*/ - - /** The Changes API enables the tracking the changes occurred in the collections since the beginning of the session, - * so it's possible to create a differential dataset for synchronization purposes (possibly to a remote db) - */ - - /** generateChangesNotification() - takes all the changes stored in each - * collection and creates a single array for the entire database. If an array of names - * of collections is passed then only the included collections will be tracked. - * - * @param {array} optional array of collection names. No arg means all collections are processed. - * @returns {array} array of changes - * @see private method createChange() in Collection - */ - generateChangesNotification(arrayOfCollectionNames?: string[]): LokiCollectionChange[]; - - /** serializeChanges() - stringify changes for network transmission - * @returns {string} string representation of the changes - */ - serializeChanges(collectionNamesArray?: string[]): string; - - /** clearChanges() - clears all the changes in all collections. - */ - clearChanges(): void; - - /** loadDatabase - Handles loading from file system, local storage, or adapter (indexeddb) - * This method utilizes loki configuration options (if provided) to determine which - * persistence method to use, or environment detection (if configuration was not provided). - * - * @param {object} options - not currently used (remove or allow overrides?) - * @param {function} callback - (Optional) user supplied async callback / error handler - */ - loadDatabase(options: { [collectionName: string]: { inflate?: (src: any, dst: any) => void; proto: any; } }, callback?: (err: any, data: any) => void): void; - - /** saveDatabase - Handles saving to file system, local storage, or adapter (indexeddb) - * This method utilizes loki configuration options (if provided) to determine which - * persistence method to use, or environment detection (if configuration was not provided). - * - * @param {object} options - not currently used (remove or allow overrides?) - * @param {function} callback - (Optional) user supplied async callback / error handler - */ - saveDatabase(callback?: (err: any) => void): void; - - // alias for saveDatabase - save(callback ?: (err: any) => void): void; - - /** deleteDatabase - Handles deleting a database from file system, local - * storage, or adapter (indexeddb) - * This method utilizes loki configuration options (if provided) to determine which - * persistence method to use, or environment detection (if configuration was not provided). - * - * @param {object} options - not currently used (remove or allow overrides?) - * @param {function} callback - user supplied async callback / error handler - */ - deleteDatabase(options: any, callback: (err: any, data: any) => void): void; - - /** autosaveDirty - check whether any collections are 'dirty' meaning we need to save (entire) database - * @returns {boolean} - true if database has changed since last autosave, false if not. - */ - autosaveDirty(): boolean; - - /** autosaveClearFlags - resets dirty flags on all collections. - * Called from saveDatabase() after db is saved. - */ - autosaveClearFlags(): void; - - /** autosaveEnable - begin a javascript interval to periodically save the database. - * - * @param {object} options - not currently used (remove or allow overrides?) - * @param {function} callback - (Optional) user supplied async callback - */ - autosaveEnable(options?: LokiConfigureOptions, callback?: (err: any) => void): void; - - /** autosaveDisable - stop the autosave interval timer. - */ - autosaveDisable(): void; +interface LokiObj { + $loki: number; + meta: { + created: number; // Date().getTime() + revision: number; + updated: number; // Date().getTime() + version: number; + }; } - /** * LokiEventEmitter is a minimalist version of EventEmitter. It enables any * constructor that inherits EventEmitter to emit events and trigger * listeners that have been added to the event through the on(event, callback) method + * + * @constructor LokiEventEmitter */ -interface LokiEventEmitter { - /** - * @prop Events property is a hashmap, with each property being an array of callbacks - */ - events: { [eventName: string]: ((...args: any[]) => void)[] }; +declare class LokiEventEmitter { - new (): LokiEventEmitter; + /** + * @prop events - a hashmap, with each property being an array of callbacks + */ + public events: { [eventName: string]: ((...args: any[]) => any)[] }; /** * @prop asyncListeners - boolean determines whether or not the callbacks associated with each event * should happen in an async fashion or not * Default is false, which means events are synchronous */ - asyncListeners: boolean; + public asyncListeners: boolean; /** - * @prop on(eventName, listener) - adds a listener to the queue of callbacks associated to an event - * @returns {int} the index of the callback in the array of listeners for a particular event + * on(eventName, listener) - adds a listener to the queue of callbacks associated to an event + * @param eventName - the name(s) of the event(s) to listen to + * @param listener - callback function of listener to attach + * @returns the index of the callback in the array of listeners for a particular event */ - on void>(eventName: string, listener: U): U; + on any>(eventName: string | string[], listener: F): F; /** - * @propt emit(eventName, data) - emits a particular event + * emit(eventName, data) - emits a particular event * with the option of passing optional parameters which are going to be processed by the callback * provided signatures match (i.e. if passing emit(event, arg0, arg1) the listener should take two parameters) - * @param {string} eventName - the name of the event - * @param {object} data - optional object passed with the event + * @param eventName - the name of the event + * @param data - optional object passed with the event */ - emit(eventName: string, data?: any): void; + emit(eventName: string, data?: any, arg?: any): void; /** - * @prop remove() - removes the listener at position 'index' from the event 'eventName' + * Alias of LokiEventEmitter.prototype.on + * addListener(eventName, listener) - adds a listener to the queue of callbacks associated to an event + * @param eventName - the name(s) of the event(s) to listen to + * @param listener - callback function of listener to attach + * @returns the event listener added */ - removeListener(eventName: string, listener: (...args: any[]) => void): void; + public addListener: LokiEventEmitter["on"]; + + /** + * removeListener() - removes the listener at position 'index' from the event 'eventName' + * @param eventName - the name(s) of the event(s) which the listener is attached to + * @param listener - the listener callback function to remove from emitter + */ + public removeListener(eventName: string | string[], listener: (...args: any[]) => any): void; } +interface LokiConstructorOptions { + verbose: boolean; + env: "NATIVESCRIPT" | "NODEJS" | "CORDOVA" | "BROWSER" | "NA"; +} + + +interface LokiConfigOptions { + adapter: LokiPersistenceAdapter | null; + autoload: boolean; + autoloadCallback: (err: any) => void; + autosave: boolean; + autosaveCallback: (err?: any) => void; + autosaveInterval: string | number; + persistenceMethod: "fs" | "localStorage" | "memory" | null; + destructureDelimiter: string; + serializationMethod: "normal" | "pretty" | "destructured" | null; + throttledSaves: boolean; +} + + +type DeserializeOptions = { partitioned?: boolean; delimited: false; delimiter?: string; partition?: number } | { partitioned?: boolean; delimited?: true; delimiter: string; partition?: number }; + + +interface ThrottledSaveDrainOptions { + recursiveWait: boolean; + recursiveWaitLimit: boolean; + recursiveWaitLimitDuration: number; + started: number; +} + + +interface Transform { + type: "find" | "where" | "simplesort" | "compoundsort" | "sort" | "limit" | "offset" | "map" | "eqJoin" | "mapReduce" | "update" | "remove"; + value?: any; + property?: string; + desc?: boolean; + dataOptions?: any; + joinData?: any; + leftJoinKey?: any; + rightJoinKey?: any; + mapFun?: any; + mapFunction?: any; + reduceFunction?: any; +} + + +/** + * Loki: The main database class + * @implements LokiEventEmitter + */ +declare class Loki extends LokiEventEmitter { + collections: Collection[]; + options: Partial & LokiConfigOptions & Partial; + filename: string; + name?: string; + databaseVersion: number; + engineVersion: number; + autosave: boolean; + autosaveInterval: number; + autosaveHandle: number | null; + persistenceAdapter: LokiPersistenceAdapter | null | undefined; + persistenceMethod: "fs" | "localStorage" | "memory" | "adapter" | null | undefined; + throttledCallbacks: ((err?: any) => void)[]; + throttledSavePending: boolean; + throttledSaves: boolean; + verbose: boolean; + ENV: "NATIVESCRIPT" | "NODEJS" | "CORDOVA" | "BROWSER" | "NA"; + + /** + * @param filename - name of the file to be saved to + * @param options - (Optional) config options object + * @param options.env - override environment detection as 'NODEJS', 'BROWSER', 'CORDOVA' + * @param [options.verbose=false] - enable console output + * @param [options.autosave=false] - enables autosave + * @param [options.autosaveInterval=5000] - time interval (in milliseconds) between saves (if dirty) + * @param [options.autoload=false] - enables autoload on loki instantiation + * @param options.autoloadCallback - user callback called after database load + * @param options.adapter - an instance of a loki persistence adapter + * @param [options.serializationMethod='normal'] - ['normal', 'pretty', 'destructured'] + * @param options.destructureDelimiter - string delimiter used for destructured serialization + * @param [options.throttledSaves=true] - debounces multiple calls to to saveDatabase reducing number of disk I/O operations + and guaranteeing proper serialization of the calls. + */ + constructor(filename: string, options?: Partial & Partial & Partial); + + // experimental support for browserify's abstract syntax scan to pick up dependency of indexed adapter. + // Hopefully, once this hits npm a browserify require of lokijs should scan the main file and detect this indexed adapter reference. + public getIndexedAdapter(): any; + + /** + * Allows reconfiguring database options + * + * @param options - configuration options to apply to loki db object + * @param options.env - override environment detection as 'NODEJS', 'BROWSER', 'CORDOVA' + * @param options.verbose - enable console output (default is 'false') + * @param options.autosave - enables autosave + * @param options.autosaveInterval - time interval (in milliseconds) between saves (if dirty) + * @param options.autoload - enables autoload on loki instantiation + * @param options.autoloadCallback - user callback called after database load + * @param options.adapter - an instance of a loki persistence adapter + * @param options.serializationMethod - ['normal', 'pretty', 'destructured'] + * @param options.destructureDelimiter - string delimiter used for destructured serialization + * @param initialConfig - (internal) true is passed when loki ctor is invoking + */ + public configureOptions(options?: Partial & Partial, initialConfig?: boolean): void; + + /** + * Copies 'this' database into a new Loki instance. Object references are shared to make lightweight. + * + * @param options - apply or override collection level settings + * @param options.removeNonSerializable - nulls properties not safe for serialization. + */ + public copy(options?: { removeNonSerializable?: boolean }): Loki; + + /** + * Adds a collection to the database. + * @param name - name of collection to add + * @param options - (optional) options to configure collection with. + * @param [options.unique=[]] - array of property names to define unique constraints for + * @param [options.exact=[]] - array of property names to define exact constraints for + * @param [options.indices=[]] - array property names to define binary indexes for + * @param [options.asyncListeners=false] - whether listeners are called asynchronously + * @param [options.disableChangesApi=true] - set to false to enable Changes Api + * @param [options.autoupdate=false] - use Object.observe to update objects automatically + * @param [options.clone=false] - specify whether inserts and queries clone to/from user + * @param [options.cloneMethod='parse-stringify'] - 'parse-stringify', 'jquery-extend-deep', 'shallow, 'shallow-assign' + * @param options.ttlInterval - time interval for clearing out 'aged' documents; not set by default. + * @returns a reference to the collection which was just added + */ + public addCollection(name: string, options?: Partial>): Collection; + + public loadCollection(collection: Collection): void; + + /** + * Retrieves reference to a collection by name. + * @param collectionName - name of collection to look up + * @returns Reference to collection in database by that name, or null if not found + */ + public getCollection(collectionName: string): Collection; + + /** + * Renames an existing loki collection + * @param oldName - name of collection to rename + * @param newName - new name of collection + * @returns reference to the newly renamed collection + */ + public renameCollection(oldName: string, newName: string): Collection; + + public listCollections(): Collection[]; + + /** + * Removes a collection from the database. + * @param collectionName - name of collection to remove + */ + public removeCollection(collectionName: string): void; + + public getName(): string; + + /** + * serializeReplacer - used to prevent certain properties from being serialized + */ + public serializeReplacer(key: "autosaveHandle" | "persistenceAdapter" | "constraints" | "ttl" | "throttledSavePending" | "throttledCallbacks" | string, value: any): any; + + /** + * Serialize database to a string which can be loaded via {@link Loki#loadJSON} + * + * @returns Stringified representation of the loki database. + */ + public serialize(): string; + public serialize(options: { serializationMethod?: "normal" | "pretty" }): string; + public serialize(options: { serializationMethod: "destructured" }): string[]; + public serialize(options?: { serializationMethod?: string | null }): string | string[]; + public serialize(options?: { serializationMethod?: string | null }): string | string[]; + + // alias of serialize + public toJson: Loki["serialize"]; + + /** + * Database level destructured JSON serialization routine to allow alternate serialization methods. + * Internally, Loki supports destructuring via loki "serializationMethod' option and + * the optional LokiPartitioningAdapter class. It is also available if you wish to do + * your own structured persistence or data exchange. + * + * @param options - output format options for use externally to loki + * @param options.partitioned - (default: false) whether db and each collection are separate + * @param options.partition - can be used to only output an individual collection or db (-1) + * @param options.delimited - (default: true) whether subitems are delimited or subarrays + * @param options.delimiter - override default delimiter + * + * @returns A custom, restructured aggregation of independent serializations. + */ + public serializeDestructured(options?: { delimited?: boolean; delimiter?: string; partitioned?: boolean; partition?: number; }): string | string[]; + + /** + * Collection level utility method to serialize a collection in a 'destructured' format + * + * @param [options] - used to determine output of method + * @param [options.delimited] - whether to return single delimited string or an array + * @param [options.delimiter] - (optional) if delimited, this is delimiter to use + * @param [options.collectionIndex] - specify which collection to serialize data for + * + * @returns A custom, restructured aggregation of independent serializations for a single collection. + */ + public serializeCollection(options?: { delimited?: boolean; collectionIndex?: number; delimiter?: string }): string | string[]; + + /** + * Database level destructured JSON deserialization routine to minimize memory overhead. + * Internally, Loki supports destructuring via loki "serializationMethod' option and + * the optional LokiPartitioningAdapter class. It is also available if you wish to do + * your own structured persistence or data exchange. + * + * @param destructuredSource - destructured json or array to deserialize from + * @param [options] - source format options + * @param [options.partitioned=false] - whether db and each collection are separate + * @param [options.partition] - can be used to deserialize only a single partition + * @param [options.delimited=true] - whether subitems are delimited or subarrays + * @param [options.delimiter] - override default delimiter + * + * @returns An object representation of the deserialized database, not yet applied to 'this' db or document array + */ + public deserializeDestructured(destructuredSource: string | string[] | null, options?: DeserializeOptions): any; + + /** + * Collection level utility function to deserializes a destructured collection. + * + * @param destructuredSource - destructured representation of collection to inflate + * @param [options] - used to describe format of destructuredSource input + * @param [options.delimited=false] - whether source is delimited string or an array + * @param [options.delimiter] - if delimited, this is delimiter to use (if other than default) + * + * @returns an array of documents to attach to collection.data. + */ + public deserializeCollection(destructuredSource: string | string[], options?: { partitioned?: boolean; delimited?: boolean; delimiter?: string; }): any[]; + + /** + * Inflates a loki database from a serialized JSON string + * + * @param serializedDb - a serialized loki database string + * @param [options] - apply or override collection level settings + * @param [options.serializationMethod] - the serialization format to deserialize + */ + public loadJSON(serializedDb: string, options?: { serializationMethod?: "normal" | "pretty" | "destructured" | null } & { retainDirtyFlags?: boolean; throttledSaves?: boolean;[collName: string]: any | { proto?: any; inflate?: (src: object, dest?: object) => void } }): void; + + /** + * Inflates a loki database from a JS object + * + * @param dbObject - a serialized loki database string + * @param options - apply or override collection level settings + * @param options.retainDirtyFlags - whether collection dirty flags will be preserved + */ + public loadJSONObject(dbObject: { name?: string; throttledSaves: boolean; collections: Collection[]; databaseVersion: number }, + options?: { retainDirtyFlags?: boolean; throttledSaves?: boolean;[collName: string]: any | { proto?: any; inflate?: (src: object, dest?: object) => void } }): void; + + /** + * Emits the close event. In autosave scenarios, if the database is dirty, this will save and disable timer. + * Does not actually destroy the db. + * + * @param callback - (Optional) if supplied will be registered with close event before emitting. + */ + public close(callback?: (err?: any) => void): void; + + /**-------------------------+ + | Changes API | + +--------------------------*/ + + /** + * The Changes API enables the tracking the changes occurred in the collections since the beginning of the session, + * so it's possible to create a differential dataset for synchronization purposes (possibly to a remote db) + */ + + /** + * (Changes API) : takes all the changes stored in each + * collection and creates a single array for the entire database. If an array of names + * of collections is passed then only the included collections will be tracked. + * + * @param optional array of collection names. No arg means all collections are processed. + * @returns array of changes + * @see private method createChange() in Collection + */ + public generateChangesNotification(arrayOfCollectionNames?: string[] | null): CollectionChange[]; + + /** + * (Changes API) - stringify changes for network transmission + * @returns string representation of the changes + */ + public serializeChanges(collectionNamesArray?: string[]): string; + + /** + * (Changes API) : clears all the changes in all collections. + */ + public clearChanges(): void; + + /** + * Wait for throttledSaves to complete and invoke your callback when drained or duration is met. + * + * @param callback - callback to fire when save queue is drained, it is passed a sucess parameter value + * @param [options] - configuration options + * @param [options.recursiveWait] - (default: true) if after queue is drained, another save was kicked off, wait for it + * @param [options.recursiveWaitLimit] - (default: false) limit our recursive waiting to a duration + * @param [options.recursiveWaitLimitDelay] - (default: 2000) cutoff in ms to stop recursively re-draining + */ + public throttledSaveDrain(callback: (result?: boolean) => void, options?: Partial): void; + + /** + * Internal load logic, decoupled from throttling/contention logic + * + * @param [options] - not currently used (remove or allow overrides?) + * @param [callback] - (Optional) user supplied async callback / error handler + */ + public loadDatabaseInternal(options?: any, callback?: (err?: any, data?: any) => void): void; + + /** + * Handles manually loading from file system, local storage, or adapter (such as indexeddb) + * This method utilizes loki configuration options (if provided) to determine which + * persistence method to use, or environment detection (if configuration was not provided). + * To avoid contention with any throttledSaves, we will drain the save queue first. + * + * If you are configured with autosave, you do not need to call this method yourself. + * + * @param [options] - if throttling saves and loads, this controls how we drain save queue before loading + * @param [options.recursiveWait] - (default: true) wait recursively until no saves are queued + * @param [options.recursiveWaitLimit] - (default: false) limit our recursive waiting to a duration + * @param [options.recursiveWaitLimitDelay] - (default: 2000) cutoff in ms to stop recursively re-draining + * @param [callback] - (Optional) user supplied async callback / error handler + * @example + * db.loadDatabase({}, function(err) { + * if (err) { + * console.log("error : " + err); + * } + * else { + * console.log("database loaded."); + * } + * }); + */ + public loadDatabase(options?: Partial, callback?: (err: any) => void): void; + + /** + * Internal save logic, decoupled from save throttling logic + */ + public saveDatabaseInternal(callback?: (err: any) => void): void; + + /** + * Handles manually saving to file system, local storage, or adapter (such as indexeddb) + * This method utilizes loki configuration options (if provided) to determine which + * persistence method to use, or environment detection (if configuration was not provided). + * + * If you are configured with autosave, you do not need to call this method yourself. + * + * @param [callback] - (Optional) user supplied async callback / error handler + * @example + * db.saveDatabase(function(err) { + * if (err) { + * console.log("error : " + err); + * } + * else { + * console.log("database saved."); + * } + * }); + */ + public saveDatabase(callback?: (err?: any) => void): void; + + // alias + public save: Loki["saveDatabase"]; + + /** + * Handles deleting a database from file system, local + * storage, or adapter (indexeddb) + * This method utilizes loki configuration options (if provided) to determine which + * persistence method to use, or environment detection (if configuration was not provided). + * + * @param callback - (Optional) user supplied async callback / error handler + */ + public deleteDatabase(callback: (err?: any, data?: any) => void): void; + public deleteDatabase(options?: null, callback?: (err?: any, data?: any) => void): void; + public deleteDatabase(options?: ((err?: any, data?: any) => void) | null, callback?: (err?: any, data?: any) => void): void; + + /** + * autosaveDirty - check whether any collections are 'dirty' meaning we need to save (entire) database + * + * @returns true if database has changed since last autosave, false if not. + */ + public autosaveDirty(): boolean; + + /** + * autosaveClearFlags - resets dirty flags on all collections. + * Called from saveDatabase() after db is saved. + * + */ + public autosaveClearFlags(): void; + + /** + * autosaveEnable - begin a javascript interval to periodically save the database. + * + * @param [options] - not currently used (remove or allow overrides?) + * @param [callback] - (Optional) user supplied async callback + */ + public autosaveEnable(options?: any, callback?: (err?: any) => void): void; + + /** + * autosaveDisable - stop the autosave interval timer. + */ + public autosaveDisable(): void; +} + + /*------------------+ | PERSISTENCE | -------------------*/ /** there are two build in persistence adapters for internal use - * fs for use in Nodejs type environments - * localStorage for use in browser environment - * defined as helper classes here so its easy and clean to use - */ + * fs for use in Nodejs type environments + * localStorage for use in browser environment + * defined as helper classes here so its easy and clean to use + */ -interface LokiPersistenceInterface { - loadDatabase(dbname: string, callback: (dataOrErr: string | Error) => void): void; - saveDatabase(dbname: string, dbstring: string, callback: (resOrErr: void | Error) => void): void; - deleteDatabase(dbname: string, callback?: (resOrErr: void | Error) => void): void; - // optional - mode?: string; // 'reference' - // filename may seem redundant but loadDatabase will need to expect this same filename - exportDatabase?(filename: string, param: any, callback?: (err: any) => void): void; +interface LokiPersistenceAdapter { + mode?: string; + loadDatabase(dbname: string, callback: (value: any) => void): void; + deleteDatabase?(dbnameOrOptions: any, callback: (err?: Error | null, data?: any) => void): void; + exportDatabase?(dbname: string, dbref: Loki, callback: (err: Error | null) => void): void; + saveDatabase?(dbname: string, dbstring: any, callback: (err?: Error | null) => void): void; } -/** constructor for fs +/** + * In in-memory persistence adapter for an in-memory database. + * This simple 'key/value' adapter is intended for unit testing and diagnostics. + * + * @param [options] - memory adapter options + * @param [options.asyncResponses=false] - whether callbacks are invoked asynchronously + * @param [options.asyncTimeout=50] - timeout in ms to queue callbacks + * @constructor LokiMemoryAdapter */ -interface LokiFsAdapter extends LokiPersistenceInterface { - fs: any; //require('fs'); +declare class LokiMemoryAdapter implements LokiPersistenceAdapter { + hashStore: { [name: string]: { savecount: number; lastsave: Date; value: string } }; + options: { asyncResponses?: boolean; asyncTimeout?: number }; - /** loadDatabase() - Load data from file, will throw an error if the file does not exist - * @param {string} dbname - the filename of the database to load - * @param {function} callback - the callback to handle the result + constructor(options?: { asyncResponses?: boolean; asyncTimeout?: number }); + + /** + * Loads a serialized database from its in-memory store. + * (Loki persistence adapter interface function) + * + * @param dbname - name of the database (filename/keyname) + * @param callback - adapter callback to return load result to caller */ - loadDatabase(dbname: string, callback: (err: Error, data: string) => void): void; + public loadDatabase(dbname: string, callback: (value: any) => void): void; - /** saveDatabase() - save data to file, will throw an error if the file can't be saved + /** + * Saves a serialized database to its in-memory store. + * (Loki persistence adapter interface function) + * + * @param dbname - name of the database (filename/keyname) + * @param callback - adapter callback to return load result to caller + */ + public saveDatabase(dbname: string, dbstring: any, callback: (err?: Error | null) => void): void; + + /** + * Deletes a database from its in-memory store. + * + * @param dbname - name of the database (filename/keyname) + * @param callback - function to call when done + */ + public deleteDatabase(dbname: string, callback: (err?: Error | null) => void): void; +} + + + +interface PageIterator { + collection: number; + pageIndex: number; + docIndex: number; +} + + +/** + * An adapter for adapters. Converts a non reference mode adapter into a reference mode adapter + * which can perform destructuring and partioning. Each collection will be stored in its own key/save and + * only dirty collections will be saved. If you turn on paging with default page size of 25megs and save + * a 75 meg collection it should use up roughly 3 save slots (key/value pairs sent to inner adapter). + * A dirty collection that spans three pages will save all three pages again + * Paging mode was added mainly because Chrome has issues saving 'too large' of a string within a + * single indexeddb row. If a single document update causes the collection to be flagged as dirty, all + * of that collection's pages will be written on next save. + * + * @param adapter - reference to a 'non-reference' mode loki adapter instance. + * @param options - configuration options for partitioning and paging + * @param [options.paging] - (default: false) set to true to enable paging collection data. + * @param [options.pageSize] - (default : 25MB) you can use this to limit size of strings passed to inner adapter. + * @param [options.delimiter] - allows you to override the default delimeter + * @constructor LokiPartitioningAdapter + */ +declare class LokiPartitioningAdapter implements LokiPersistenceAdapter { + mode: string; + dbref: Loki | null; + dbname: string + adapter: LokiPersistenceAdapter | null; + options: { paging?: boolean; pageSize?: number; delimiter?: string }; + pageIterator: PageIterator | {}; + dirtyPartitions: number[] | undefined; + + constructor(adapter: LokiPersistenceAdapter, options?: { paging?: boolean; pageSize?: number; delimiter?: string }); + + /** + * Loads a database which was partitioned into several key/value saves. + * (Loki persistence adapter interface function) + * + * @param dbname - name of the database (filename/keyname) + * @param callback - adapter callback to return load result to caller + */ + public loadDatabase(dbname: string, callback: (dbOrErr: Loki | null | Error) => void): void; + + /** + * Used to sequentially load each collection partition, one at a time. + * + * @param partition - ordinal collection position to load next + * @param callback - adapter callback to return load result to caller + */ + public loadNextPartition(partition: number, callback: () => void): void; + + /** + * Used to sequentially load the next page of collection partition, one at a time. + * + * @param callback - adapter callback to return load result to caller + */ + public loadNextPage(callback: () => void): void; + + /** + * Saves a database by partioning into separate key/value saves. + * (Loki 'reference mode' persistence adapter interface function) + * + * @param dbname - name of the database (filename/keyname) + * @param dbref - reference to database which we will partition and save. + * @param callback - adapter callback to return load result to caller + */ + public exportDatabase(dbname: string, dbref: Loki, callback: (err: Error | null) => void): void; + + /** + * Helper method used internally to save each dirty collection, one at a time. + * + * @param callback - adapter callback to return load result to caller + */ + public saveNextPartition(callback: (err: Error | null) => void): void; + + /** + * Helper method used internally to generate and save the next page of the current (dirty) partition. + * + * @param callback - adapter callback to return load result to caller + */ + public saveNextPage(callback: (err: Error | null) => void): void; +} + + + +/** + * A loki persistence adapter which persists using node fs module + * @constructor LokiFsAdapter + */ +declare class LokiFsAdapter implements LokiPersistenceAdapter { + + constructor(); + + /** + * loadDatabase() - Load data from file, will throw an error if the file does not exist + * @param dbname - the filename of the database to load + * @param callback - the callback to handle the result + */ + public loadDatabase(dbname: string, callback: (data: any | Error) => void): void; + + /** + * saveDatabase() - save data to file, will throw an error if the file can't be saved * might want to expand this to avoid dataloss on partial save - * @param {string} dbname - the filename of the database to load - * @param {function} callback - the callback to handle the result + * @param dbname - the filename of the database to load + * @param callback - the callback to handle the result */ - saveDatabase(dbname: string, dbstring: string, callback: (err: any) => void): void; + public saveDatabase(dbname: string, dbstring: string | Uint8Array, callback: (err?: Error | null) => void): void; - /** deleteDatabase() - delete the database file, will throw an error if the + /** + * deleteDatabase() - delete the database file, will throw an error if the * file can't be deleted - * @param {string} dbname - the filename of the database to delete - * @param {function} callback - the callback to handle the result + * @param dbname - the filename of the database to delete + * @param callback - the callback to handle the result */ - deleteDatabase(dbname: string, callback: (resOrErr: void | Error) => void): void; + public deleteDatabase(dbname: string, callback: (err?: Error | null) => void): void; } -/** constructor for local storage + +/** + * A loki persistence adapter which persists to web browser's local storage object + * @constructor LokiLocalStorageAdapter */ -interface LokiLocalStorageAdapter extends LokiPersistenceInterface { +declare class LokiLocalStorageAdapter { - /** loadDatabase() - Load data from localstorage - * @param {string} dbname - the name of the database to load - * @param {function} callback - the callback to handle the result + /** + * loadDatabase() - Load data from localstorage + * @param dbname - the name of the database to load + * @param callback - the callback to handle the result */ - loadDatabase(dbname: string, callback: (dataOrErr: string | Error) => void): void; + public loadDatabase(dbname: string, callback: (dataOrError: any | Error) => void): void; - /** saveDatabase() - save data to localstorage, will throw an error if the file can't be saved + /** + * saveDatabase() - save data to localstorage, will throw an error if the file can't be saved * might want to expand this to avoid dataloss on partial save - * @param {string} dbname - the filename of the database to load - * @param {function} callback - the callback to handle the result + * @param dbname - the filename of the database to load + * @param callback - the callback to handle the result */ - saveDatabase(dbname: string, dbstring: string, callback: (resOrErr: void | Error) => void): void; + public saveDatabase(dbname: string, dbstring: string, callback: (err?: Error | null) => void): void; - /** deleteDatabase() - delete the database from localstorage, will throw an error if it + /** + * deleteDatabase() - delete the database from localstorage, will throw an error if it * can't be deleted - * @param {string} dbname - the filename of the database to delete - * @param {function} callback - the callback to handle the result + * @param dbname - the filename of the database to delete + * @param callback - the callback to handle the result */ - deleteDatabase(dbname: string, callback: (resOrErr: void | Error) => void): void; + public deleteDatabase(dbname: string, callback: (err?: Error | null) => void): void; } +interface GetDataOptions { + forceClones: boolean; + forceCloneMethod: ("parse-stringify" | "jquery-extend-deep" | "shallow" | "shallow-assign" | "shallow-recurse-objects") | null; + removeMeta: boolean; +} -/** Resultset class allowing chainable queries. Intended to be instanced internally. + +/** + * Resultset class allowing chainable queries. Intended to be instanced internally. * Collection.find(), Collection.where(), and Collection.chain() instantiate this. * - * Example: + * @example * mycollection.chain() * .find({ 'doors' : 4 }) * .where(function(obj) { return obj.name === 'Toyota' }) * .data(); */ -interface LokiResultset { - // retain reference to collection we are querying against - collection: LokiCollection; +declare class Resultset { + collection: Collection; + filteredrows: number[]; filterInitialized: boolean; - filteredrows: string[]; // technically number[] (e.g. = Object.keys(this.collection.data)) - options: LokiResultsetOptions; - searchIsChained: boolean; - /** - * @constructor - * @param {Collection} collection - The collection which this Resultset will query against. - * @param {Object} options - Object containing one or more options. - * @param {string} options.queryObj - Optional mongo-style query object to initialize resultset with. - * @param {function} options.queryFunc - Optional javascript filter function to initialize resultset with. - * @param {bool} options.firstOnly - Optional boolean used by collection.findOne(). + * @param collection - The collection which this Resultset will query against. + * @param options */ - new (collection: LokiCollection, options: LokiResultsetOptions): LokiResultset | E[]; + constructor(collection: Collection, options?: any); - /** reset() - Reset the resultset to its initial state. + /** + * reset() - Reset the resultset to its initial state. * - * @returns {Resultset} Reference to this resultset, for future chain operations. + * @returns Reference to this resultset, for future chain operations. */ - reset(): LokiResultset; + public reset(): this; - /** toJSON() - Override of toJSON to avoid circular references + /** + * toJSON() - Override of toJSON to avoid circular references */ - toJSON(): LokiResultset; + public toJSON(): Resultset; - /** limit() - Allows you to limit the number of documents passed to next chain operation. + /** + * Allows you to limit the number of documents passed to next chain operation. * A resultset copy() is made to avoid altering original resultset. * - * @param {int} qty - The number of documents to return. - * @returns {Resultset} Returns a copy of the resultset, limited by qty, for subsequent chain ops. + * @param qty - The number of documents to return. + * @returns Returns a copy of the resultset, limited by qty, for subsequent chain ops. */ - limit(qty: number): LokiResultset; + public limit(qty: number): Resultset; - /** offset() - Used for skipping 'pos' number of documents in the resultset. + /** + * Used for skipping 'pos' number of documents in the resultset. * - * @param {int} pos - Number of documents to skip; all preceding documents are filtered out. - * @returns {Resultset} Returns a copy of the resultset, containing docs starting at 'pos' for subsequent chain ops. + * @param pos - Number of documents to skip; all preceding documents are filtered out. + * @returns Returns a copy of the resultset, containing docs starting at 'pos' for subsequent chain ops. */ - offset(pos: number): LokiResultset; + public offset(pos: number): Resultset; - /** copy() - To support reuse of resultset in branched query situations. + /** + * copy() - To support reuse of resultset in branched query situations. * - * @returns {Resultset} Returns a copy of the resultset (set) but the underlying document references will be the same. + * @returns Returns a copy of the resultset (set) but the underlying document references will be the same. */ - copy(): LokiResultset; - // alias of copy() - branch(): LokiResultset; + public copy(): Resultset; + + /** + * Alias of copy() + */ + public branch: Resultset["copy"]; /** * transform() - executes a named collection transform or raw array of transform steps against the resultset. * - * @param transform {string|array} : (Optional) name of collection transform or raw transform array - * @param parameters {object} : (Optional) object property hash of parameters, if the transform requires them. - * @returns {Resultset} : either (this) resultset or a clone of of this resultset (depending on steps) + * @param transform - name of collection transform or raw transform array + * @param parameters - (Optional) object property hash of parameters, if the transform requires them. + * @returns either (this) resultset or a clone of of this resultset (depending on steps) */ - transform(transform?: string | any[], parameters?: any): LokiResultset; + public transform(transform: string | string[] | Transform[], parameters?: object): Resultset; - /** sort() - User supplied compare function is provided two documents to compare. (chainable) - * Example: + /** + * User supplied compare function is provided two documents to compare. (chainable) + * @example * rslt.sort(function(obj1, obj2) { * if (obj1.name === obj2.name) return 0; * if (obj1.name > obj2.name) return 1; * if (obj1.name < obj2.name) return -1; * }); * - * @param {function} comparefun - A javascript compare function used for sorting. - * @returns {Resultset} Reference to this resultset, sorted, for future chain operations. + * @param comparefun - A javascript compare function used for sorting. + * @returns Reference to this resultset, sorted, for future chain operations. */ - sort(comparefun: (a: E, b: E) => number): LokiResultset; + public sort(comparefun: (a: E & LokiObj, b: E & LokiObj) => number): this; - /** simplesort() - Simpler, loose evaluation for user to sort based on a property name. (chainable) + /** + * Simpler, loose evaluation for user to sort based on a property name. (chainable). + * Sorting based on the same lt/gt helper functions used for binary indices. * - * @param {string} propname - name of property to sort by. - * @param {bool} isdesc - (Optional) If true, the property will be sorted in descending order - * @returns {Resultset} Reference to this resultset, sorted, for future chain operations. + * @param propname - name of property to sort by. + * @param isdesc - (Optional) If true, the property will be sorted in descending order + * @returns Reference to this resultset, sorted, for future chain operations. */ - simplesort(propname: string, isdesc?: boolean): LokiResultset; + public simplesort(propname: keyof E, isdesc?: boolean): this; - /** compoundsort() - Allows sorting a resultset based on multiple columns. - * Example : rs.compoundsort(['age', 'name']); to sort by age and then name (both ascending) - * Example : rs.compoundsort(['age', ['name', true]); to sort by age (ascending) and then by name (descending) + /** + * Allows sorting a resultset based on multiple columns. + * @example + * // to sort by age and then name (both ascending) + * rs.compoundsort(['age', 'name']); + * // to sort by age (ascending) and then by name (descending) + * rs.compoundsort(['age', ['name', true]); * - * @param {array} properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order - * @returns {Resultset} Reference to this resultset, sorted, for future chain operations. + * @param properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order + * @returns Reference to this resultset, sorted, for future chain operations. */ - compoundsort(properties: ([string, boolean] | [string])[]): LokiResultset; + public compoundsort(properties: [keyof E, boolean][]): this; - /** calculateRange() - Binary Search utility method to find range/segment of values matching criteria. - * this is used for collection.find() and first find filter of resultset/dynview - * slightly different than get() binary search in that get() hones in on 1 value, - * but we have to hone in on many (range) - * @param {string} op - operation, such as $eq - * @param {string} prop - name of property to calculate range for - * @param {object} val - value to use for range calculation. - * @returns {array} [start, end] index array positions - */ - calculateRange(op: "$eq", prop: string, val: any): [number/*start*/, number/*end*/]; - calculateRange(op: "$dteq", prop: string, val: any): [number/*start*/, number/*end*/]; - calculateRange(op: "$gt", prop: string, val: any): [number/*start*/, number/*end*/]; - calculateRange(op: "$gte", prop: string, val: any): [number/*start*/, number/*end*/]; - calculateRange(op: "$lt", prop: string, val: any): [number/*start*/, number/*end*/]; - calculateRange(op: "$lte", prop: string, val: any): [number/*start*/, number/*end*/]; - calculateRange(op: string, prop: string, val: any): [number/*start*/, number/*end*/]; - - /** findOr() - oversee the operation of OR'ed query expressions. + /** + * findOr() - oversee the operation of OR'ed query expressions. * OR'ed expression evaluation runs each expression individually against the full collection, * and finally does a set OR on each expression's results. * Each evaluation can utilize a binary index to prevent multiple linear array scans. * - * @param {array} expressionArray - array of expressions - * @returns {Resultset} this resultset for further chain ops. + * @param expressionArray - array of expressions + * @returns this resultset for further chain ops. */ - findOr(expressionArray: LokiQuery[]): LokiResultset; - $or(expressionArray: LokiQuery[]): LokiResultset; + public findOr(expressionArray: LokiQuery[]): this; - /** findAnd() - oversee the operation of AND'ed query expressions. + public $or: Resultset["findOr"]; + + /** + * findAnd() - oversee the operation of AND'ed query expressions. * AND'ed expression evaluation runs each expression progressively against the full collection, * internally utilizing existing chained resultset functionality. * Only the first filter can utilize a binary index. * - * @param {array} expressionArray - array of expressions - * @returns {Resultset} this resultset for further chain ops. + * @param expressionArray - array of expressions + * @returns this resultset for further chain ops. */ - findAnd(expressionArray: LokiQuery[]): LokiResultset; - $and(expressionArray: LokiQuery[]): LokiResultset; + public findAnd(expressionArray: LokiQuery[]): this; - /** find() - Used for querying via a mongo-style query object. + public $and: Resultset["findAnd"]; + + /** + * Used for querying via a mongo-style query object. * - * @param {object} query - A mongo-style query object used for filtering current results. - * @param {boolean} firstOnly - (Optional) Used by collection.findOne() - * @returns {Resultset} this resultset for further chain ops. + * @param query - A mongo-style query object used for filtering current results. + * @param firstOnly - (Optional) Used by collection.findOne() + * @returns this resultset for further chain ops. */ - //find(query: LokiQuery, firstOnly: boolean): E; - //find(query?: any, firstOnly?: boolean): E[]; - find(query: LokiQuery, firstOnly?: boolean): LokiResultset; + public find(query?: LokiQuery, firstOnly?: boolean): this; - /** where() - Used for filtering via a javascript filter function. + /** + * where() - Used for filtering via a javascript filter function. * - * @param {function} fun - A javascript function used for filtering current results by. - * @returns {Resultset} this resultset for further chain ops. + * @param fun - A javascript function used for filtering current results by. + * @returns this resultset for further chain ops. */ - where(fun: (obj: E) => boolean): LokiResultset; + public where(fun: (data: E & LokiObj) => boolean): this; - /** count() - returns the number of documents in the resultset. + /** + * count() - returns the number of documents in the resultset. * - * @returns {number} The number of documents in the resultset. + * @returns The number of documents in the resultset. */ - count(): number; + public count(): number; - /** data() - Terminates the chain and returns array of filtered documents + /** + * Terminates the chain and returns array of filtered documents * - * @param options {object} : allows specifying 'forceClones' and 'forceCloneMethod' options. - * options : - * forceClones {boolean} : Allows forcing the return of cloned objects even when + * @param [options] - allows specifying 'forceClones' and 'forceCloneMethod' options. + * @param [options.forceClones] - Allows forcing the return of cloned objects even when * the collection is not configured for clone object. - * forceCloneMethod {string} : Allows overriding the default or collection specified cloning method. - * Possible values include 'parse-stringify', 'jquery-extend-deep', and 'shallow' + * @param [options.forceCloneMethod] - Allows overriding the default or collection specified cloning method. + * Possible values include 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign' + * @param [options.removeMeta] - Will force clones and strip $loki and meta properties from documents * - * @returns {array} Array of documents in the resultset + * @returns Array of documents in the resultset */ - data(options?: { forceClones?: string; forceCloneMethod?: string; }): E[]; + public data(options?: Partial): (E & LokiObj)[]; - /** update() - used to run an update operation on all documents currently in the resultset. + /** + * Used to run an update operation on all documents currently in the resultset. * - * @param {function} updateFunction - User supplied updateFunction(obj) will be executed for each document object. - * @returns {Resultset} this resultset for further chain ops. + * @param updateFunction - User supplied updateFunction(obj) will be executed for each document object. + * @returns this resultset for further chain ops. */ - update(updateFunction: (obj: E) => void): LokiResultset; + public update(updateFunction: (obj: E) => void): this; - /** remove() - removes all document objects which are currently in resultset from collection (as well as resultset) + /** + * Removes all document objects which are currently in resultset from collection (as well as resultset) * - * @returns {Resultset} this (empty) resultset for further chain ops. + * @returns this (empty) resultset for further chain ops. */ - remove(): LokiResultset; + public remove(): this; - /** mapReduce() - data transformation via user supplied functions + /** + * data transformation via user supplied functions * - * @param {function} mapFunction - this function accepts a single document for you to transform and return - * @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value + * @param mapFunction - this function accepts a single document for you to transform and return + * @param reduceFunction - this function accepts many (array of map outputs) and returns single value * @returns The output of your reduceFunction */ - mapReduce(mapFunction: (value: E, index: number, array: E[]) => T, reduceFunction: (array: T[]) => U): U; + public mapReduce(mapFunction: (value: E, index: number, array: E[]) => U, reduceFunction: (ary: U[]) => R): R; - /** eqJoin() - Left joining two sets of data. Join keys can be defined or calculated properties + /** + * eqJoin() - Left joining two sets of data. Join keys can be defined or calculated properties * eqJoin expects the right join key values to be unique. Otherwise left data will be joined on the last joinData object with that key - * @param {Array} joinData - Data array to join to. - * @param {String,function} leftJoinKey - Property name in this result set to join on or a function to produce a value to join on - * @param {String,function} rightJoinKey - Property name in the joinData to join on or a function to produce a value to join on - * @param {function} (optional) mapFun - A function that receives each matching pair and maps them into output objects - function(left,right){return joinedObject} - * @returns {Resultset} A resultset with data in the format [{left: leftObj, right: rightObj}] + * @param joinData - Data array to join to. + * @param leftJoinKey - Property name in this result set to join on or a function to produce a value to join on + * @param rightJoinKey - Property name in the joinData to join on or a function to produce a value to join on + * @param [mapFun] - (Optional) A function that receives each matching pair and maps them into output objects - function(left,right){return joinedObject} + * @param [dataOptions] - options to data() before input to your map function + * @param [dataOptions.removeMeta] - allows removing meta before calling mapFun + * @param [dataOptions.forceClones] - forcing the return of cloned objects to your map object + * @param [dataOptions.forceCloneMethod] - Allows overriding the default or collection specified cloning method. + * @returns A resultset with data in the format [{left: leftObj, right: rightObj}] */ - eqJoin(joinData: T[] | LokiResultset, leftJoinKey: string | ((obj: E) => string), rightJoinKey: string | ((obj: T) => string)): LokiResultset<{ left: E; right: T; }>; - eqJoin(joinData: T[] | LokiResultset, leftJoinKey: string | ((obj: E) => string), rightJoinKey: string | ((obj: T) => string), mapFun?: (a: E, b: T) => U): LokiResultset; + public eqJoin( + joinData: Collection | Resultset | any[], + leftJoinKey: string | ((obj: any) => string), + rightJoinKey: string | ((obj: any) => string), + mapFun?: (left: any, right: any) => any, + dataOptions?: Partial + ): Resultset; - map(mapFun: (currentValue: E, index: number, array: E[]) => T): LokiResultset; + /** + * Applies a map function into a new collection for further chaining. + * @param mapFun - javascript map function + * @param [dataOptions] - options to data() before input to your map function + * @param [dataOptions.removeMeta] - allows removing meta before calling mapFun + * @param [dataOptions.forceClones] - forcing the return of cloned objects to your map object + * @param [dataOptions.forceCloneMethod] - Allows overriding the default or collection specified cloning method. + */ + public map(mapFun: (value: E, index: number, array: E[]) => U, dataOptions?: Partial): Resultset; } +interface DynamicViewOptions { + persistent: boolean; + sortPriority: "active" | "passive"; + minRebuildInterval: number; +} -/** DynamicView class is a versatile 'live' view class which can have filters and sorts applied. + +/** + * DynamicView class is a versatile 'live' view class which can have filters and sorts applied. * Collection.addDynamicView(name) instantiates this DynamicView object and notifies it * whenever documents are add/updated/removed so it can remain up-to-date. (chainable) * - * Examples: - * var mydv = mycollection.addDynamicView('test'); // default is non-persistent - * mydv.applyWhere(function(obj) { return obj.name === 'Toyota'; }); - * mydv.applyFind({ 'doors' : 4 }); - * var results = mydv.data(); + * @example + * var mydv = mycollection.addDynamicView('test'); // default is non-persistent + * mydv.applyFind({ 'doors' : 4 }); + * mydv.applyWhere(function(obj) { return obj.name === 'Toyota'; }); + * var results = mydv.data(); * + * @implements LokiEventEmitter */ -interface LokiDynamicView extends LokiEventEmitter { - cachedresultset: LokiResultset; - collection: LokiCollection; - events: { [id: string]: ((...args: any[]) => void)[] }; /*{ - 'rebuild': ((...args) => void)[]; - };*/ - // keep ordered filter pipeline - filterPipeline: LokiFilter[]; - minRebuildInterval: number; +declare class DynamicView extends LokiEventEmitter { name: string; - options: LokiDynamicViewOptions; - persistent: boolean; + collection: Collection; rebuildPending: boolean; - resultset: LokiResultset; - resultdata: E[]; + resultset: Resultset; + resultdata: (E & LokiObj)[]; resultsdirty: boolean; - // sorting member variables, we only support one active search, applied using applySort() or applySimpleSort() - sortFunction: (a: E, b: E) => number; - sortCriteria: ([string, boolean] | [string])[]; + cachedresultset: Resultset | null; + filterPipeline: { type: "find" | "where", val: any; uid?: string | number }[]; + sortFunction: ((a: E & LokiObj, b: E & LokiObj) => number) | null; + sortCriteria: [keyof E, boolean][] | null; sortDirty: boolean; - sortPriority: string; // 'persistentSortPriority', 'passive' (will defer the sort phase until they call data(). most efficient overall), 'active' (will sort async whenever next idle. prioritizes read speeds) + options: Partial; /** - * @constructor - * @param {Collection} collection - A reference to the collection to work against - * @param {string} name - The name of this dynamic view - * @param {object} options - (Optional) Pass in object with 'persistent' and/or 'sortPriority' options. + * @param collection - A reference to the collection to work against + * @param name - The name of this dynamic view + * @param [options] - (Optional) Pass in object with 'persistent' and/or 'sortPriority' options. + * @param [options.persistent=false] - indicates if view is to main internal results array in 'resultdata' + * @param [options.sortPriority='passive'] - 'passive' (sorts performed on call to data) or 'active' (after updates) + * @param [options.minRebuildInterval] - minimum rebuild interval (need clarification to docs here) + * @see {@link Collection#addDynamicView} to construct instances of DynamicView */ - new (collection: LokiCollection, name: string, options?: LokiDynamicViewOptions): LokiDynamicView; + constructor(collection: Collection, name: string, options?: Partial); - /** rematerialize() - intended for use immediately after deserialization (loading) + /** + * rematerialize() - internally used immediately after deserialization (loading) * This will clear out and reapply filterPipeline ops, recreating the view. * Since where filters do not persist correctly, this method allows * restoring the view to state where user can re-apply those where filters. * - * @param {Object} options - (Optional) allows specification of 'removeWhereFilters' option - * @returns {DynamicView} This dynamic view for further chained ops. + * @param [options] - (Optional) allows specification of 'removeWhereFilters' option + * @returns This dynamic view for further chained ops. + * @fires DynamicView.rebuild */ - rematerialize(options?: { removeWhereFilters?: boolean; }): LokiDynamicView; + public rematerialize(options?: { removeWhereFilters?: boolean }): this; - /** branchResultset() - Makes a copy of the internal resultset for branched queries. + /** + * branchResultset() - Makes a copy of the internal resultset for branched queries. * Unlike this dynamic view, the branched resultset will not be 'live' updated, * so your branched query should be immediately resolved and not held for future evaluation. * - * @param {string|array} transform: Optional name of collection transform, or an array of transform steps - * @param {object} parameters: optional parameters (if optional transform requires them) - * @returns {Resultset} A copy of the internal resultset for branched queries. + * @param transform - Optional name of collection transform, or an array of transform steps + * @param [parameters] - optional parameters (if optional transform requires them) + * @returns A copy of the internal resultset for branched queries. */ - branchResultset(transform?: string | any[], parameters?: any): LokiResultset; + public branchResultset(transform: string | string[] | Transform[], parameters?: object): Resultset; - /** toJSON() - Override of toJSON to avoid circular references + /** + * toJSON() - Override of toJSON to avoid circular references */ - toJSON(): LokiDynamicView; + public toJSON(): DynamicView; - /** removeFilters() - Used to clear pipeline and reset dynamic view to initial state. + /** + * removeFilters() - Used to clear pipeline and reset dynamic view to initial state. * Existing options should be retained. + * @param [options] - configure removeFilter behavior + * @param [options.queueSortPhase] - (default: false) if true we will async rebuild view (maybe set default to true in future?) */ - removeFilters(): void; + public removeFilters(options?: { queueSortPhase?: boolean }): void; - /** applySort() - Used to apply a sort to the dynamic view + /** + * applySort() - Used to apply a sort to the dynamic view + * @example + * dv.applySort(function(obj1, obj2) { + * if (obj1.name === obj2.name) return 0; + * if (obj1.name > obj2.name) return 1; + * if (obj1.name < obj2.name) return -1; + * }); * - * @param {function} comparefun - a javascript compare function used for sorting - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @param comparefun - a javascript compare function used for sorting + * @returns this DynamicView object, for further chain ops. */ - applySort(comparefun: (a: E, b: E) => number): LokiDynamicView; + public applySort(comparefun: (a: E & LokiObj, b: E & LokiObj) => number): this; - /** applySimpleSort() - Used to specify a property used for view translation. + /** + * applySimpleSort() - Used to specify a property used for view translation. + * @example + * dv.applySimpleSort("name"); * - * @param {string} propname - Name of property by which to sort. - * @param {boolean} isdesc - (Optional) If true, the sort will be in descending order. - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @param propname - Name of property by which to sort. + * @param [isdesc] - (Optional) If true, the sort will be in descending order. + * @returns this DynamicView object, for further chain ops. */ - applySimpleSort(propname: string, isdesc?: boolean): LokiDynamicView; + public applySimpleSort(propname: keyof E, isdesc?: boolean): this; - /** applySortCriteria() - Allows sorting a resultset based on multiple columns. - * Example : dv.applySortCriteria(['age', 'name']); to sort by age and then name (both ascending) - * Example : dv.applySortCriteria(['age', ['name', true]); to sort by age (ascending) and then by name (descending) - * Example : dv.applySortCriteria(['age', true], ['name', true]); to sort by age (descending) and then by name (descending) + /** + * applySortCriteria() - Allows sorting a resultset based on multiple columns. + * @example + * // to sort by age and then name (both ascending) + * dv.applySortCriteria(['age', 'name']); + * // to sort by age (ascending) and then by name (descending) + * dv.applySortCriteria(['age', ['name', true]); + * // to sort by age (descending) and then by name (descending) + * dv.applySortCriteria(['age', true], ['name', true]); * - * @param {array} properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order - * @returns {DynamicView} Reference to this DynamicView, sorted, for future chain operations. + * @param criteria - array of property names or subarray of [propertyname, isdesc] used evaluate sort order + * @returns Reference to this DynamicView, sorted, for future chain operations. */ - applySortCriteria(criteria: ([string, boolean] | [string])[]): LokiDynamicView; + public applySortCriteria(criteria: [keyof E, boolean][]): this; - /** startTransaction() - marks the beginning of a transaction. + /** + * startTransaction() - marks the beginning of a transaction. * - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @returns this DynamicView object, for further chain ops. */ - startTransaction(): LokiDynamicView; + public startTransaction(): this; - /** commit() - commits a transaction. + /** + * commit() - commits a transaction. * - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @returns this DynamicView object, for further chain ops. */ - commit(): LokiDynamicView; + public commit(): this; - /** rollback() - rolls back a transaction. + /** + * rollback() - rolls back a transaction. * - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @returns this DynamicView object, for further chain ops. */ - rollback(): LokiDynamicView; + public rollback(): this; - /** Implementation detail. + /** + * Implementation detail. * _indexOfFilterWithId() - Find the index of a filter in the pipeline, by that filter's ID. * - * @param {string|number} uid - The unique ID of the filter. - * @returns {number}: index of the referenced filter in the pipeline; -1 if not found. + * @param [uid] - The unique ID of the filter. + * @returns index of the referenced filter in the pipeline; -1 if not found. */ - _indexOfFilterWithId(uid: string | number): number; + public _indexOfFilterWithId(uid?: string | number): number; - /** Implementation detail. + /** + * Implementation detail. * _addFilter() - Add the filter object to the end of view's filter pipeline and apply the filter to the resultset. * - * @param {object} filter - The filter object. Refer to applyFilter() for extra details. + * @param filter - The filter object. Refer to applyFilter() for extra details. */ - _addFilter(filter: LokiFilter): void; + public _addFilter(filter: { type: "find" | "where", val: any; uid?: string | number }): void; - /** reapplyFilters() - Reapply all the filters in the current pipeline. + /** + * reapplyFilters() - Reapply all the filters in the current pipeline. * - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @returns this DynamicView object, for further chain ops. */ - reapplyFilters(): LokiDynamicView; + public reapplyFilters(): this; - /** applyFilter() - Adds or updates a filter in the DynamicView filter pipeline + /** + * applyFilter() - Adds or updates a filter in the DynamicView filter pipeline * - * @param {object} filter - A filter object to add to the pipeline. + * @param filter - A filter object to add to the pipeline. * The object is in the format { 'type': filter_type, 'val', filter_param, 'uid', optional_filter_id } - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @returns this DynamicView object, for further chain ops. */ - applyFilter(filter: LokiFilter): LokiDynamicView; + public applyFilter(filter: { type: "find" | "where", val: any; uid?: string | number }): this; - /** applyFind() - Adds or updates a mongo-style query option in the DynamicView filter pipeline + /** + * applyFind() - Adds or updates a mongo-style query option in the DynamicView filter pipeline * - * @param {object} query - A mongo-style query object to apply to pipeline - * @param {string|number} uid - Optional: The unique ID of this filter, to reference it in the future. - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @param query - A mongo-style query object to apply to pipeline + * @param [uid] - Optional: The unique ID of this filter, to reference it in the future. + * @returns this DynamicView object, for further chain ops. */ - applyFind(query: LokiQuery, uid?: string | number): LokiDynamicView; + public applyFind(query: any, uid?: string | number): this; - /** applyWhere() - Adds or updates a javascript filter function in the DynamicView filter pipeline + /** + * applyWhere() - Adds or updates a javascript filter function in the DynamicView filter pipeline * - * @param {function} fun - A javascript filter function to apply to pipeline - * @param {string|number} uid - Optional: The unique ID of this filter, to reference it in the future. - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @param fun - A javascript filter function to apply to pipeline + * @param [uid] - Optional: The unique ID of this filter, to reference it in the future. + * @returns this DynamicView object, for further chain ops. */ - applyWhere(fun: (obj: E) => boolean, uid?: string | number): LokiDynamicView; + public applyWhere(fun: (obj: any) => boolean, uid?: string | number): this; - /** removeFilter() - Remove the specified filter from the DynamicView filter pipeline + /** + * removeFilter() - Remove the specified filter from the DynamicView filter pipeline * - * @param {string|number} uid - The unique ID of the filter to be removed. - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @param uid - The unique ID of the filter to be removed. + * @returns this DynamicView object, for further chain ops. */ - removeFilter(uid: string | number): LokiDynamicView; + public removeFilter(uid: string | number): this; - /** count() - returns the number of documents representing the current DynamicView contents. + /** + * count() - returns the number of documents representing the current DynamicView contents. * - * @returns {number} The number of documents representing the current DynamicView contents. + * @returns The number of documents representing the current DynamicView contents. */ - count(): number; + public count(): number; - /** data() - resolves and pending filtering and sorting, then returns document array as result. + /** + * data() - resolves and pending filtering and sorting, then returns document array as result. * - * @returns {array} An array of documents representing the current DynamicView contents. + * @param [options] - optional parameters to pass to resultset.data() if non-persistent + * @param [options.forceClones] - Allows forcing the return of cloned objects even when + * the collection is not configured for clone object. + * @param [options.forceCloneMethod] - Allows overriding the default or collection specified cloning method. + * Possible values include 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign' + * @param [options.removeMeta] - Will force clones and strip $loki and meta properties from documents + * @returns An array of documents representing the current DynamicView contents. */ - data(): E[]; + public data(options?: Partial): (E & LokiObj)[]; - /** queueRebuildEvent() - When the view is not sorted we may still wish to be notified of rebuild events. + /** + * queueRebuildEvent() - When the view is not sorted we may still wish to be notified of rebuild events. * This event will throttle and queue a single rebuild event when batches of updates affect the view. */ - queueRebuildEvent(): void; + public queueRebuildEvent(): void; - /** queueSortPhase : If the view is sorted we will throttle sorting to either : + /** + * queueSortPhase : If the view is sorted we will throttle sorting to either : * (1) passive - when the user calls data(), or * (2) active - once they stop updating and yield js thread control */ - queueSortPhase(): void; + public queueSortPhase(): void; - /** performSortPhase() - invoked synchronously or asynchronously to perform final sort phase (if needed) + /** + * performSortPhase() - invoked synchronously or asynchronously to perform final sort phase (if needed) */ - performSortPhase(options?: { suppressRebuildEvent?: boolean; }): void; + public performSortPhase(options?: { persistent?: boolean; suppressRebuildEvent?: boolean }): void; - /** evaluateDocument() - internal method for (re)evaluating document inclusion. + /** + * evaluateDocument() - internal method for (re)evaluating document inclusion. * Called by : collection.insert() and collection.update(). * - * @param {int} objIndex - index of document to (re)run through filter pipeline. - * @param {bool} isNew - true if the document was just added to the collection. + * @param objIndex - index of document to (re)run through filter pipeline. + * @param [isNew] - true if the document was just added to the collection. */ - evaluateDocument(objIndex: number, isNew?: boolean): void; + public evaluateDocument(objIndex: number | string, isNew?: boolean): void; - /** removeDocument() - internal function called on collection.delete() + + /** + * removeDocument() - internal function called on collection.delete() */ - removeDocument(objIndex: number): void; + public removeDocument(objIndex: number | string): void; - /** mapReduce() - data transformation via user supplied functions + /** + * mapReduce() - data transformation via user supplied functions * - * @param {function} mapFunction - this function accepts a single document for you to transform and return - * @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value + * @param mapFunction - this function accepts a single document for you to transform and return + * @param reduceFunction - this function accepts many (array of map outputs) and returns single value * @returns The output of your reduceFunction */ - mapReduce(mapFunction: (item: E, index: number, array: E[]) => T, reduceFunction: (array: T[]) => U): U; + public mapReduce(mapFunction: (value: E, index: number, array: E[]) => U, reduceFunction: (ary: U[]) => R): R; } - -/** Collection class that handles documents of same type - */ -interface LokiCollection extends LokiEventEmitter { - // option to observe objects and update them automatically, ignored if Object.observe is not supported - autoupdate: boolean; - // option to make event listeners async, default is sync - asyncListeners: boolean; - binaryIndices: { [id: string]: { name: string; dirty: boolean; values: number[] } }; - - cachedIndex: number[]; - cachedBinaryIndex: { [id: string]: { name: string; dirty: boolean; values: number[] } }; - cachedData: E[]; - // changes are tracked by collection and aggregated by the db - changes: LokiCollectionChange[]; - // default clone method (if enabled) is parse-stringify - cloneMethod: string; // 'parse-stringify' - // options to clone objects when inserting them - cloneObjects: boolean; - console: { - log: () => void; - warn: () => void; - error: () => void; - }; - constraints: { - unique: { [id: string]: LokiUniqueIndex }; - exact: { [id: string]: LokiExactIndex }; - }; - data: E[]; - // in autosave scenarios we will use collection level dirty flags to determine whether save is needed. - // currently, if any collection is dirty we will autosave the whole database if autosave is configured. - // defaulting to true since this is called from addCollection and adding a collection should trigger save - dirty: boolean; - // disable track changes - disableChangesApi: boolean; - DynamicViews: LokiDynamicView[]; - events: { [id: string]: ((...args: any[]) => void)[] }; /*{ - 'insert': ((...args) => void)[]; - 'update': ((...args) => void)[]; - 'pre-insert': ((...args) => void)[]; - 'pre-update': ((...args) => void)[]; - 'close': ((...args) => void)[]; - 'flushbuffer': ((...args) => void)[]; - 'error': ((...args) => void)[]; - 'delete': ((...args) => void)[]; - 'warning': ((...args) => void)[]; - };*/ - idIndex: number[]; - maxId: number; // currentMaxId - change manually at your own peril! +interface BinaryIndex { name: string; - // is collection transactional + dirty: boolean; + values: number[]; +} + + +interface CollectionOptions { + disableChangesApi: boolean; + disableDeltaChangesApi: boolean; + adaptiveBinaryIndices: boolean; + asyncListeners: boolean; + autoupdate: boolean; + clone: boolean; + cloneMethod: ("parse-stringify" | "jquery-extend-deep" | "shallow" | "shallow-assign" | "shallow-recurse-objects"); + serializableIndices: boolean; transactional: boolean; + ttl: number; + ttlInterval: number; + exact: (keyof E)[]; + unique: (keyof E)[]; + indices: (keyof E) | (keyof E)[]; +} + + +interface CollectionChange { + name: string; + operation: string; + obj: any; +} + + +/** + * Collection class that handles documents of same type + * @implements LokiEventEmitter + * @see {@link Loki#addCollection} for normal creation of collections + */ +declare class Collection extends LokiEventEmitter { + name: string; objType: string; - // transforms will be used to store frequently used query chains as a series of steps - // which itself can be stored along with the database. - transforms: { [id: string]: any }; - // unique contraints contain duplicate object references, so they are not persisted. - // we will keep track of properties which have unique contraint applied here, and regenerate on load - uniqueNames: string[]; + data: E[]; + adaptiveBinaryIndices: boolean; + asyncListeners: boolean; + autoupdate: boolean; + dirty: boolean; + binaryIndices: { [P in keyof E]: BinaryIndex }; + cachedIndex: number[] | null; + cachedBinaryIndex: { [P in keyof E]: BinaryIndex } | null; + cachedData: E[] | null; + changes: CollectionChange[]; + cloneMethod: ("parse-stringify" | "jquery-extend-deep" | "shallow" | "shallow-assign" | "shallow-recurse-objects") | null; + cloneObjects: boolean; + constraints: { + unique: { [P in keyof E]: UniqueIndex }; + exact: { [P in keyof E]: ExactIndex } + }; + disableChangesApi: boolean; + disableDeltaChangesApi: boolean; + DynamicViews: DynamicView[]; + idIndex: number[]; + ttl: { age: any; ttlInterval: any; daemon: any; }; + maxId: number; + uniqueNames: (keyof E)[]; + transforms: { [name: string]: Transform[] }; + serializableIndices: boolean; + transactional: boolean; + observerCallback: (changes: { object: any }[]) => void; + getChanges: () => CollectionChange[]; + flushChanges: () => void; + getChangeDelta: (obj: any, old?: any) => any; + getObjectDelta: (oldObject: any, newObject?: any) => any; + setChangesApi: (enabled?: boolean) => void; - options: LokiCollectionOptions; - // option to activate a cleaner daemon - clears "aged" documents at set intervals. - ttl: { - age: number; - ttlInterval: number; - daemon: number; + /** + * @param name - collection name + * @param [options] - (optional) configuration object + * @param [options.unique=[]] - array of property names to define unique constraints for + * @param [options.exact=[]] - array of property names to define exact constraints for + * @param [options.indices=[]] - array property names to define binary indexes for + * @param [options.adaptiveBinaryIndices=true] - collection indices will be actively rebuilt rather than lazily + * @param [options.asyncListeners=false] - whether listeners are invoked asynchronously + * @param [options.disableChangesApi=true] - set to false to enable Changes API + * @param [options.disableDeltaChangesApi=true] - set to false to enable Delta Changes API (requires Changes API, forces cloning) + * @param [options.autoupdate=false] - use Object.observe to update objects automatically + * @param [options.clone=false] - specify whether inserts and queries clone to/from user + * @param [options.serializableIndices=true[]] - converts date values on binary indexed properties to epoch time + * @param [options.cloneMethod='parse-stringify'] - 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign' + * @param options.ttlInterval - time interval for clearing out 'aged' documents; not set by default. + * @see {@link Loki#addCollection} for normal creation of collections + */ + constructor(name: string, options?: Partial>); + + public console: { + log(...args: any[]): void; + warn(...args: any[]): void; + error(...args: any[]): void; }; - /** Collection class that handles documents of same type - * @constructor - * @param {string} collection name - * @param {array} array of property names to be indicized - * @param {object} configuration object + public addAutoUpdateObserver(obj: any): void; + + public removeAutoUpdateObserver(obj: any): void; + + /** + * Adds a named collection transform to the collection + * @param name - name to associate with transform + * @param transform - an array of transformation 'step' objects to save into the collection + * @example + * users.addTransform('progeny', [ + * { + * type: 'find', + * value: { + * 'age': {'$lte': 40} + * } + * } + * ]); + * + * var results = users.chain('progeny').data(); */ - new (name: string, options?: LokiCollectionOptions): LokiCollection; + public addTransform(name: string, transform: Transform[]): void; - getChanges(): LokiCollectionChange[]; + /** + * Retrieves a named transform from the collection. + * @param name - name of the transform to lookup. + */ + public getTransform(name: string): Transform[]; - setChangesApi(enabled: boolean): void; + /** + * Updates a named collection transform to the collection + * @param name - name to associate with transform + * @param transform - a transformation object to save into collection + */ + public setTransform(name: string, transform: Transform[]): void; - flushChanges(): void; + /** + * Removes a named collection transform from the collection + * @param name - name of collection transform to remove + */ + public removeTransform(name: string): void; - observerCallback: (changes: { object: any }[]) => void; + public byExample(template: object): { $and: any[] }; - addAutoUpdateObserver(object: any): void; + public findObject(template: object): E | null; - removeAutoUpdateObserver(object: any): void; - - addTransform(name: string, transform: any): void; - - setTransform(name: string, transform: any): void; - - removeTransform(name: string): void; - - byExample(template: any): { '$and': any[] }; - - findObject(template: any): E; - - findObjects(template: any): E[]; + public findObjects(template: object): E[]; /*----------------------------+ | TTL daemon | +----------------------------*/ - ttlDaemonFuncGen(): () => void; + public ttlDaemonFuncGen(): () => void; - setTTL(age: number, interval: number): void; + /** + * Updates or applies collection TTL settings. + * @param age - age (in ms) to expire document from collection + * @param interval - time (in ms) to clear collection of aged documents. + */ + public setTTL(age: number, interval: number): void; /*----------------------------+ | INDEXING | @@ -857,711 +1434,575 @@ interface LokiCollection extends LokiEventEmitter { /** * create a row filter that covers all documents in the collection */ - prepareFullDocIndex(): number[]; + public prepareFullDocIndex(): number[]; - /** Ensure binary index on a certain field + /** + * Will allow reconfiguring certain collection options. + * @param [options.adaptiveBinaryIndices] - collection indices will be actively rebuilt rather than lazily */ - ensureIndex(property: string, force?: boolean): void; + public configureOptions(options?: { adaptiveBinaryIndices?: boolean }): void; - ensureUniqueIndex(field: string): LokiUniqueIndex; - - /** Ensure all binary indices + /** + * Ensure binary index on a certain field + * @param property - name of property to create binary index on + * @param [force] - (Optional) flag indicating whether to construct index immediately */ - ensureAllIndexes(force?: boolean): void; + public ensureIndex(property: keyof E, force?: boolean): void; - flagBinaryIndexesDirty(): void; + public getSequencedIndexValues(property: string): string; - flagBinaryIndexDirty(index: string): void; + public ensureUniqueIndex(field: keyof E): UniqueIndex; - count(query?: LokiQuery): number; - - /** Rebuild idIndex + /** + * Ensure all binary indices */ - ensureId(): void; + public ensureAllIndexes(force?: boolean): void; - /** Rebuild idIndex async with callback - useful for background syncing with a remote server + public flagBinaryIndexesDirty(): void; + + public flagBinaryIndexDirty(index: string): void; + + /** + * Quickly determine number of documents in collection (or query) + * @param [query] - (optional) query object to count results of + * @returns number of documents in the collection */ - ensureIdAsync(callback: () => void): void; + public count(query?: LokiQuery): number; - /** Each collection maintains a list of DynamicViews associated with it + /** + * Rebuild idIndex + */ + public ensureId(): void; + + /** + * Rebuild idIndex async with callback - useful for background syncing with a remote server + */ + public ensureIdAsync(callback: () => void): void; + + /** + * Add a dynamic view to the collection + * @param name - name of dynamic view to add + * @param [options] - options to configure dynamic view with + * @param [options.persistent=false] - indicates if view is to main internal results array in 'resultdata' + * @param [options.sortPriority='passive'] - 'passive' (sorts performed on call to data) or 'active' (after updates) + * @param options.minRebuildInterval - minimum rebuild interval (need clarification to docs here) + * @returns reference to the dynamic view added + * @example + * var pview = users.addDynamicView('progeny'); + * pview.applyFind({'age': {'$lte': 40}}); + * pview.applySimpleSort('name'); + * + * var results = pview.data(); + */ + public addDynamicView(name: string, options?: Partial): DynamicView; + + /** + * Remove a dynamic view from the collection + * @param name - name of dynamic view to remove **/ - addDynamicView(name: string, options?: LokiDynamicViewOptions): LokiDynamicView; + public removeDynamicView(name: string): void; - removeDynamicView(name: string): void; + /** + * Look up dynamic view reference from within the collection + * @param name - name of dynamic view to retrieve reference of + * @returns A reference to the dynamic view with that name + **/ + public getDynamicView(name: string): DynamicView | null; - getDynamicView(name: string): LokiDynamicView; - - /** find and update: pass a filtering function to select elements to be updated - * and apply the updatefunctino to those elements iteratively + /** + * Applies a 'mongo-like' find query object and passes all results to an update function. + * For filter function querying you should migrate to [updateWhere()]{@link Collection#updateWhere}. + * + * @param filterObject - 'mongo-like' query object (or deprecated filterFunction mode) + * @param updateFunction - update function to run against filtered documents */ - findAndUpdate(filterFunction: (obj: E) => boolean, updateFunction: (obj: E) => E): void; + public findAndUpdate(filterObject: ((data: E) => boolean) | LokiQuery, updateFunction: (obj: E & LokiObj) => any): void; - /** generate document method - ensure object(s) have meta properties, clone it if necessary, etc. - * @param {object} doc: the document to be inserted (or an array of objects) - * @returns document or documents (if passed an array of objects) + /** + * Applies a 'mongo-like' find query object removes all documents which match that filter. + * + * @param filterObject - 'mongo-like' query object */ - insert(doc: E): E; - insert(doc: E[]): E[]; + public findAndRemove(filterObject?: LokiQuery): void; - /** generate document method - ensure object has meta properties, clone it if necessary, etc. - * @param {object} the document to be inserted + /** + * Adds object(s) to collection, ensure object(s) have meta properties, clone it if necessary, etc. + * @param doc - the document (or array of documents) to be inserted + * @returns document or documents inserted + * @example + * users.insert({ + * name: 'Odin', + * age: 50, + * address: 'Asgard' + * }); + * + * // alternatively, insert array of documents + * users.insert([{ name: 'Thor', age: 35}, { name: 'Loki', age: 30}]); + */ + public insert(doc: E): E | undefined; + public insert(doc: E[]): E[] | undefined; + public insert(doc: E | E[]): E | E[] | undefined; + public insert(doc: E | E[]): E | E[] | undefined; + + /** + * Adds a single object, ensures it has meta properties, clone it if necessary, etc. + * @param doc - the document to be inserted + * @param [bulkInsert] - quiet pre-insert and insert event emits * @returns document or 'undefined' if there was a problem inserting it */ - insertOne(doc: E): E; + public insertOne(doc: E, bulkInsert?: boolean): (E & LokiObj) | undefined; - clear(): void; - - /** Update method + /** + * Empties the collection. + * @param [options] - configure clear behavior + * @param [options.removeIndices] - (default: false) */ - update(doc: E): E; - update(doc: E[]): void; + public clear(options?: { removeIndices?: boolean }): void; - /** Add object to collection + /** + * Updates an object and notifies collection that the document has changed. + * @param doc - document to update within the collection */ - add(obj: E): E; + public update(doc: E): E; + public update(doc: E[]): void; + public update(doc: E | E[]): E | void; + public update(doc: E | E[]): E | void; - removeWhere(query: ((obj: E) => boolean) | LokiQuery): void; - - removeDataOnly(): void; - - /** delete wrapped + /** + * Add object to collection */ - remove(doc: E): E; - remove(doc: number): E; - remove(doc: number[]): void; - remove(doc: E[]): void; + public add(obj: E): E & LokiObj; + public add(obj: E & LokiObj): E & LokiObj; + + /** + * Applies a filter function and passes all results to an update function. + * + * @param filterFunction - filter function whose results will execute update + * @param updateFunction - update function to run against filtered documents + */ + public updateWhere(filterFunction: (data: E) => boolean, updateFunction: (obj: E & LokiObj) => any): void; + + /** + * Remove all documents matching supplied filter function. + * For 'mongo-like' querying you should migrate to [findAndRemove()]{@link Collection#findAndRemove}. + * @param query - query object to filter on + */ + public removeWhere(query: ((value: E, index: number, array: E[]) => boolean) | LokiQuery): void; + + public removeDataOnly(): void; + + /** + * Remove a document from the collection + * @param doc - document to remove from collection + */ + public remove(doc: number | E): E | null; + public remove(doc: number[] | E[]): void; + public remove(doc: number | E | number[] | E[]): E | null | void; + public remove(doc: number | E | number[] | E[]): E | null | void; /*---------------------+ | Finding methods | +----------------------*/ - /** Get by Id - faster than other methods because of the searching algorithm + /** + * Get by Id - faster than other methods because of the searching algorithm + * @param id - $loki id of document you want to retrieve + * @param returnPosition - if 'true' we will return [object, position] + * @returns Object reference if document was found, null if not, + * or an array if 'returnPosition' was passed. */ - get(id: number | string): E; - get(id: number | string, returnPosition?: boolean): E | [E, number]; + public get(id: number): E & LokiObj; + public get(id: number, returnPosition: true): [E & LokiObj, number]; + public get(id: number, returnPosition?: boolean): (E & LokiObj) | [E & LokiObj, number] | null; - by(field: string): (value: any) => E; - by(field: string, value: string): E; - - /** Find one object by index property, by property equal to value + /** + * Perform binary range lookup for the data[dataPosition][binaryIndexName] property value + * Since multiple documents may contain the same value (which the index is sorted on), + * we hone in on range and then linear scan range to find exact index array position. + * @param dataPosition : coll.data array index/position + * @param binaryIndexName : index to search for dataPosition in */ - findOne(query: LokiQuery): E; + public getBinaryIndexPosition(dataPosition: number, binaryIndexName: keyof E): number | null; - /** Chain method, used for beginning a series of chained find() and/or view() operations + /** + * Adaptively insert a selected item to the index. + * @param dataPosition : coll.data array index/position + * @param binaryIndexName : index to search for dataPosition in + */ + public adaptiveBinaryIndexInsert(dataPosition: number, binaryIndexName: keyof E): void; + + /** + * Adaptively update a selected item within an index. + * @param dataPosition : coll.data array index/position + * @param binaryIndexName : index to search for dataPosition in + */ + public adaptiveBinaryIndexUpdate(dataPosition: number, binaryIndexName: keyof E): void; + + /** + * Adaptively remove a selected item from the index. + * @param dataPosition : coll.data array index/position + * @param binaryIndexName : index to search for dataPosition in + */ + public adaptiveBinaryIndexRemove(dataPosition: number, binaryIndexName: keyof E, removedFromIndexOnly?: boolean): void; + + /** + * Internal method used for index maintenance and indexed searching. + * Calculates the beginning of an index range for a given value. + * For index maintainance (adaptive:true), we will return a valid index position to insert to. + * For querying (adaptive:false/undefined), we will : + * return lower bound/index of range of that value (if found) + * return next lower index position if not found (hole) + * If index is empty it is assumed to be handled at higher level, so + * this method assumes there is at least 1 document in index. + * + * @param prop - name of property which has binary index + * @param val - value to find within index + * @param [adaptive] - if true, we will return insert position + */ + public calculateRangeStart(prop: keyof E, val: any, adaptive?: boolean): number; + + /** + * Internal method used for indexed $between. Given a prop (index name), and a value + * (which may or may not yet exist) this will find the final position of that upper range value. + */ + public calculateRangeEnd(prop: keyof E, val: any): number; + + /** + * calculateRange() - Binary Search utility method to find range/segment of values matching criteria. + * this is used for collection.find() and first find filter of resultset/dynview + * slightly different than get() binary search in that get() hones in on 1 value, + * but we have to hone in on many (range) + * @param op - operation, such as $eq + * @param prop - name of property to calculate range for + * @param val - value to use for range calculation. + * @returns [start, end] index array positions + */ + public calculateRange(op: ("$eq" | "$aeq" | "$dteq" | "$gt" | "$gte" | "$lt" | "$lte" | "$between" | "$in"), prop: keyof E, val: any): number[]; + + /** + * Retrieve doc by Unique index + * @param field - name of uniquely indexed property to use when doing lookup + * @param value - unique value to search for + * @returns document matching the value passed + */ + public by(field: keyof E): (value: any) => E | undefined; + public by(field: keyof E, value: any): E | undefined; + public by(field: keyof E, value?: any): E | ((value: any) => E | undefined) | undefined; + public by(field: keyof E, value?: any): E | ((value: any) => E | undefined) | undefined; + + /** + * Find one object by index property, by property equal to value + * @param query - query object used to perform search with + * @returns First matching document, or null if none + */ + public findOne(query?: LokiQuery): (E & LokiObj) | null; + + /** + * Chain method, used for beginning a series of chained find() and/or view() operations * on a collection. * - * @param {array} transform : Ordered array of transform step objects similar to chain - * @param {object} parameters: Object containing properties representing parameters to substitute - * @returns {Resultset} : (or data array if any map or join functions where called) + * @param [transform] - Ordered array of transform step objects similar to chain + * @param [parameters] - Object containing properties representing parameters to substitute + * @returns (this) resultset, or data array if any map or join functions where called */ - chain(transform?: string | any[], parameters?: any): LokiResultset; + public chain(): Resultset; + public chain(transform?: string | string[] | Transform[], parameters?: object): Resultset; /** - * Find method, api is similar to mongodb except for now it only supports one search parameter. - * for more complex queries use view() and storeView() + * Find method, api is similar to mongodb. + * for more complex queries use [chain()]{@link Collection#chain} or [where()]{@link Collection#where}. + * @example {@tutorial Query Examples} + * @param query - 'mongo-like' query object + * @returns Array of matching documents */ - find(): E[]; - find(query: LokiQuery): LokiResultset; + public find(query?: LokiQuery): (E & LokiObj)[]; - /** Find object by unindexed field by property equal to value, + /** + * Find object by unindexed field by property equal to value, * simply iterates and returns the first element matching the query */ - findOneUnindexed(prop: string, value: any): E; - - /** Transaction methods */ - - /** start the transation */ - startTransaction(): void; - - /** commit the transation */ - commit(): void; - - /** roll back the transation */ - rollback(): void; - - // async executor. This is only to enable callbacks at the end of the execution. - async(fun: () => void, callback: () => void): void; - - /** Create view function - filter - */ - where(fun: (obj: E) => boolean): LokiResultset; - - /** Map Reduce - */ - mapReduce(mapFunction: (item: E, index: number, array: E[]) => U, reduceFunction: (array: U[]) => V): V; - - /** eqJoin - Join two collections on specified properties - */ - eqJoin(joinData: T[] | LokiResultset, leftJoinProp: string | ((obj: E) => string), rightJoinProp: string | ((obj: T) => string)): LokiResultset<{ left: E; right: T; }>; - eqJoin(joinData: T[] | LokiResultset, leftJoinProp: string | ((obj: E) => string), rightJoinProp: string | ((obj: T) => string), mapFun?: (a: E, b: T) => U): LokiResultset; - - /* ------ STAGING API -------- */ - /** stages: a map of uniquely identified 'stages', which hold copies of objects to be - * manipulated without affecting the data in the original collection - */ - stages: { [id: string]: any }; - - /** create a stage and/or retrieve it - */ - getStage(name: string): E[]; - - /** a collection of objects recording the changes applied through a commmitStage - */ - commitLog: { - timestamp: number; // timestamp (i.e. new Date().getTime()) - message: any; - data: E; - }[]; - - /** create a copy of an object and insert it into a stage - */ - stage(stageName: string, obj: E): E; - - /** re-attach all objects to the original collection, so indexes and views can be rebuilt - * then create a message to be inserted in the commitlog - */ - commitStage(stageName: string, message: any): void; - - no_op(): void; - - extract(field: string): any[]; - - max(field: string): number; - - min(field: string): number; - - maxRecord(field: string): { index: number; value: any; }; - - minRecord(field: string): { index: number; value: any; }; - - extractNumerical(field: string): number[]; - - avg(field: string): number; - - stdDev(field: string): number; - - mode(field: string): string | number; - - median(field: string): number; -} - - - - -/** comparison operators - * a is the value in the collection - * b is the query value - */ -interface LokiOps { - $eq(a: any, b: any): boolean; - $ne(a: any, b: any): boolean; - $dteq(a: any, b: any): boolean; - $gt(a: any, b: any): boolean; - $gte(a: any, b: any): boolean; - $lt(a: any, b: any): boolean; - $lte(a: any, b: any): boolean; - $in(a: any, b: { indexOf: (value: any) => boolean }): boolean; - $nin(a: any, b: { indexOf: (value: any) => boolean }): boolean; - $keyin(a: string, b: any): boolean; - $nkeyin(a: string, b: any): boolean; - $definedin(a: any, b: any): boolean; - $undefinedin(a: any, b: any): boolean; - $regex(a: any, b: RegExp | { test: (str: string) => boolean }): boolean; - $containsString(a: string | any, b: string): boolean; - $containsNone(a: any, b: any): boolean; - $containsAny(a: any, b: any | any[]): boolean; - $contains(a: any, b: any | any[]): boolean; - $type(a: any, b: any): boolean; - $size(a: any, b: any): boolean; - $len(a: any, b: any): boolean; - // field-level logical operators - // a is the value in the collection - // b is the nested query operation (for '$not') - // or an array of nested query operations (for '$and' and '$or') - $not(a: any, b: any): boolean; - $and(a: any, b: any[]): boolean; - $or(a: any, b: any[]): boolean; -} - - -interface LokiKeyValueStore { - keys: K[]; - values: V[]; - - sort(a: any, b: any): number; - setSort(fun: (a: K, b: K) => number): void; - bs(): LokiBSonSort; - set(key: K, value: V): void; - get(key: K): V; -} - - -interface LokiUniqueIndex { - field: string; - keyMap: { [id: string]: E }; - lokiMap: { [id: number]: any }; - - new (uniqueField: string): LokiUniqueIndex; - - set(obj: E): void; - get(key: string): E; - byId(id: number): E; - update(obj: E): void; - remove(key: string): void; - clear(): void; -} - - -interface LokiExactIndex { - index: { [id: string]: E[] }; - field: string; - - new (exactField: string): LokiExactIndex - - /** add the value you want returned to the key in the index */ - set(key: string, val: E): void; - /** remove the value from the index, if the value was the last one, remove the key */ - remove(key: string, val: E): void; - /** get the values related to the key, could be more than one */ - get(key: string): E[]; - /** clear will zap the index */ - clear(key?: any): void; -} - - -interface LokiSortedIndex { - field: string; - keys: K[]; - values: V[][]; - - new (sortedField: string): LokiSortedIndex; - - // set the default sort - sort(a: any, b: any): number; - bs(): LokiBSonSort; - // and allow override of the default sort - setSort(fun: (a: any, b: any) => number): void; - // add the value you want returned to the key in the index - set(key: K, value: V): void; - // get all values which have a key == the given key - get(key: K): V[]; - // get all values which have a key < the given key - getLt(key: K): V[]; - // get all values which have a key > the given key - getGt(key: K): V[]; - // get all vals from start to end - getAll(key: K, start: number, end: number): V[]; - // just in case someone wants to do something smart with ranges - getPos(key: K): { found: boolean; index: number; }; - // remove the value from the index, if the value was the last one, remove the key - remove(key: K, value: V): void; - // clear will zap the index - clear(): void; -} - - -interface LokiConfigureOptions { - adapter?: LokiPersistenceInterface; - autoload?: boolean; - autoloadCallback?: (dataOrErr: any | Error) => void; - autosave?: boolean; - autosaveCallback?: (err: any) => void; - autosaveInterval?: number; // milliseconds between auto-saves - env?: string; /*'NODEJS', 'BROWSER', 'CORDOVA'*/ - persistenceMethod?: string; /*'fs', 'localStorage', 'adapter'*/ - verbose?: boolean; -} - - -interface LokiCollectionOptions { - asyncListeners?: boolean; - autoupdate?: boolean; - clone?: boolean; - cloneMethod?: string; - disableChangesApi?: boolean; - exact?: string[]; - indices?: string | string[]; - transactional?: boolean; - unique?: string | string[]; -} - - -interface LokiDynamicViewOptions { - minRebuildInterval?: number; - persistent?: boolean; - sortPriority: string; /*'active', 'passive'*/ -} - - -interface LokiResultsetOptions { - firstOnly?: boolean; - queryObj?: LokiQuery; - queryFunc?: (item: E) => boolean; -} - - -interface LokiQuery { -} - - -interface LokiFilter { - type: string; /*'find', 'where'*/ - val: LokiQuery | ((obj: E, index: number, array: E[]) => boolean); - uid: number | string; -} - - -interface LokiElementMetaData { - created: number; // unix style timestamp (i.e. new Date().getTime()) - revision: number; -} - - -interface LokiCollectionChange { - name: string; - operation: string;/*'I', 'R', 'U'*/ - obj: any; -} - - -interface LokiBSonSort { - (fun: (a: T, b: T) => number): (array: T[], item: T) => { found: boolean; index: number; }; -} - - -/* -interface LokiUtils { - copyProperties(src: any, dest: any): void; - - // used to recursively scan hierarchical transform step object for param substitution - resolveTransformObject(subObj: U, params: any, depth?: number): U; - - // top level utility to resolve an entire (single) transform (array of steps) for parameter substitution - resolveTransformParams(transform: U[], params: any): U[]; -} - -// Sort helper that support null and undefined -declare function ltHelper(prop1: any, prop2: any, equal?: boolean): boolean; - -declare function gtHelper(prop1: any, prop2: any, equal?: boolean): boolean; - -declare function sortHelper(prop1: any, prop2: any, desc?: boolean): number; - -declare function doQueryOp(val: any, op: any): boolean; - -declare function containsCheckFn(a: T[], b): (curr: T) => boolean; -declare function containsCheckFn(a: string, b): (curr: string) => boolean; -declare function containsCheckFn(a: T, b): (curr: string) => boolean; -*/ - -/** General utils, including statistical functions - */ -/* -declare function isDeepProperty(field: string): boolean; - -declare function parseBase10(num: string | number): number; - -declare function isNotUndefined(obj: any): boolean; - -declare function add(a: string | number, b: string | number): number; - -declare function sub(a: string | number, b: string | number): number; - -declare function median(values: number[]): number; - -declare function average(array: (string | number)[]); - -declare function standardDeviation(values: (string | number)[]): number; - -declare function deepProperty(obj: any, property: string, isDeep?: boolean): any; - -declare function binarySearch(array: U[], item: U, fun: (a: U, b: U) => number): { found: boolean; index: number; }; - -// compoundeval() - helper function for compoundsort(), performing individual object comparisons -// -// @param {array} properties - array of property names, in order, by which to evaluate sort order -// @param {object} obj1 - first object to compare -// @param {object} obj2 - second object to compare -// @returns {integer} 0, -1, or 1 to designate if identical (sortwise) or which should be first -declare function compoundeval(properties: ([string, boolean] | [string])[], obj1: any, obj2: any): number; - -// dotSubScan - helper function used for dot notation queries. -declare function dotSubScan(root: any | any[], propPath: string[], fun: (root, value: V) => boolean, value: V): boolean; - -// making indexing opt-in... our range function knows how to deal with these ops : -//var indexedOpsList = ['$eq', '$dteq', '$gt', '$gte', '$lt', '$lte']; - -declare function clone(data: U, method?: string): U; // stage: 'parse-stringify', 'jquery-extend-deep', 'shallow' - -declare function cloneObjectArray(objarray: U[], method?: string): U; // stage: 'parse-stringify', 'jquery-extend-deep', 'shallow' - -declare function localStorageAvailable(): boolean; -*/ - - - - -/* ======== loki-indexed-adapter.js ======== */ -interface LokiIndexedAdapter { - app: string; - catalog: LokiCatalog; - - /** IndexedAdapter - Loki persistence adapter class for indexedDb. - * This class fulfills abstract adapter interface which can be applied to other storage methods - * Utilizes the included LokiCatalog app/key/value database for actual database persistence. - * @param {string} appname - Application name context can be used to distinguish subdomains or just 'loki' - */ - new (appname: string): LokiIndexedAdapter; - - /** checkAvailability - used to check if adapter is available - * @returns {boolean} true if indexeddb is available, false if not. - */ - checkAvailability(): boolean; - - /** loadDatabase() - Retrieves a serialized db string from the catalog. - * @param {string} dbname - the name of the database to retrieve. - * @param {function} callback - callback should accept string param containing serialized db string. - */ - loadDatabase(dbname: string, callback?: (data: any) => void): void; - - // alias for loadDatabase - loadKey(dbname: string, callback?: (data: any) => void): void; - - /** saveDatabase() - Saves a serialized db to the catalog. - * @param {string} dbname - the name to give the serialized database within the catalog. - * @param {string} dbstring - the serialized db string to save. - * @param {function} callback - (Optional) callback passed obj.success with true or false - */ - saveDatabase(dbname: string, dbstring: string, callback?: (err: Error | void) => void): void; - - // alias for saveDatabase - saveKey(dbname: string, dbstring: string, callback?: (err: Error | void) => void): void; - - /** deleteDatabase() - Deletes a serialized db from the catalog. - * @param {string} dbname - the name of the database to delete from the catalog. - */ - deleteDatabase(dbname: string): void; - - // alias for deleteDatabase - deleteKey(dbname: string): void; - - /** getDatabaseList() - Retrieves object array of catalog entries for current app. - * @param {function} callback - should accept array of database names in the catalog for current app. - */ - getDatabaseList(callback: (names: string[]) => void): void; - - // alias for getDatabaseList - getKeyList(callback: (names: string[]) => void): void; - - /** getCatalogSummary - allows retrieval of list of all keys in catalog along with size - * @param {function} callback - (Optional) callback to accept result array. - */ - getCatalogSummary(callback: (entries: { app: string; key: string; size: number; }) => void): void; -} - - -/** LokiCatalog - underlying App/Key/Value catalog persistence - * This non-interface class implements the actual persistence. - * Used by the IndexedAdapter class. - */ -interface LokiCatalog { - db: IDBDatabase; - - new (callback: (cat: LokiCatalog) => void): LokiCatalog; - - initializeLokiCatalog(callback: (cat: LokiCatalog) => void): void; - - getAppKey(app: string, key: string, callback: (resObj: any) => void): void; - - getAppKeyById(id: any, callback: (result: any, data: T) => void, data: T): void; - - setAppKey(app: string, key: string, val: any, callback: (res: { success: boolean }) => void): void; - - deleteAppKey(id: any, callback: (res: { success: boolean; }) => void): void; - - getAppKeys(app: string, callback: (data: any[]) => void): void; - - // Hide 'cursoring' and return array of { id: id, key: key } - getAllKeys(callback: (data: any[]) => void): void; -} -/* ======== END loki-indexed-adapter.js ======== */ - - - -/* ======== loki-crypted-file-adapter.js ======== */ -/** - * @file lokiCryptedFileAdapter.js - * @author Hans Klunder - */ - -/** require libs */ -//var fs = require('fs'); -//var cryptoLib = require('crypto'); -//var isError = require('util').isError; - -/* The default Loki File adapter uses plain text JSON files. This adapter crypts the database string and wraps the result -* in a JSON including enough info to be able to decrypt it (except for the 'secret' of course !) -* -* The idea is that the 'secret' does not reside in your source code but is supplied by some other source (e.g. the user in node-webkit) -* -* The idea + encrypt/decrypt routines are borrowed from https://github.com/mmoulton/krypt/blob/develop/lib/krypt.js -* not using the krypt module to avoid third party dependencies -*/ -interface LokiCryptedFileAdapter { - secret: string; - - /** The constructor is automatically called on `require` , see examples below - * @constructor - */ - new (): LokiCryptedFileAdapter; - - /** setSecret() - set the secret to be used during encryption and decryption - * - * @param {string} secret - the secret to be used - */ - setSecret(secret: string): void; - - /** loadDatabase() - Retrieves a serialized db string from the catalog. - * - * @example - // LOAD - var cryptedFileAdapter = require('./lokiCryptedFileAdapter'); - cryptedFileAdapter.setSecret('mySecret'); // you should change 'mySecret' to something supplied by the user - var db = new loki('test.crypted', { adapter: cryptedFileAdapter }); //you can use any name, not just '*.crypted' - db.loadDatabase(function(result) { - console.log('done'); - }); - * - * @param {string} dbname - the name of the database to retrieve. - * @param {function} callback - callback should accept string param containing serialized db string. - */ - loadDatabase(dbname: string, callback: (decryptedDataOrErr: string | any) => void): void; + public findOneUnindexed(prop: keyof E, value: any): (E & LokiObj) | null; /** - * - @example - // SAVE : will save database in 'test.crypted' - var cryptedFileAdapter = require('./lokiCryptedFileAdapter'); - cryptedFileAdapter.setSecret('mySecret'); // you should change 'mySecret' to something supplied by the user - var loki=require('lokijs'); - var db = new loki('test.crypted',{ adapter: cryptedFileAdapter }); //you can use any name, not just '*.crypted' - var coll = db.addCollection('testColl'); - coll.insert({test: 'val'}); - db.saveDatabase(); // could pass callback if needed for async complete - - @example - // if you have the krypt module installed you can use: - krypt --decrypt test.crypted --secret mySecret - to view the contents of the database - - * saveDatabase() - Saves a serialized db to the catalog. - * - * @param {string} dbname - the name to give the serialized database within the catalog. - * @param {string} dbstring - the serialized db string to save. - * @param {function} callback - (Optional) callback passed obj.success with true or false + * Transaction methods */ - saveDatabase(dbname: string, dbstring: string, callback: (err: any) => void): void; + + /** start the transation */ + public startTransaction(): void; + + /** commit the transation */ + public commit(): void; + + /** roll back the transation */ + public rollback(): void; + + // async executor. This is only to enable callbacks at the end of the execution. + public async(fun: () => void, callback: () => void): void; + + /** + * Query the collection by supplying a javascript filter function. + * @example + * var results = coll.where(function(obj) { + * return obj.legs === 8; + * }); + * + * @param fun - filter function to run against all collection docs + * @returns all documents which pass your filter function + */ + public where(fun: (data: E) => boolean): (E & LokiObj)[]; + + /** + * Map Reduce operation + * + * @param mapFunction - function to use as map function + * @param reduceFunction - function to use as reduce function + * @returns The result of your mapReduce operation + */ + public mapReduce(mapFunction: (value: E, index: number, array: E[]) => U, reduceFunction: (ary: U[]) => R): R; + + /** + * Join two collections on specified properties + * + * @param joinData - array of documents to 'join' to this collection + * @param leftJoinProp - property name in collection + * @param rightJoinProp - property name in joinData + * @param mapFun - (Optional) map function to use + * @param dataOptions - options to data() before input to your map function + * @param [dataOptions.removeMeta] - allows removing meta before calling mapFun + * @param [dataOptions.forceClones] - forcing the return of cloned objects to your map object + * @param [dataOptions.forceCloneMethod] - Allows overriding the default or collection specified cloning method. + * @returns Result of the mapping operation + */ + public eqJoin( + joinData: Collection | Resultset | any[], + leftJoinProp: string | ((obj: any) => string), + rightJoinProp: string | ((obj: any) => string), + mapFun?: (left: any, right: any) => any, + dataOptions?: Partial + ): Resultset; + + /* ------ STAGING API -------- */ + /** + * stages: a map of uniquely identified 'stages', which hold copies of objects to be + * manipulated without affecting the data in the original collection + */ + public stages: { [name: string]: any }; + + /** + * (Staging API) create a stage and/or retrieve it + */ + public getStage(name: string): any; + + /** + * a collection of objects recording the changes applied through a commmitStage + */ + public commitLog: { timestamp: number; message: string; data: any }[]; + + + /** + * (Staging API) create a copy of an object and insert it into a stage + */ + public stage(stageName: string, obj: F): F; + + /** + * (Staging API) re-attach all objects to the original collection, so indexes and views can be rebuilt + * then create a message to be inserted in the commitlog + * @param stageName - name of stage + * @param message + */ + public commitStage(stageName: string, message: string): void; + + public no_op: () => void; + + public extract(field: string): any[]; + + public max(field: string): number; + + public min(field: string): number; + + public maxRecord(field: string): { index: number; value: any }; + + public minRecord(field: string): { index: number; value: any }; + + public extractNumerical(field: string): number[]; + + /** + * Calculates the average numerical value of a property + * + * @param field - name of property in docs to average + * @returns average of property in all docs in the collection + */ + public avg(field: string): number; + + /** + * Calculate standard deviation of a field + * @param field + */ + public stdDev(field: string): number; + + /** + * @param field + */ + public mode(field: string): string | undefined; + + /** + * @param field - property name + */ + public median(field: string): number; } -interface LokiCryptedFileAdapterEncryptResult { - cipher: string; - keyDerivation: string; - keyLength: number; - iterations: number; - iv: string; - salt: string; - value: string; + +declare class KeyValueStore { + keys: any[]; + values: any[]; + + constructor(); + + public sort(a: any, b: any): -1 | 0 | 1; + + public setSort(fun: (target: any, test: any) => any): void; + + public bs(): (array: any[], item: any) => { found: boolean; index: number }; + + public set(key: any, value: any): void; + + public get(key: any): any[]; } -/* ======== END loki-crypted-file-adapter.js ======== */ +declare class UniqueIndex { + field: keyof E; + keyMap: { [fieldValue: string]: E/*{ $loki: number }*/ | undefined }; + lokiMap: { [$loki: number]: string | number | undefined }; -/* ======== loki-angular.js ======== */ -/* introduces a angular module named lokijs that returns the 'lokijs' module - var module = angular.module('lokijs', []) - .factory('Loki', function Loki() { - return lokijs; - }); - return module; -*/ -/* ======== END loki-angular.js ======== */ + constructor(uniqueField: keyof E); + + public set(obj: E/*{ $loki: number }*/): void; + + public get(key: string | number): E | undefined; + + public byId(id: number): E | undefined; + + /** + * Updates a document's unique index given an updated object. + * @param {Object} obj Original document object + * @param {Object} doc New document object (likely the same as obj) + */ + public update(obj: E/*{ $loki: number }*/, doc: any): void; + + public remove(key: string): void; + + public clear(): void; +} +declare class ExactIndex { + field: keyof E; + index: { [key: string]: E[] | undefined }; -/* ======== jquery-sync-adapter.js ======== */ + constructor(exactField: keyof E); -/** LokiJS JquerySyncAdapter - * A remote sync adapter example for LokiJS + // add the value you want returned to the key in the index + public set(key: string | number, val: E): void; + + // remove the value from the index, if the value was the last one, remove the key + public remove(key: string | number, val: E): void; + + // get the values related to the key, could be more than one + public get(key: string | number): E[] | undefined; + + // clear will zap the index + public clear(key?: null): void; +} + + + +declare class SortedIndex { + field: string; + keys: any[]; + values: any[]; + + constructor(sortedField: string); + + // set the default sort + public sort(a: any, b: any): -1 | 0 | 1; + + public bs(): (array: any[], item: any) => { found: boolean; index: number }; + + // and allow override of the default sort + public setSort(fun: (target: any, test: any) => number): void; + + // add the value you want returned to the key in the index + public set(key: any, value: any): void; + + // get all values which have a key == the given key + public get(key: any): any[]; + + // get all values which have a key < the given key + public getLt(key: any): any[]; + + // get all values which have a key > the given key + public getGt(key: any): any[]; + + // get all vals from start to end + public getAll(key: any, start: number, end: number): any[]; + + // just in case someone wants to do something smart with ranges + public getPos(key: any): { found: boolean; index: number }; + + // remove the value from the index, if the value was the last one, remove the key + public remove(key: any, value: any): void; + + // clear will zap the index + public clear(): void; +} + + +// type aliases to allow the nested classes inside LokiConstructor to extend classes sharing them same name(s) as themselves +declare class _Collection extends Collection { } +declare class _KeyValueStore extends KeyValueStore { } +declare class _LokiMemoryAdapter extends LokiMemoryAdapter { } +declare class _LokiPartitioningAdapter extends LokiPartitioningAdapter { } +declare class _LokiLocalStorageAdapter extends LokiLocalStorageAdapter { } +declare class _LokiFsAdapter extends LokiFsAdapter { } + + +/** + * LokiJS + * A lightweight document oriented javascript database * @author Joe Minichino */ - -/** this adapter assumes an object options is passed, - * containing the following properties: - * ajaxLib: jquery or compatible ajax library - * save: { url: the url to save to, dataType [optional]: json|xml|etc., type [optional]: POST|GET|PUT} - * load: { url: the url to load from, dataType [optional]: json|xml| etc., type [optional]: POST|GET|PUT } - */ -interface LokiJquerySyncAdapter { - options: LokiJquerySyncAdapterOptions - - new (options: LokiJquerySyncAdapterOptions): LokiJquerySyncAdapter; - - saveDatabase(name: string, data: any, callback?: (data: any, textStatus: string, xhr: XMLHttpRequest) => any): void; - - loadDatabase(name: string, callback?: (data: any, textStatus: string, xhr: XMLHttpRequest) => any): void; +declare class LokiConstructor extends Loki { + constructor(filename: string, options?: Partial & Partial & Partial); } - - -interface LokiJquerySyncAdapterOptions { - ajaxLib: { ajax(options: any): any; }; - save: { - url: any; - type?: string; /*'GET', 'POST, 'DELETE', etc.*/ - dataType?: string; /*'json', 'xml', etc.*/ +declare module LokiConstructor { + export var persistenceAdapters: { + fs: _LokiFsAdapter, + localStorage: _LokiLocalStorageAdapter }; - load: { - url: any; - type?: string; /*'GET', 'POST, 'DELETE', etc.*/ - dataType?: string; /*'json', 'xml', etc.*/ - }; -} + export function aeq(prop1: any, prop2: any): boolean; -interface LokiJquerySyncAdapterError extends Error { - name: string; // "JquerySyncAdapterError" - message: any; + function lt(prop1: any, prop2: any, equal?: boolean): boolean; - new (message: any): LokiJquerySyncAdapterError; -} -/* ======== END jquery-sync-adapter.js ======== */ + function gt(prop1: any, prop2: any, equal?: boolean): boolean; + export var LokiOps: LokiOps; -declare var LokiCryptedFileAdapterConstructor: { - new (): LokiCryptedFileAdapter; -} + export class Collection extends _Collection { } -declare module "lokiCryptedFileAdapter" { - export = LokiCryptedFileAdapterConstructor; -} + export class KeyValueStore extends _KeyValueStore { } + export class LokiMemoryAdapter extends _LokiMemoryAdapter { } -declare var LokiIndexedAdapterConstructor: { - new (filename: string): LokiIndexedAdapter; -} + export class LokiPartitioningAdapter extends _LokiPartitioningAdapter { } -declare module "loki-indexed-adapter" { - export = LokiIndexedAdapterConstructor; -} + export class LokiLocalStorageAdapter extends _LokiLocalStorageAdapter { } - -declare var LokiConstructor: { - new (filename: string, options?: LokiConfigureOptions): Loki; - LokiOps: LokiOps; - Collection: LokiCollection; - KeyValueStore: LokiKeyValueStore; + export class LokiFsAdapter extends _LokiFsAdapter { } } declare module "lokijs" { diff --git a/types/lokijs/lokijs-tests.ts b/types/lokijs/lokijs-tests.ts index 2e08370c02..167adba4ad 100644 --- a/types/lokijs/lokijs-tests.ts +++ b/types/lokijs/lokijs-tests.ts @@ -37,10 +37,10 @@ class QueenAnt extends Ant { class AntColony { - ants: LokiCollection; - queens: LokiCollection; + ants: Loki.Collection; + queens: Loki.Collection; - constructor(ants?: LokiCollection, queens?: LokiCollection) { + constructor(ants: Loki.Collection, queens: Loki.Collection) { this.ants = ants; this.queens = queens; } diff --git a/types/lokijs/tsconfig.json b/types/lokijs/tsconfig.json index bd01821699..96175c28a4 100644 --- a/types/lokijs/tsconfig.json +++ b/types/lokijs/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "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/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index ddaafced3d..520f267b5f 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.41.0 +// Type definitions for Mapbox GL JS v0.42.2 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer , Patrick Reames // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,1080 +7,1110 @@ /// declare namespace mapboxgl { - let accessToken: string; - let version: string; - export function supported(options?: {failIfMajorPerformanceCaveat?: boolean}): boolean; - export function setRTLTextPlugin(pluginURL: string, callback: Function): void; + let accessToken: string; + let version: string; - type LngLatLike = number[] | LngLat; - type LngLatBoundsLike = number[][] | LngLatLike[] | LngLatBounds; - type PointLike = number[] | Point; + export function supported(options?: { failIfMajorPerformanceCaveat?: boolean }): boolean; - /** - * Map - */ - export class Map extends Evented { - constructor(options?: MapboxOptions); + export function setRTLTextPlugin(pluginURL: string, callback: Function): void; - addControl(control: Control, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; + type LngLatLike = number[] | LngLat; + type LngLatBoundsLike = number[][] | LngLatLike[] | LngLatBounds; + type PointLike = number[] | Point; + type Expression = any[]; - removeControl(control: Control): this; + /** + * Map + */ + export class Map extends Evented { + constructor(options?: MapboxOptions); - addClass(klass: string, options?: mapboxgl.StyleOptions): this; + addControl(control: Control, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; - removeClass(klass: string, options?: mapboxgl.StyleOptions): this; + removeControl(control: Control): this; - setClasses(klasses: string[], options?: mapboxgl.StyleOptions): this; + addClass(klass: string, options?: mapboxgl.StyleOptions): this; - hasClass(klass: string): boolean; + removeClass(klass: string, options?: mapboxgl.StyleOptions): this; - getClasses(): string[]; + setClasses(klasses: string[], options?: mapboxgl.StyleOptions): this; - resize(): this; + hasClass(klass: string): boolean; - getBounds(): mapboxgl.LngLatBounds; + getClasses(): string[]; - setMaxBounds(lnglatbounds?: LngLatBoundsLike): this; + resize(): this; - setMinZoom(minZoom?: number): this; + getBounds(): mapboxgl.LngLatBounds; - getMinZoom(): number; + setMaxBounds(lnglatbounds?: LngLatBoundsLike): this; - setMaxZoom(maxZoom?: number): this; + setMinZoom(minZoom?: number): this; - getMaxZoom(): number; + getMinZoom(): number; - project(lnglat: LngLatLike): mapboxgl.Point; + setMaxZoom(maxZoom?: number): this; - unproject(point: PointLike): mapboxgl.LngLat; + getMaxZoom(): number; - queryRenderedFeatures(pointOrBox?: PointLike | PointLike[], parameters?: {layers?: string[], filter?: any[]}): GeoJSON.Feature[]; + project(lnglat: LngLatLike): mapboxgl.Point; - querySourceFeatures(sourceID: string, parameters?: {sourceLayer?: string, filter?: any[]}): GeoJSON.Feature[]; + unproject(point: PointLike): mapboxgl.LngLat; - setStyle(style: mapboxgl.Style | string): this; + queryRenderedFeatures(pointOrBox?: PointLike | PointLike[], parameters?: { layers?: string[], filter?: any[] }): GeoJSON.Feature[]; - getStyle(): mapboxgl.Style; + querySourceFeatures(sourceID: string, parameters?: { sourceLayer?: string, filter?: any[] }): GeoJSON.Feature[]; - isStyleLoaded(): boolean; + setStyle(style: mapboxgl.Style | string): this; - addSource(id: string, source: VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; + getStyle(): mapboxgl.Style; - isSourceLoaded(id: string): boolean; + isStyleLoaded(): boolean; - areTilesLoaded(): boolean; + addSource(id: string, source: VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; - removeSource(id: string): this; + isSourceLoaded(id: string): boolean; - getSource(id: string): VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource; + areTilesLoaded(): boolean; - addImage(name: string, image: HTMLImageElement | ArrayBufferView, options?: {width?: number, height?: number, pixelRatio?: number}): this; + removeSource(id: string): this; - removeImage(name: string): this; + getSource(id: string): VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource; - loadImage(url: string, callback: Function): this; + addImage(name: string, image: HTMLImageElement | ArrayBufferView, options?: { width?: number, height?: number, pixelRatio?: number }): this; - addLayer(layer: mapboxgl.Layer, before?: string): this; + removeImage(name: string): this; - moveLayer(id: string, beforeId?: string): this; + loadImage(url: string, callback: Function): this; - removeLayer(id: string): this; + addLayer(layer: mapboxgl.Layer, before?: string): this; - getLayer(id: string): mapboxgl.Layer; + moveLayer(id: string, beforeId?: string): this; - setFilter(layer: string, filter?: any[]): this; + removeLayer(id: string): this; - setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this; + getLayer(id: string): mapboxgl.Layer; - getFilter(layer: string): any[]; + setFilter(layer: string, filter?: any[]): this; - setPaintProperty(layer: string, name: string, value: any, klass?: string): this; + setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this; - getPaintProperty(layer: string, name: string, klass?: string): any; + getFilter(layer: string): any[]; - setLayoutProperty(layer: string, name: string, value: any): this; + setPaintProperty(layer: string, name: string, value: any, klass?: string): this; - getLayoutProperty(layer: string, name: string, klass?: string): any; + getPaintProperty(layer: string, name: string, klass?: string): any; - setLight(options: mapboxgl.Light, lightOptions: any): this; + setLayoutProperty(layer: string, name: string, value: any): this; - getLight(): mapboxgl.Light; + getLayoutProperty(layer: string, name: string, klass?: string): any; - getContainer(): HTMLElement; + setLight(options: mapboxgl.Light, lightOptions: any): this; - getCanvasContainer(): HTMLElement; + getLight(): mapboxgl.Light; - getCanvas(): HTMLCanvasElement; + getContainer(): HTMLElement; - loaded(): boolean; + getCanvasContainer(): HTMLElement; - remove(): void; + getCanvas(): HTMLCanvasElement; - onError(): void; + loaded(): boolean; - showTileBoundaries: boolean; + remove(): void; - showCollisionBoxes: boolean; + onError(): void; - repaint: boolean; + showTileBoundaries: boolean; - getCenter(): mapboxgl.LngLat; + showCollisionBoxes: boolean; - setCenter(center: LngLatLike, eventData?: mapboxgl.EventData): this; + repaint: boolean; - panBy(offset: number[], options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + getCenter(): mapboxgl.LngLat; - panTo(lnglat: LngLatLike, options?: mapboxgl.AnimationOptions, eventdata?: mapboxgl.EventData): this; + setCenter(center: LngLatLike, eventData?: mapboxgl.EventData): this; - getZoom(): number; + panBy(offset: number[], options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; - setZoom(zoom: number, eventData?: mapboxgl.EventData): this; + panTo(lnglat: LngLatLike, options?: mapboxgl.AnimationOptions, eventdata?: mapboxgl.EventData): this; - zoomTo(zoom: number, options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + getZoom(): number; - zoomIn(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + setZoom(zoom: number, eventData?: mapboxgl.EventData): this; - zoomOut(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + zoomTo(zoom: number, options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; - getBearing(): number; + zoomIn(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; - setBearing(bearing: number, eventData?: mapboxgl.EventData): this; + zoomOut(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; - rotateTo(bearing: number, options?: mapboxgl.AnimationOptions, eventData?: EventData): this; + getBearing(): number; - resetNorth(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + setBearing(bearing: number, eventData?: mapboxgl.EventData): this; - snapToNorth(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + rotateTo(bearing: number, options?: mapboxgl.AnimationOptions, eventData?: EventData): this; - getPitch(): number; + resetNorth(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; - setPitch(pitch: number, eventData?: EventData): this; + snapToNorth(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; - fitBounds(bounds: LngLatBoundsLike, options?: { linear?: boolean, easing?: Function, padding?: number | mapboxgl.PaddingOptions, offset?: PointLike, maxZoom?: number }, eventData?: mapboxgl.EventData): this; + getPitch(): number; - jumpTo(options: mapboxgl.CameraOptions, eventData?: mapboxgl.EventData): this; + setPitch(pitch: number, eventData?: EventData): this; - easeTo(options: mapboxgl.CameraOptions | mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + fitBounds(bounds: LngLatBoundsLike, options?: { linear?: boolean, easing?: Function, padding?: number | mapboxgl.PaddingOptions, offset?: PointLike, maxZoom?: number }, eventData?: mapboxgl.EventData): this; - flyTo(options: mapboxgl.FlyToOptions, eventData?: mapboxgl.EventData): this; + jumpTo(options: mapboxgl.CameraOptions, eventData?: mapboxgl.EventData): this; - isMoving(): boolean; + easeTo(options: mapboxgl.CameraOptions | mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; - stop(): this; + flyTo(options: mapboxgl.FlyToOptions, eventData?: mapboxgl.EventData): this; - scrollZoom: ScrollZoomHandler; + isMoving(): boolean; - boxZoom: BoxZoomHandler; + stop(): this; - dragRotate: DragRotateHandler; + scrollZoom: ScrollZoomHandler; - dragPan: DragPanHandler; + boxZoom: BoxZoomHandler; - keyboard: KeyboardHandler; + dragRotate: DragRotateHandler; - doubleClickZoom: DoubleClickZoomHandler; + dragPan: DragPanHandler; - touchZoomRotate: TouchZoomRotateHandler; - } + keyboard: KeyboardHandler; - export interface MapboxOptions { - /** If true, an attribution control will be added to the map. */ - attributionControl?: boolean; + doubleClickZoom: DoubleClickZoomHandler; - bearing?: number; + touchZoomRotate: TouchZoomRotateHandler; + } - /** Snap to north threshold in degrees. */ - bearingSnap?: number; + export interface MapboxOptions { + /** If true, an attribution control will be added to the map. */ + attributionControl?: boolean; - /** If true, enable the "box zoom" interaction (see BoxZoomHandler) */ - boxZoom?: boolean; + bearing?: number; - /** initial map center */ - center?: LngLatLike; + /** Snap to north threshold in degrees. */ + bearingSnap?: number; - /** Style class names with which to initialize the map */ - classes?: string[]; + /** If true, enable the "box zoom" interaction (see BoxZoomHandler) */ + boxZoom?: boolean; - /** ID of the container element */ - container?: string | Element; + /** initial map center */ + center?: LngLatLike; - /** If true, enable the "drag to pan" interaction (see DragPanHandler). */ - dragPan?: boolean; + /** Style class names with which to initialize the map */ + classes?: string[]; - /** If true, enable the "drag to rotate" interaction (see DragRotateHandler). */ - dragRotate?: boolean; + /** ID of the container element */ + container?: string | Element; - /** If true, enable the "double click to zoom" interaction (see DoubleClickZoomHandler). */ - doubleClickZoom?: boolean; + /** If true, enable the "drag to pan" interaction (see DragPanHandler). */ + dragPan?: boolean; - /** If true, the map will track and update the page URL according to map position */ - hash?: boolean; + /** If true, enable the "drag to rotate" interaction (see DragRotateHandler). */ + dragRotate?: boolean; - /** If true, map creation will fail if the implementation determines that the performance of the created WebGL context would be dramatically lower than expected. */ - failIfMayorPerformanceCaveat?: boolean; + /** If true, enable the "double click to zoom" interaction (see DoubleClickZoomHandler). */ + doubleClickZoom?: boolean; - /** If false, no mouse, touch, or keyboard listeners are attached to the map, so it will not respond to input */ - interactive?: boolean; + /** If true, the map will track and update the page URL according to map position */ + hash?: boolean; - /** If true, enable keyboard shortcuts (see KeyboardHandler). */ - keyboard?: boolean; + /** If true, map creation will fail if the implementation determines that the performance of the created WebGL context would be dramatically lower than expected. */ + failIfMayorPerformanceCaveat?: boolean; - logoPosition?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; + /** If false, no mouse, touch, or keyboard listeners are attached to the map, so it will not respond to input */ + interactive?: boolean; - /** If set, the map is constrained to the given bounds. */ - maxBounds?: LngLatBoundsLike; + /** If true, enable keyboard shortcuts (see KeyboardHandler). */ + keyboard?: boolean; - /** Maximum zoom of the map */ - maxZoom?: number; + logoPosition?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; - /** Minimum zoom of the map */ - minZoom?: number; + /** If set, the map is constrained to the given bounds. */ + maxBounds?: LngLatBoundsLike; - /** If true, The maps canvas can be exported to a PNG using map.getCanvas().toDataURL();. This is false by default as a performance optimization. */ - preserveDrawingBuffer?: boolean; + /** Maximum zoom of the map */ + maxZoom?: number; - pitch?: number; + /** Minimum zoom of the map */ + minZoom?: number; - refreshExpiredTiles?: boolean; + /** If true, The maps canvas can be exported to a PNG using map.getCanvas().toDataURL();. This is false by default as a performance optimization. */ + preserveDrawingBuffer?: boolean; - renderWorldCopies?: boolean; + pitch?: number; - /** If true, enable the "scroll to zoom" interaction */ - scrollZoom?: boolean; + refreshExpiredTiles?: boolean; - /** stylesheet location */ - style?: mapboxgl.Style | string; + renderWorldCopies?: boolean; - /** If true, the map will automatically resize when the browser window resizes */ - trackResize?: boolean; + /** If true, enable the "scroll to zoom" interaction */ + scrollZoom?: boolean; - /** If true, enable the "pinch to rotate and zoom" interaction (see TouchZoomRotateHandler). */ - touchZoomRotate?: boolean; + /** stylesheet location */ + style?: mapboxgl.Style | string; - /** Initial zoom level */ - zoom?: number; + /** If true, the map will automatically resize when the browser window resizes */ + trackResize?: boolean; - /** Maximum tile cache size for each layer. */ - maxTileCacheSize?: number; - } + /** If true, enable the "pinch to rotate and zoom" interaction (see TouchZoomRotateHandler). */ + touchZoomRotate?: boolean; - export interface PaddingOptions { - top: number; - bottom: number; - left: number; - right: number; - } + /** Initial zoom level */ + zoom?: number; - /** - * BoxZoomHandler - */ - export class BoxZoomHandler { - constructor(map: mapboxgl.Map); + /** Maximum tile cache size for each layer. */ + maxTileCacheSize?: number; + } - isEnabled(): boolean; + export interface PaddingOptions { + top: number; + bottom: number; + left: number; + right: number; + } - isActive(): boolean; + /** + * BoxZoomHandler + */ + export class BoxZoomHandler { + constructor(map: mapboxgl.Map); - enable(): void; + isEnabled(): boolean; - disable(): void; - } + isActive(): boolean; - /** - * ScrollZoomHandler - */ - export class ScrollZoomHandler { - constructor(map: mapboxgl.Map); + enable(): void; - isEnabled(): boolean; + disable(): void; + } - enable(): void; + /** + * ScrollZoomHandler + */ + export class ScrollZoomHandler { + constructor(map: mapboxgl.Map); - disable(): void; - } + isEnabled(): boolean; - /** - * DragPenHandler - */ - export class DragPanHandler { - constructor(map: mapboxgl.Map); + enable(): void; - isEnabled(): boolean; + disable(): void; + } - isActive(): boolean; + /** + * DragPenHandler + */ + export class DragPanHandler { + constructor(map: mapboxgl.Map); - enable(): void; + isEnabled(): boolean; - disable(): void; - } + isActive(): boolean; - /** - * DragRotateHandler - */ - export class DragRotateHandler { - constructor(map: mapboxgl.Map, options?: {bearingSnap?: number, pitchWithRotate?: boolean}); + enable(): void; - isEnabled(): boolean; + disable(): void; + } - isActive(): boolean; + /** + * DragRotateHandler + */ + export class DragRotateHandler { + constructor(map: mapboxgl.Map, options?: { bearingSnap?: number, pitchWithRotate?: boolean }); - enable(): void; + isEnabled(): boolean; - disable(): void; - } + isActive(): boolean; - /** - * KeyboardHandler - */ - export class KeyboardHandler { - constructor(map: mapboxgl.Map); + enable(): void; - isEnabled(): boolean; + disable(): void; + } - enable(): void; + /** + * KeyboardHandler + */ + export class KeyboardHandler { + constructor(map: mapboxgl.Map); - disable(): void; - } + isEnabled(): boolean; - /** - * DoubleClickZoomHandler - */ - export class DoubleClickZoomHandler { - constructor(map: mapboxgl.Map); + enable(): void; - isEnabled(): boolean; + disable(): void; + } - enable(): void; + /** + * DoubleClickZoomHandler + */ + export class DoubleClickZoomHandler { + constructor(map: mapboxgl.Map); - disable(): void; - } + isEnabled(): boolean; - /** - * TouchZoomRotateHandler - */ - export class TouchZoomRotateHandler { - constructor(map: mapboxgl.Map); + enable(): void; - isEnabled(): boolean; + disable(): void; + } - enable(): void; + /** + * TouchZoomRotateHandler + */ + export class TouchZoomRotateHandler { + constructor(map: mapboxgl.Map); - disable(): void; + isEnabled(): boolean; - disableRotation(): void; + enable(): void; - enableRotation(): void; - } + disable(): void; - export interface IControl { - onAdd(map: Map): HTMLElement; - onRemove(map: Map): any; - getDefaultPosition(): string; - } + disableRotation(): void; - /** - * Control - */ - export class Control extends Evented { - } + enableRotation(): void; + } - /** - * Navigation - */ - export class NavigationControl extends Control { - constructor(); - } + export interface IControl { + onAdd(map: Map): HTMLElement; - export class PositionOptions { - enableHighAccuracy?: boolean; - timeout?: number; - maximumAge?: number; - } + onRemove(map: Map): any; - export class FitBoundsOptions { - maxZoom?: number; - } + getDefaultPosition(): string; + } - /** - * Geolocate - */ - export class GeolocateControl extends Control { - constructor(options?: {positionOptions?: PositionOptions, fitBoundsOptions?: FitBoundsOptions, trackUserLocation?: boolean, showUserLocation?: boolean}); - } + /** + * Control + */ + export class Control extends Evented { + } - /** - * Attribution - */ - export class AttributionControl extends Control { - constructor(options?: {compact?: boolean}); - } + /** + * Navigation + */ + export class NavigationControl extends Control { + constructor(); + } - /** - * Scale - */ - export class ScaleControl extends Control { - constructor(options?: {maxWidth?: number, unit?: string}) - } + export class PositionOptions { + enableHighAccuracy?: boolean; + timeout?: number; + maximumAge?: number; + } - /** - * Fullscreen - */ - export class FullscreenControl extends Control { - constructor(); - } + export class FitBoundsOptions { + maxZoom?: number; + } - /** - * Popup - */ - export class Popup extends Evented { - constructor(options?: mapboxgl.PopupOptions); + /** + * Geolocate + */ + export class GeolocateControl extends Control { + constructor(options?: { positionOptions?: PositionOptions, fitBoundsOptions?: FitBoundsOptions, trackUserLocation?: boolean, showUserLocation?: boolean }); + } - addTo(map: mapboxgl.Map): this; + /** + * Attribution + */ + export class AttributionControl extends Control { + constructor(options?: { compact?: boolean }); + } - isOpen(): boolean; + /** + * Scale + */ + export class ScaleControl extends Control { + constructor(options?: { maxWidth?: number, unit?: string }) + } - remove(): this; + /** + * Fullscreen + */ + export class FullscreenControl extends Control { + constructor(); + } - getLngLat(): mapboxgl.LngLat; + /** + * Popup + */ + export class Popup extends Evented { + constructor(options?: mapboxgl.PopupOptions); - setLngLat(lnglat: LngLatLike): this; + addTo(map: mapboxgl.Map): this; - setText(text: string): this; + isOpen(): boolean; - setHTML(html: string): this; + remove(): this; - setDOMContent(htmlNode: Node): this; - } + getLngLat(): mapboxgl.LngLat; - export interface PopupOptions { - closeButton?: boolean; + setLngLat(lnglat: LngLatLike): this; - closeOnClick?: boolean; + setText(text: string): this; - anchor?: 'top' | 'bottom' | 'left' | 'right' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; + setHTML(html: string): this; - offset?: number | PointLike | { [key:string]: PointLike;}; - } + setDOMContent(htmlNode: Node): this; + } - export interface Style { - bearing?: number; - center?: number[]; - glyphs?: string; - layers?: Layer[]; - metadata?: any; - name?: string; - pitch?: number; - light?: Light; - sources?: any; - sprite?: string; - transition?: Transition; - version: number; - zoom?: number; - } + export interface PopupOptions { + closeButton?: boolean; - export interface Transition { - delay?: number; - duration?: number; - } + closeOnClick?: boolean; - export interface Light { - "anchor"?: "map" | "viewport"; - "position"?: number[]; - "color"?: string; - "intensity"?: number; - } + anchor?: 'top' | 'bottom' | 'left' | 'right' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; - export interface Source { - type: "vector" | "raster" | "geojson" | "image" | "video" | "canvas"; - } + offset?: number | PointLike | { [key: string]: PointLike; }; + } - /** - * GeoJSONSource - */ + export interface Style { + bearing?: number; + center?: number[]; + glyphs?: string; + layers?: Layer[]; + metadata?: any; + name?: string; + pitch?: number; + light?: Light; + sources?: any; + sprite?: string; + transition?: Transition; + version: number; + zoom?: number; + } - export interface GeoJSONSourceRaw extends Source, GeoJSONSourceOptions { - type: "geojson"; - } + export interface Transition { + delay?: number; + duration?: number; + } - export class GeoJSONSource implements GeoJSONSourceRaw { - type: "geojson"; + export interface Light { + 'anchor'?: 'map' | 'viewport'; + 'position'?: number[]; + 'color'?: string; + 'intensity'?: number; + } - constructor(options?: mapboxgl.GeoJSONSourceOptions); + export interface Source { + type: 'vector' | 'raster' | 'geojson' | 'image' | 'video' | 'canvas'; + } - setData(data: GeoJSON.Feature | GeoJSON.FeatureCollection | String): this; - } + /** + * GeoJSONSource + */ - export interface GeoJSONSourceOptions { - data?: GeoJSON.Feature | GeoJSON.FeatureCollection | string; + export interface GeoJSONSourceRaw extends Source, GeoJSONSourceOptions { + type: 'geojson'; + } - maxzoom?: number; + export class GeoJSONSource implements GeoJSONSourceRaw { + type: 'geojson'; - buffer?: number; + constructor(options?: mapboxgl.GeoJSONSourceOptions); - tolerance?: number; + setData(data: GeoJSON.Feature | GeoJSON.FeatureCollection | String): this; + } - cluster?: number | boolean; + export interface GeoJSONSourceOptions { + data?: GeoJSON.Feature | GeoJSON.FeatureCollection | string; - clusterRadius?: number; + maxzoom?: number; - clusterMaxZoom?: number; - } + buffer?: number; - /** - * VideoSource - */ - export interface VideoSource extends VideoSourceOptions { } - export class VideoSource implements Source { - type: "video"; + tolerance?: number; - constructor(options?: mapboxgl.VideoSourceOptions); + cluster?: number | boolean; - getVideo(): HTMLVideoElement; + clusterRadius?: number; - setCoordinates(coordinates: number[][]): this; - } + clusterMaxZoom?: number; + } - export interface VideoSourceOptions { - urls?: string[]; + /** + * VideoSource + */ + export interface VideoSource extends VideoSourceOptions { + } - coordinates?: number[][]; - } + export class VideoSource implements Source { + type: 'video'; - /** - * ImageSource - */ - export interface ImageSource extends ImageSourceOptions { } - export class ImageSource implements Source { - type: "image"; + constructor(options?: mapboxgl.VideoSourceOptions); - constructor(options?: mapboxgl.ImageSourceOptions); + getVideo(): HTMLVideoElement; - setCoordinates(coordinates: number[][]): this; - } + setCoordinates(coordinates: number[][]): this; + } - export interface ImageSourceOptions { - url?: string; + export interface VideoSourceOptions { + urls?: string[]; - coordinates?: number[][]; - } + coordinates?: number[][]; + } - /** - * CanvasSource - */ - export class CanvasSource implements Source, CanvasSourceOptions { - type: "canvas"; + /** + * ImageSource + */ + export interface ImageSource extends ImageSourceOptions { + } - coordinates: number[][]; + export class ImageSource implements Source { + type: 'image'; - canvas: string; + constructor(options?: mapboxgl.ImageSourceOptions); - getCanvas(): HTMLCanvasElement; + setCoordinates(coordinates: number[][]): this; + } - setCoordinates(coordinates: number[][]): this; - } + export interface ImageSourceOptions { + url?: string; - export interface CanvasSourceOptions { - coordinates: number[][]; + coordinates?: number[][]; + } - animate?: boolean; + /** + * CanvasSource + */ + export class CanvasSource implements Source, CanvasSourceOptions { + type: 'canvas'; - canvas: string; - } + coordinates: number[][]; - interface VectorSource extends Source { - type: "vector"; - url?: string; - tiles?: string[]; - minzoom?: number; - maxzoom?: number; - } + canvas: string; - interface RasterSource extends Source { - type: "raster"; - url: string; - tiles?: string[]; - minzoom?: number; - maxzoom?: number; - tileSize?: number; - } + getCanvas(): HTMLCanvasElement; - /** - * LngLat - */ - export class LngLat { - lng: number; - lat: number; + setCoordinates(coordinates: number[][]): this; + } - constructor(lng: number, lat: number); + export interface CanvasSourceOptions { + coordinates: number[][]; - /** Return a new LngLat object whose longitude is wrapped to the range (-180, 180). */ - wrap(): mapboxgl.LngLat; + animate?: boolean; - /** Return a LngLat as an array */ - toArray(): number[]; + canvas: string; + } - /** Return a LngLat as a string */ - toString(): string; + interface VectorSource extends Source { + type: 'vector'; + url?: string; + tiles?: string[]; + minzoom?: number; + maxzoom?: number; + } - toBounds(radius: number): LngLatBounds; + interface RasterSource extends Source { + type: 'raster'; + url: string; + tiles?: string[]; + minzoom?: number; + maxzoom?: number; + tileSize?: number; + } - static convert(input: LngLatLike): mapboxgl.LngLat; - } + /** + * LngLat + */ + export class LngLat { + lng: number; + lat: number; - /** - * LngLatBounds - */ - export class LngLatBounds { - sw: LngLatLike; - ne: LngLatLike; - constructor(sw?: LngLatLike, ne?: LngLatLike); + constructor(lng: number, lat: number); - setNorthEast(ne: LngLatLike): this; + /** Return a new LngLat object whose longitude is wrapped to the range (-180, 180). */ + wrap(): mapboxgl.LngLat; - setSouthWest(sw: LngLatLike): this; + /** Return a LngLat as an array */ + toArray(): number[]; - /** Extend the bounds to include a given LngLat or LngLatBounds. */ - extend(obj: mapboxgl.LngLat | mapboxgl.LngLatBounds): this; + /** Return a LngLat as a string */ + toString(): string; - /** Get the point equidistant from this box's corners */ - getCenter(): mapboxgl.LngLat; + toBounds(radius: number): LngLatBounds; - /** Get southwest corner */ - getSouthWest(): mapboxgl.LngLat; + static convert(input: LngLatLike): mapboxgl.LngLat; + } - /** Get northeast corner */ - getNorthEast(): mapboxgl.LngLat; + /** + * LngLatBounds + */ + export class LngLatBounds { + sw: LngLatLike; + ne: LngLatLike; - /** Get northwest corner */ - getNorthWest(): mapboxgl.LngLat; + constructor(sw?: LngLatLike, ne?: LngLatLike); - /** Get southeast corner */ - getSouthEast(): mapboxgl.LngLat; + setNorthEast(ne: LngLatLike): this; - /** Get west edge longitude */ - getWest(): number; + setSouthWest(sw: LngLatLike): this; - /** Get south edge latitude */ - getSouth(): number; + /** Extend the bounds to include a given LngLat or LngLatBounds. */ + extend(obj: mapboxgl.LngLat | mapboxgl.LngLatBounds): this; - /** Get east edge longitude */ - getEast(): number; + /** Get the point equidistant from this box's corners */ + getCenter(): mapboxgl.LngLat; - /** Get north edge latitude */ - getNorth(): number; + /** Get southwest corner */ + getSouthWest(): mapboxgl.LngLat; - /** Returns a LngLatBounds as an array */ - toArray(): number[][]; + /** Get northeast corner */ + getNorthEast(): mapboxgl.LngLat; - /** Return a LngLatBounds as a string */ - toString(): string; + /** Get northwest corner */ + getNorthWest(): mapboxgl.LngLat; - /** Convert an array to a LngLatBounds object, or return an existing LngLatBounds object unchanged. */ - static convert(input: LngLatBoundsLike): mapboxgl.LngLatBounds; - } + /** Get southeast corner */ + getSouthEast(): mapboxgl.LngLat; - /** - * Point - */ - // Todo: Pull out class to seperate definition for Module "point-geometry" - export class Point { - x: number; - y: number; + /** Get west edge longitude */ + getWest(): number; - constructor(x: number, y: number); + /** Get south edge latitude */ + getSouth(): number; - clone(): Point; + /** Get east edge longitude */ + getEast(): number; - add(p: number): Point; + /** Get north edge latitude */ + getNorth(): number; - sub(p: number): Point; + /** Returns a LngLatBounds as an array */ + toArray(): number[][]; - mult(k: number): Point; + /** Return a LngLatBounds as a string */ + toString(): string; - div(k: number): Point; + /** Convert an array to a LngLatBounds object, or return an existing LngLatBounds object unchanged. */ + static convert(input: LngLatBoundsLike): mapboxgl.LngLatBounds; + } - rotate(a: number): Point; + /** + * Point + */ + // Todo: Pull out class to seperate definition for Module "point-geometry" + export class Point { + x: number; + y: number; - matMult(m: number): Point; + constructor(x: number, y: number); - unit(): Point; + clone(): Point; - perp(): Point; + add(p: number): Point; - round(): Point; + sub(p: number): Point; - mag(): number; + mult(k: number): Point; - equals(p: Point): boolean; + div(k: number): Point; - dist(p: Point): number; + rotate(a: number): Point; - distSqr(p: Point): number; + matMult(m: number): Point; - angle(): number; + unit(): Point; - angleTo(p: Point): number; + perp(): Point; - angleWidth(p: Point): number; + round(): Point; - angleWithSep(x: number, y: number): number; + mag(): number; - static convert(a: PointLike): Point; - } + equals(p: Point): boolean; - export class Marker { - constructor(element?: HTMLElement, options?: { offset?: PointLike }); + dist(p: Point): number; - addTo(map: Map): this; + distSqr(p: Point): number; - remove(): this; + angle(): number; - getLngLat(): LngLat; + angleTo(p: Point): number; - setLngLat(lngLat: LngLatLike): this; + angleWidth(p: Point): number; - setPopup(popup?: Popup): this; + angleWithSep(x: number, y: number): number; - getPopup(): Popup; + static convert(a: PointLike): Point; + } - togglePopup(): this; - } + export class Marker { + constructor(element?: HTMLElement, options?: { offset?: PointLike }); - /** - * Evented - */ - export class Evented { - on(type: string, listener: Function): this; + addTo(map: Map): this; - on(type: string, layer: string, listener: Function): this; + remove(): this; - off(type?: string | any, listener?: Function): this; + getLngLat(): LngLat; - off(type?: string | any, layer?: string, listener?: Function): this; + setLngLat(lngLat: LngLatLike): this; - once(type: string, listener: Function): this; + setPopup(popup?: Popup): this; - fire(type: string, data?: mapboxgl.EventData | Object): this; + getPopup(): Popup; - listens(type: string): boolean; - } + togglePopup(): this; + } - /** - * StyleOptions - */ - export interface StyleOptions { - transition?: boolean; - } - - /** - * EventData - */ - export class EventData { - type: string; - target: Map; - originalEvent: Event; - point: mapboxgl.Point; - lngLat: mapboxgl.LngLat; - } - - export class MapMouseEvent { - type: string; - target: Map; - originalEvent: MouseEvent; - point: mapboxgl.Point; - lngLat: mapboxgl.LngLat; - } - - export class MapTouchEvent { - type: string; - target: Map; - originalEvent: TouchEvent; - point: mapboxgl.Point; - lngLat: mapboxgl.LngLat; - points: Point[]; - lngLats: LngLat[]; - } - - export class MapBoxZoomEvent { - originalEvent: MouseEvent; - boxZoomBounds: LngLatBounds; - } - - export class MapDataEvent { - type: string; - dataType: "source" | "style" | "tile"; - isSourceLoaded?: boolean; - source?: mapboxgl.Source; - coord?: any; - } - - /** - * AnimationOptions - */ - export interface AnimationOptions { - /** Number in milliseconds */ - duration?: number; - easing?: Function; - /** point, origin of movement relative to map center */ - offset?: PointLike; - /** When set to false, no animation happens */ - animate?: boolean; - } - - /** - * CameraOptions - */ - export interface CameraOptions { - /** Map center */ - center?: LngLatLike; - /** Map zoom level */ - zoom?: number; - /** Map rotation bearing in degrees counter-clockwise from north */ - bearing?: number; - /** Map angle in degrees at which the camera is looking at the ground */ - pitch?: number; - /** If zooming, the zoom center (defaults to map center) */ - around?: LngLatLike; - } - - /** - * FlyToOptions - */ - export interface FlyToOptions extends AnimationOptions, CameraOptions { - curve?: number; - minZoom?: number; - speed?: number; - screenSpeed?: number; - easing?: Function; - } - - /** - * MapEvent - */ - export interface MapEvent { - resize?: void; - webglcontextlost?: {originalEvent: WebGLContextEvent}; - webglcontextrestored?: {originalEvent: WebGLContextEvent}; - remove?: void; - dataloading?: {data: mapboxgl.MapDataEvent}; - data?: {data: mapboxgl.MapDataEvent}; - render?: void; - contextmenu?: {data: mapboxgl.MapMouseEvent}; - dblclick?: {data: mapboxgl.MapMouseEvent}; - click?: {data: mapboxgl.MapMouseEvent}; - tiledataloading?: {data: mapboxgl.MapDataEvent}; - sourcedataloading?: {data: mapboxgl.MapDataEvent}; - styledataloading?: {data: mapboxgl.MapDataEvent}; - touchcancel?: {data: mapboxgl.MapTouchEvent}; - touchmove?: {data: mapboxgl.MapTouchEvent}; - touchend?: {data: mapboxgl.MapTouchEvent}; - touchstart?: {data: mapboxgl.MapTouchEvent}; - mousemove?: {data: mapboxgl.MapMouseEvent}; - mouseup?: {data: mapboxgl.MapMouseEvent}; - mousedown?: {data: mapboxgl.MapMouseEvent}; - moveend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - move?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - movestart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - mouseout?:{data: mapboxgl.MapMouseEvent}; - load?: void; - sourcedata?: {data: mapboxgl.MapDataEvent}; - styledata?: {data: mapboxgl.MapDataEvent}; - zoomend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - zoom?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - zoomstart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - boxzoomcancel?: {data: mapboxgl.MapBoxZoomEvent}; - boxzoomstart?: {data: mapboxgl.MapBoxZoomEvent}; - boxzoomend?: {data: mapboxgl.MapBoxZoomEvent}; - rotate?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - rotatestart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - rotateend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - drag?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - dragend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - pitch?: {data: mapboxgl.EventData}; - } - - export interface Layer { - id: string; - type?: "fill" | "line" | "symbol" | "circle" | "fill-extrusion" | "raster" | "background" | "heatmap"; - - metadata?: any; - ref?: string; - - source?: string | VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw; - - "source-layer"?: string; - - minzoom?: number; - maxzoom?: number; - - interactive?: boolean; - - filter?: any[]; - layout?: BackgroundLayout | FillLayout | FillExtrusionLayout | LineLayout | SymbolLayout | RasterLayout | CircleLayout; - paint?: BackgroundPaint | FillPaint | FillExtrusionPaint | LinePaint | SymbolPaint | RasterPaint | CirclePaint; - } - - export interface StyleFunction { - stops?: any[][]; - property?: string; - base?: number; - type?: "identity" | "exponential" | "interval" | "categorical"; - default?: any; - "colorSpace"?: "rgb" | "lab" | "interval"; - } - - export interface BackgroundLayout { - visibility?: "visible" | "none"; - } - export interface BackgroundPaint { - "background-color"?: string; - "background-pattern"?: string; - "background-opacity"?: number; - } - - export interface FillLayout { - visibility?: "visible" | "none"; - } - export interface FillPaint { - "fill-antialias"?: boolean; - "fill-opacity"?: number | StyleFunction; - "fill-color"?: string | StyleFunction; - "fill-outline-color"?: string | StyleFunction; - "fill-translate"?: number[]; - "fill-translate-anchor"?: "map" | "viewport"; - "fill-pattern"?: "string"; - } - - export interface FillExtrusionLayout { - visibility?: "visible" | "none"; - } - export interface FillExtrusionPaint { - "fill-extrusion-opacity"?: number; - "fill-extrusion-color"?: string | StyleFunction; - "fill-extrusion-translate"?: number[]; - "fill-extrusion-translate-anchor"?: "map" | "viewport"; - "fill-extrusion-pattern"?: string; - "fill-extrusion-height"?: number | StyleFunction; - "fill-extrusion-base"?: number | StyleFunction; - } - - export interface LineLayout { - visibility?: "visible" | "none"; - - "line-cap"?: "butt" | "round" | "square"; - "line-join"?: "bevel" | "round" | "miter"; - "line-miter-limit"?: number; - "line-round-limit"?: number; - } - export interface LinePaint { - "line-opacity"?: number | StyleFunction; - "line-color"?: string | StyleFunction; - "line-translate"?: number[]; - "line-translate-anchor"?: "map" | "viewport"; - "line-width"?: number | StyleFunction; - "line-gap-width"?: number | StyleFunction; - "line-offset"?: number | StyleFunction; - "line-blur"?: number | StyleFunction; - "line-dasharray"?: number[]; - "line-dasharray-transition"?: Transition; - "line-pattern"?: string; - } - - export interface SymbolLayout { - visibility?: "visible" | "none"; - - "symbol-placement"?: "point" | "line"; - "symbol-spacing"?: number; - "symbol-avoid-edges"?: boolean; - "icon-allow-overlap"?: boolean; - "icon-ignore-placement"?: boolean; - "icon-optional"?: boolean; - "icon-rotation-alignment"?: "map" | "viewport" | "auto"; - "icon-pitch-alignment"?: "map" | "viewport"| "auto"; - "icon-size"?: number | StyleFunction; - "icon-text-fit"?: "none" | "both" | "width" | "height"; - "icon-text-fit-padding"?: number[]; - "icon-image"?: string | StyleFunction; - "icon-rotate"?: number | StyleFunction; - "icon-padding"?: number; - "icon-keep-upright"?: boolean; - "icon-offset"?: number[] | StyleFunction; - "text-pitch-alignment"?: "map" | "viewport" | "auto"; - "text-rotation-alignment"?: "map" | "viewport" | "auto"; - "text-field"?: string | StyleFunction; - "text-font"?: string | string[]; - "text-size"?: number | StyleFunction; - "text-max-width"?: number; - "text-line-height"?: number; - "text-letter-spacing"?: number; - "text-justify"?: "left" | "center" | "right"; - "text-anchor"?: "center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right"; - "text-max-angle"?: number; - "text-rotate"?: number | StyleFunction; - "text-padding"?: number; - "text-keep-upright"?: boolean; - "text-transform"?: "none" | "uppercase" | "lowercase" | StyleFunction; - "text-offset"?: number[]; - "text-allow-overlap"?: boolean; - "text-ignore-placement"?: boolean; - "text-optional"?: boolean; - - } - export interface SymbolPaint { - "icon-opacity"?: number | StyleFunction; - "icon-color"?: string | StyleFunction; - "icon-halo-color"?: string | StyleFunction; - "icon-halo-width"?: number | StyleFunction; - "icon-halo-blur"?: number | StyleFunction; - "icon-translate"?: number[]; - "icon-translate-anchor"?: "map" | "viewport"; - "text-opacity"?: number | StyleFunction; - "text-color"?: string | StyleFunction; - "text-halo-color"?: string | StyleFunction; - "text-halo-width"?: number | StyleFunction; - "text-halo-blur"?: number | StyleFunction; - "text-translate"?: number[]; - "text-translate-anchor"?: "map" | "viewport"; - } - - export interface RasterLayout { - visibility?: "visible" | "none"; - } - - export interface RasterPaint { - "raster-opacity"?: number; - "raster-hue-rotate"?: number; - "raster-brightness-min"?: number; - "raster-brightness-max"?: number; - "raster-saturation"?: number; - "raster-contrast"?: number; - "raster-fade-duration"?: number; - } - - export interface CircleLayout { - visibility?: "visible" | "none"; - } - - export interface CirclePaint { - "circle-radius"?: number | StyleFunction; - "circle-radius-transition"?: Transition; - "circle-color"?: string | StyleFunction; - "circle-blur"?: number | StyleFunction; - "circle-opacity"?: number | StyleFunction; - "circle-translate"?: number[]; - "circle-translate-anchor"?: "map" | "viewport"; - "circle-pitch-scale"?: "map" | "viewport"; - "circle-pitch-alignment"?: "map" | "viewport"; - "circle-stroke-width"?: number | StyleFunction; - "circle-stroke-color"?: string | StyleFunction; - "circle-stroke-opacity"?: number | StyleFunction; - } + /** + * Evented + */ + export class Evented { + on(type: string, listener: Function): this; + + on(type: string, layer: string, listener: Function): this; + + off(type?: string | any, listener?: Function): this; + + off(type?: string | any, layer?: string, listener?: Function): this; + + once(type: string, listener: Function): this; + + fire(type: string, data?: mapboxgl.EventData | Object): this; + + listens(type: string): boolean; + } + + /** + * StyleOptions + */ + export interface StyleOptions { + transition?: boolean; + } + + /** + * EventData + */ + export class EventData { + type: string; + target: Map; + originalEvent: Event; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + } + + export class MapMouseEvent { + type: string; + target: Map; + originalEvent: MouseEvent; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + } + + export class MapTouchEvent { + type: string; + target: Map; + originalEvent: TouchEvent; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + points: Point[]; + lngLats: LngLat[]; + } + + export class MapBoxZoomEvent { + originalEvent: MouseEvent; + boxZoomBounds: LngLatBounds; + } + + export class MapDataEvent { + type: string; + dataType: 'source' | 'style' | 'tile'; + isSourceLoaded?: boolean; + source?: mapboxgl.Source; + coord?: any; + } + + /** + * AnimationOptions + */ + export interface AnimationOptions { + /** Number in milliseconds */ + duration?: number; + easing?: Function; + /** point, origin of movement relative to map center */ + offset?: PointLike; + /** When set to false, no animation happens */ + animate?: boolean; + } + + /** + * CameraOptions + */ + export interface CameraOptions { + /** Map center */ + center?: LngLatLike; + /** Map zoom level */ + zoom?: number; + /** Map rotation bearing in degrees counter-clockwise from north */ + bearing?: number; + /** Map angle in degrees at which the camera is looking at the ground */ + pitch?: number; + /** If zooming, the zoom center (defaults to map center) */ + around?: LngLatLike; + } + + /** + * FlyToOptions + */ + export interface FlyToOptions extends AnimationOptions, CameraOptions { + curve?: number; + minZoom?: number; + speed?: number; + screenSpeed?: number; + easing?: Function; + } + + /** + * MapEvent + */ + export interface MapEvent { + resize?: void; + webglcontextlost?: { originalEvent: WebGLContextEvent }; + webglcontextrestored?: { originalEvent: WebGLContextEvent }; + remove?: void; + dataloading?: { data: mapboxgl.MapDataEvent }; + data?: { data: mapboxgl.MapDataEvent }; + render?: void; + contextmenu?: { data: mapboxgl.MapMouseEvent }; + dblclick?: { data: mapboxgl.MapMouseEvent }; + click?: { data: mapboxgl.MapMouseEvent }; + tiledataloading?: { data: mapboxgl.MapDataEvent }; + sourcedataloading?: { data: mapboxgl.MapDataEvent }; + styledataloading?: { data: mapboxgl.MapDataEvent }; + touchcancel?: { data: mapboxgl.MapTouchEvent }; + touchmove?: { data: mapboxgl.MapTouchEvent }; + touchend?: { data: mapboxgl.MapTouchEvent }; + touchstart?: { data: mapboxgl.MapTouchEvent }; + mousemove?: { data: mapboxgl.MapMouseEvent }; + mouseup?: { data: mapboxgl.MapMouseEvent }; + mousedown?: { data: mapboxgl.MapMouseEvent }; + moveend?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + move?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + movestart?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + mouseout?: { data: mapboxgl.MapMouseEvent }; + load?: void; + sourcedata?: { data: mapboxgl.MapDataEvent }; + styledata?: { data: mapboxgl.MapDataEvent }; + zoomend?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + zoom?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + zoomstart?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + boxzoomcancel?: { data: mapboxgl.MapBoxZoomEvent }; + boxzoomstart?: { data: mapboxgl.MapBoxZoomEvent }; + boxzoomend?: { data: mapboxgl.MapBoxZoomEvent }; + rotate?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + rotatestart?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + rotateend?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + drag?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + dragend?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + pitch?: { data: mapboxgl.EventData }; + } + + export interface Layer { + id: string; + type?: 'fill' | 'line' | 'symbol' | 'circle' | 'fill-extrusion' | 'raster' | 'background' | 'heatmap'; + + metadata?: any; + ref?: string; + + source?: string | VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw; + + 'source-layer'?: string; + + minzoom?: number; + maxzoom?: number; + + interactive?: boolean; + + filter?: any[]; + layout?: BackgroundLayout | FillLayout | FillExtrusionLayout | LineLayout | SymbolLayout | RasterLayout | CircleLayout | HeatmapLayout; + paint?: BackgroundPaint | FillPaint | FillExtrusionPaint | LinePaint | SymbolPaint | RasterPaint | CirclePaint | HeatmapPaint; + } + + export interface StyleFunction { + stops?: any[][]; + property?: string; + base?: number; + type?: 'identity' | 'exponential' | 'interval' | 'categorical'; + default?: any; + 'colorSpace'?: 'rgb' | 'lab' | 'interval'; + } + + export interface BackgroundLayout { + visibility?: 'visible' | 'none'; + } + + export interface BackgroundPaint { + 'background-color'?: string | Expression; + 'background-pattern'?: string; + 'background-opacity'?: number | Expression; + } + + export interface FillLayout { + visibility?: 'visible' | 'none'; + } + + export interface FillPaint { + 'fill-antialias'?: boolean; + 'fill-opacity'?: number | StyleFunction | Expression; + 'fill-color'?: string | StyleFunction | Expression; + 'fill-outline-color'?: string | StyleFunction | Expression; + 'fill-translate'?: number[] | Expression; + 'fill-translate-anchor'?: 'map' | 'viewport'; + 'fill-pattern'?: string; + } + + export interface FillExtrusionLayout { + visibility?: 'visible' | 'none'; + } + + export interface FillExtrusionPaint { + 'fill-extrusion-opacity'?: number | Expression; + 'fill-extrusion-color'?: string | StyleFunction | Expression; + 'fill-extrusion-translate'?: number[] | Expression; + 'fill-extrusion-translate-anchor'?: 'map' | 'viewport'; + 'fill-extrusion-pattern'?: string; + 'fill-extrusion-height'?: number | StyleFunction | Expression; + 'fill-extrusion-base'?: number | StyleFunction | Expression; + } + + export interface LineLayout { + visibility?: 'visible' | 'none'; + + 'line-cap'?: 'butt' | 'round' | 'square'; + 'line-join'?: 'bevel' | 'round' | 'miter'; + 'line-miter-limit'?: number | Expression; + 'line-round-limit'?: number | Expression; + } + + export interface LinePaint { + 'line-opacity'?: number | StyleFunction | Expression; + 'line-color'?: string | StyleFunction | Expression; + 'line-translate'?: number[] | Expression; + 'line-translate-anchor'?: 'map' | 'viewport'; + 'line-width'?: number | StyleFunction | Expression; + 'line-gap-width'?: number | StyleFunction | Expression; + 'line-offset'?: number | StyleFunction | Expression; + 'line-blur'?: number | StyleFunction | Expression; + 'line-dasharray'?: number[]; + 'line-dasharray-transition'?: Transition; + 'line-pattern'?: string; + } + + export interface SymbolLayout { + visibility?: 'visible' | 'none'; + + 'symbol-placement'?: 'point' | 'line'; + 'symbol-spacing'?: number | Expression; + 'symbol-avoid-edges'?: boolean; + 'icon-allow-overlap'?: boolean; + 'icon-ignore-placement'?: boolean; + 'icon-optional'?: boolean; + 'icon-rotation-alignment'?: 'map' | 'viewport' | 'auto'; + 'icon-pitch-alignment'?: 'map' | 'viewport' | 'auto'; + 'icon-size'?: number | StyleFunction | Expression; + 'icon-text-fit'?: 'none' | 'both' | 'width' | 'height'; + 'icon-text-fit-padding'?: number[] | Expression; + 'icon-image'?: string | StyleFunction; + 'icon-rotate'?: number | StyleFunction | Expression; + 'icon-padding'?: number | Expression; + 'icon-keep-upright'?: boolean; + 'icon-offset'?: number[] | StyleFunction | Expression; + 'text-pitch-alignment'?: 'map' | 'viewport' | 'auto'; + 'text-rotation-alignment'?: 'map' | 'viewport' | 'auto'; + 'text-field'?: string | StyleFunction; + 'text-font'?: string | string[]; + 'text-size'?: number | StyleFunction | Expression; + 'text-max-width'?: number | Expression; + 'text-line-height'?: number | Expression; + 'text-letter-spacing'?: number | Expression; + 'text-justify'?: 'left' | 'center' | 'right'; + 'text-anchor'?: 'center' | 'left' | 'right' | 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; + 'text-max-angle'?: number | Expression; + 'text-rotate'?: number | StyleFunction | Expression; + 'text-padding'?: number | Expression; + 'text-keep-upright'?: boolean; + 'text-transform'?: 'none' | 'uppercase' | 'lowercase' | StyleFunction | Expression; + 'text-offset'?: number[] | Expression; + 'text-allow-overlap'?: boolean; + 'text-ignore-placement'?: boolean; + 'text-optional'?: boolean; + + } + + export interface SymbolPaint { + 'icon-opacity'?: number | StyleFunction | Expression; + 'icon-color'?: string | StyleFunction | Expression; + 'icon-halo-color'?: string | StyleFunction | Expression; + 'icon-halo-width'?: number | StyleFunction | Expression; + 'icon-halo-blur'?: number | StyleFunction | Expression; + 'icon-translate'?: number[] | Expression; + 'icon-translate-anchor'?: 'map' | 'viewport'; + 'text-opacity'?: number | StyleFunction | Expression; + 'text-color'?: string | StyleFunction | Expression; + 'text-halo-color'?: string | StyleFunction | Expression; + 'text-halo-width'?: number | StyleFunction | Expression; + 'text-halo-blur'?: number | StyleFunction | Expression; + 'text-translate'?: number[] | Expression; + 'text-translate-anchor'?: 'map' | 'viewport'; + } + + export interface RasterLayout { + visibility?: 'visible' | 'none'; + } + + export interface RasterPaint { + 'raster-opacity'?: number | Expression; + 'raster-hue-rotate'?: number | Expression; + 'raster-brightness-min'?: number | Expression; + 'raster-brightness-max'?: number | Expression; + 'raster-saturation'?: number | Expression; + 'raster-contrast'?: number | Expression; + 'raster-fade-duration'?: number | Expression; + } + + export interface CircleLayout { + visibility?: 'visible' | 'none'; + } + + export interface CirclePaint { + 'circle-radius'?: number | StyleFunction | Expression; + 'circle-radius-transition'?: Transition; + 'circle-color'?: string | StyleFunction | Expression; + 'circle-blur'?: number | StyleFunction | Expression; + 'circle-opacity'?: number | StyleFunction | Expression; + 'circle-translate'?: number[] | Expression; + 'circle-translate-anchor'?: 'map' | 'viewport'; + 'circle-pitch-scale'?: 'map' | 'viewport'; + 'circle-pitch-alignment'?: 'map' | 'viewport'; + 'circle-stroke-width'?: number | StyleFunction | Expression; + 'circle-stroke-color'?: string | StyleFunction | Expression; + 'circle-stroke-opacity'?: number | StyleFunction | Expression; + } + + export interface HeatmapLayout { + visibility?: 'visible' | 'none'; + } + + export interface HeatmapPaint { + 'heatmap-radius'?: number | Expression; + 'heatmap-transition'?: Transition; + 'heatmap-weight'?: number | StyleFunction | Expression; + 'heatmap-intensity'?: number | Expression; + 'heatmap-color'?: string | Expression; + 'heatmap-color-transition'?: Transition; + 'heatmap-opacity'?: number | Expression; + 'heatmap-opacity-transition'?: Transition; + } } declare module 'mapbox-gl' { - export = mapboxgl; + export = mapboxgl; } declare module 'mapbox-gl/dist/mapbox-gl' { - export = mapboxgl; + export = mapboxgl; } diff --git a/types/mapnik/index.d.ts b/types/mapnik/index.d.ts new file mode 100644 index 0000000000..33b455f0dd --- /dev/null +++ b/types/mapnik/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for mapnik 3.x +// Project: http://mapnik.org +// Definitions by: Loli +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +export const settings: any; +export function register_default_fonts(): void; +export function register_default_input_plugins(): void; +export function register_datasource(path: string): void; +export class VectorTile { + constructor(z: number, x: number, y: number) + addDataSync(vectorTile: any): void; +} +export class Datasource { + constructor(datasource: any) + featureset(): Featureset; +} + +export class Featureset { + constructor() + next(): FeaturesetNext; +} +export class FeaturesetNext { + constructor() + toJSON(): string; +} + +export class Image { + constructor(x: number, y: number) + encode(type: string, callback?: (err: Error, buffer: Buffer) => void): void; + getData(): Buffer; +} + +export interface Image { + // constructor(x: number, y: number) + new(x: number, y: number): () => void; + encode(type: string, callback?: (err: Error, buffer: Buffer) => void): void; + getData(): Buffer; + save(fp: string): () => void; + open(fp: string): () => void; +} + +export class Map { + constructor(x: number, y: number) + load(xml: string, callback?: (err: Error, map: Map) => void): void; + zoomAll(): void; + render(images: Image | VectorTile , callback?: (err: Error, map: Image) => void): void; +} diff --git a/types/mapnik/mapnik-tests.ts b/types/mapnik/mapnik-tests.ts new file mode 100644 index 0000000000..23e726f111 --- /dev/null +++ b/types/mapnik/mapnik-tests.ts @@ -0,0 +1,40 @@ +import * as mapnik from "mapnik"; +import * as fs from "fs"; +import * as path from "path"; + +mapnik.register_default_fonts(); +mapnik.register_default_input_plugins(); + +const map: mapnik.Map = new mapnik.Map(256, 256); +map.load('./test/stylesheet.xml', function xx(err: Error, map: mapnik.Map) { + if (err) throw err; + map.zoomAll(); + const im: mapnik.Image = new mapnik.Image(256, 256); + map.render(im, function xxx(err: Error, im: mapnik.Image) { + if (err) throw err; + im.encode('png', function xxxx(err: Error, buffer: Buffer) { + if (err) throw err; + fs.writeFile('map.png', buffer, function xxxxx(err: Error) { + if (err) throw err; + console.log('saved map image to map.png'); + }); + }); + }); +}); + +// new mapnik.Image.open("xxx").save("xx"); + +mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins, 'shape.input')); +const ds: mapnik.Datasource = new mapnik.Datasource({type: 'shape', file: 'test/data/world_merc.shp'}); +const featureset: mapnik.Featureset = ds.featureset(); +const geojson: any = { + type: "FeatureCollection", + features: [ + ] +}; +let feat: mapnik.FeaturesetNext = featureset.next(); +while (feat) { + geojson.features.push(JSON.parse(feat.toJSON())); + feat = featureset.next(); +} +fs.writeFileSync("output.geojson", JSON.stringify(geojson, null, 2)); diff --git a/types/mapnik/tsconfig.json b/types/mapnik/tsconfig.json new file mode 100644 index 0000000000..81f111a37e --- /dev/null +++ b/types/mapnik/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", + "mapnik-tests.ts" + ] +} \ No newline at end of file diff --git a/types/mapnik/tslint.json b/types/mapnik/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/mapnik/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file 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/materialize-css/index.d.ts b/types/materialize-css/index.d.ts index a457c3ad1a..ebc997c51f 100644 --- a/types/materialize-css/index.d.ts +++ b/types/materialize-css/index.d.ts @@ -1,712 +1,418 @@ -// Type definitions for materialize-css 0.100 +// Type definitions for materialize-css 1.0 // Project: http://materializecss.com/ -// Definitions by: Erik Lieben -// Leon Yu -// Sukhdeep Singh -// Jean-Francois Cere -// Sebastien Cote +// Definitions by: 胡玮文 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /// -/// -declare namespace Materialize { - /** - * The collapsible options - */ - interface CollapsibleOptions { - /** - * A setting that changes the collapsible behavior to expandable instead of the default accordion style - */ - accordion?: boolean; +export = M; - /** - * Callback for Collapsible section close. - * @default `function() { alert('Closed'); }` - */ - onClose?: Function; +declare global { + namespace M { + class Autocomplete extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Autocomplete; - /** - * Callback for Collapsible section open. - * @default `function() { alert('Opened'); }` - */ - onOpen?: Function; - } + /** + * Select a specific autocomplete options. + * @param el Element of the autocomplete option. + */ + selectOption(el: Element): void; - interface TooltipOptions { - /** - * The delay before the tooltip shows (in milliseconds) - */ - delay: number; - /** - * Tooltip text. Can use custom HTML if you set the html option - */ - tooltip?: string; - /** - * Set the direction of the tooltip. 'top', 'right', 'bottom', 'left'. - * - * @default `'bottom'` - */ - position?: string; - /** - * Allow custom html inside the tooltip. - * - * @default `false` - */ - html?: boolean; - } + /** + * Update autocomplete options data. + * @param data Autocomplete options data object. + */ + updateData(data: AutocompleteData): void; - /** - * The dropdown options - */ - interface DropDownOptions { - /** - * The duration of the transition enter in milliseconds. - * @default `300` - */ - inDuration?: number; + /** + * If the autocomplete is open. + */ + isOpen: boolean; - /** - * The duration of the transition out in milliseconds. - * @default `225` - */ - outDuration?: number; + /** + * Number of matching autocomplete options. + */ + count: number; - /** - * If true, constrainWidth to the size of the dropdown activator. - * @default `true` - */ - constrainWidth?: boolean; - /** - * If true, the dropdown will open on hover. - * @default `false` - */ - hover?: boolean; + /** + * Index of the current selected option. + */ + activeIndex: number; + } - /** - * This defines the spacing from the aligned edge. - * @default `0` - */ - gutter?: number; + interface AutocompleteData { + [key: string]: string | null; + } - /** - * If true, the dropdown will show below the activator. - * @default `false` - */ - belowOrigin?: boolean; + interface AutocompleteOptions { + /** + * Data object defining autocomplete options with optional icon strings. + */ + data: AutocompleteData; - /** - * Defines the edge the menu is aligned to. - * @default `'left'` - */ - alignment?: string; - /** - * If true, stops the event propagating from the dropdown origin click handler. - * - * @default `false` - */ - stopPropagation?: boolean; - } + /** + * Limit of results the autocomplete shows. + * @default infinity + */ + limit: number; - /** - * The slider options - */ - interface SliderOptions { - /** - * Set to false to hide slide indicators. - * @default `true` - */ - indicators?: boolean; + /** + * Callback for when autocompleted. + */ + onAutocomplete: (this: Autocomplete, text: string) => void; - /** - * Set height of slider. - * @default `400` - */ - height?: number; + /** + * Minimum number of characters before autocomplete starts. + * @default 1 + */ + minLength: number; - /** - * Set the duration of the transition animation in ms. - * @default `500` - */ - transition?: number; + /** + * Sort function that defines the order of the list of autocomplete options. + */ + sortFunction: (a: string, b: string, inputText: string) => number; + } - /** - * Set the duration between transitions in ms. - * @default `6000` - */ - interval?: number; - } + class Sidenav extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Sidenav; - /** - * The carousel options - */ - interface CarouselOptions { - /** - * Transition duration in milliseconds - * @default `200` - */ - duration?: number; + /** + * Opens Sidenav + */ + open(): void; - /** - * Perspective zoom. If 0, all items are the same size. - * @default `-100` - */ - dist?: number; + /** + * Closes Sidenav + */ + close(): void; - /** - * Set the duration of the transition animation in ms. - * @default `500` - */ - shift?: number; + /** + * Describes open/close state of Sidenav + */ + isOpen: boolean; - /** - * Set the duration between transitions in ms. - * @default `6000` - */ - padding?: number; + /** + * Describes if sidenav is fixed + */ + isFixed: boolean; - /** - * Set the width of the carousel. - * @default `false` - */ - fullWidth?: boolean; - /** - * Set to true to show indicators. - * - * @default `false` - */ - indicators?: boolean; - /** - * Don't wrap around and cycle through items. - * - * @default `false` - */ - noWrap?: boolean; - } + /** + * Describes if Sidenav is being dragged + */ + isDragged: boolean; + } - /** - * The modal options - */ - interface ModalOptions { - /** - * Modal can be dismissed by clicking outside of the modal. - * @default `true` - */ - dismissible?: boolean; + /** + * Options for the Sidenav + */ + interface SidenavOptions { + /** + * Side of screen on which Sidenav appears + * @default 'left' + */ + edge: 'left' | 'right'; - /** - * Opacity of modal background. - * @default `.5` - */ - opacity?: number; + /** + * Allow swipe gestures to open/close Sidenav + * @default true + */ + draggable: boolean; - /** - * Transition in duration. - * @default `300` - */ - inDuration?: number; + /** + * Length in ms of enter transition + * @default 250 + */ + inDuration: number; - /** - * Transition out duration. - * @default `200` - */ - outDuration?: number; - /** - * Starting top style attribute - * @default `4%` - */ - startingTop?: string; - /** - * Ending top style attribute - * @default `10%` - */ - endingTop?: string; + /** + * Length in ms of exit transition + * @default 200 + */ + outDuration: number; - /** - * Callback for Modal open. - * @default `function() { alert('Ready'); }` - */ - ready?: Function; + /** + * Function called when sidenav starts entering + */ + onOpenStart: (this: Sidenav, elem: Element) => void; - /** - * Callback for Modal close. - * @default `function() { alert('Closed'); }` - */ - complete?: Function; - } + /** + * Function called when sidenav finishes entering + */ + onOpenEnd: (this: Sidenav, elem: Element) => void; - /** - * The push pin options - */ - interface PushpinOptions { - /** - * The distance in pixels from the top of the page where the element becomes fixed. - * @default `0` - */ - top?: number; + /** + * Function called when sidenav starts exiting + */ + onCloseStart: (this: Sidenav, elem: Element) => void; - /** - * The distance in pixels from the top of the page where the elements stops being fixed. - * @default `Infinity` - */ - bottom?: number; + /** + * Function called when sidenav finishes exiting + */ + onCloseEnd: (this: Sidenav, elem: Element) => void; + } - /** - * The offset from the top the element will be fixed at. - * @default `0` - */ - offset?: number; - } + class Tabs extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Tabs; - /** - * The scroll spy options - */ - interface ScrollSpyOptions { - /** - * Offset from top. - * @default `200` - */ - scrollOffset?: number; - /** - * Class name to be added to the active link. - * @default `active` - */ - activeClass?: string; - /** - * Function that returns a selector to add activeClass to. The parameter is the section id - */ - getActiveElement?: Function; - } + /** + * Show tab content that corresponds to the tab with the id + * @param tabId The id of the tab that you want to switch to + */ + select(tabId: string): void; - /** - * The slideNav options - */ - interface SideNavOptions { - /** - * The sideNav width. - * @default `240` - */ - menuWidth?: number; + /** + * The index of tab that is currently shown + */ + index: number; + } - /** - * The horizontal origin. - * @default `'left'` - */ - edge?: string; + /** + * Options for the Tabs + */ + interface TabsOptions { + /** + * Transition duration in milliseconds. + * @default 300 + */ + duration: number; - /** - * Closes sideNav on clicks, useful for Angular/Meteor. - * @default `false` - */ - closeOnClick?: boolean; + /** + * Callback for when a new tab content is shown + */ + onShow: (this: Tabs, newContent: Element) => void; - /** - * Choose whether you can drag to open on touch screens. - * @default `true` - */ - draggable?: boolean; + /** + * Set to true to enable swipeable tabs. This also uses the responsiveThreshold option + * @default false + */ + swipeable: boolean; - /** - * Execute a callback function when sideNav is opened. - * - * The callback provides a parameter which refers to the sideNav being opened. - */ - onOpen?: Function; + /** + * The maximum width of the screen, in pixels, where the swipeable functionality initializes. + * @default infinity + */ + responsiveThreshold: number; + } - /** - * Execute a callback function when sideNav is closed. - * - * The callback provides a parameter which refers to the sideNav being closed. - */ - onClose?: Function; - } + class Modal extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Modal; - interface ScrollFireOptions { - /** - * The selector for the element that is being tracked. - */ - selector?: string; + /** + * Open modal + */ + open(): void; - /** - * Offset to use when activating the scroll fire event - * If this is 0, the callback will be fired when the selector element is at the very bottom of the user's window. - */ - offset?: number; + /** + * Close modal + */ + close(): void; - /** - * The string function call that you want to make when the user scrolls to the threshold. - * It will only be called once. - * Example: 'console.log("hello, world!")'; - * or callback: () => { console.log('hello world'); } - */ - callback?: string | (() => void); - } + /** + * If the modal is open. + */ + isOpen: boolean; - interface TabOptions { - /** - * Execute a callback function when the tab is changed. - * - * The callback provides a parameter which refers to the current tab being shown. - */ - onShow?: Function; + /** + * ID of the modal element + */ + id: string; + } - /** - * Set to true to enable swipeable tabs. This also uses the responsiveThreshold option. - * - * @default `false` - */ - swipeable?: boolean; + /** + * Options for the Modal + */ + interface ModalOptions { + /** + * Opacity of the modal overlay. + * @default 0.5 + */ + opacity: number; - /** - * The maximum width of the screen, in pixels, where the swipeable functionality initializes. - * - * @default `Infinity` - */ - responsiveThreshold?: number; - } + /** + * Transition in duration in milliseconds. + * @default 250 + */ + inDuration: number; - interface ChipDataObject { - tag: string; - image?: string; - id?: number; - } + /** + * Transition out duration in milliseconds. + * @default 250 + */ + outDuration: number; - interface ChipOptions { - /** - * Set the chip data - */ - data?: ChipDataObject[]; - /** - * Set first placeholder when there are no tags - */ - placeholder?: string; - /** - * Set second placeholder when adding additional tags. - */ - secondaryPlaceholder?: string; - /** - * Set autocomplete data. - */ - autocompleteData?: any; - /** - * Set autocomplete limit. - */ - autocompleteLimit?: number; - /** - * Set autocompleteOptions - */ - autocompleteOptions?: AutoCompleteOptions; - } + /** + * Callback function called when modal is finished entering. + */ + ready: (this: Modal, elem: Element, openingTrigger: Element) => void; - interface AutoCompleteOptions { - /** - * The JSON object data to be used for the autocomplete suggetions list - */ - data: object; - /** - * The max amount of results that can be shown at once. - * @default `Infinity` - */ - limit?: number; - /** - * Callback function when value is autcompleted. - */ - onAutocomplete?: (val: any) => void; - /** - * The minimum length of the input for the autocomplete to start. - * @default `1` - */ - minLength?: number; - } + /** + * Callback function called when modal is finished exiting. + */ + complete: (this: Modal, elem: Element) => void; - interface Toast { - /** - * Dismiss all toasts - */ - removeAll: Function; - } + /** + * Allow modal to be dismissed by keyboard or overlay click. + * @default true + */ + dismissible: boolean; - /** - * The Materialize object - */ - interface Materialize { - /** - * Displays a toast message on screen - * - * @param string | JQuery message The message to display on screen - * @param number displayLength The duration in milliseconds to display the message on screen - * @param string className The className to use to format the message to display - * @param Function completeCallback Callback function to call when the messages completes/hides. - */ - toast(message: string | JQuery, displayLength: number, className?: string, completeCallback?: Function): void; + /** + * Starting top offset + * @default '4%' + */ + startingTop: string; - /** - * Fires an event when the page is scrolled to a certain area - * - * @param ScrollFireOptions options optional parameter with scroll fire options - */ - scrollFire(options?: ScrollFireOptions[]): void; + /** + * Ending top offset + * @default '10%' + */ + endingTop: string; + } - /** - * A staggered reveal effect for any UL Tag with list items - * - * @param string selector the selector for the list to show in staggered fasion - */ - showStaggeredList(selector: string): void; + class Tooltip extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Tooltip; - /** - * Fade in images. It also animates grayscale and brightness to give it a unique effect. - * - * @param string selector the selector for the image to fade in - */ - fadeInImage(selector: string): void; + /** + * Show tooltip. + */ + open(): void; - /** - * Update all text field to reinitialize all the Materialize labels on the page if dynamically adding inputs - */ - updateTextFields(): void; + /** + * Hide tooltip. + */ + close(): void; - /** - * Toast functions - */ - Toast: Toast; - } -} - -/** - * Declare Pickadate namespace again in order to add more Materialize specific properties to TimeOptions interface - * - * @see http://www.typescriptlang.org/docs/handbook/declaration-merging.html - */ -declare namespace Pickadate { - interface TimeOptions { - /** - * Set default time such as : 'now', '1:30AM', '16:30'. - * @default `'now'` - */ - default?: string; - /** - * set default time to * milliseconds from now (using with default = 'now') - * @default `0` - */ - fromnow?: number; - /** - * Use AM/PM or 24-hour format - * @default `false` - */ - twelvehour?: boolean; - /** - * text for done-button - * @default `'OK'` - */ - donetext?: string; - /** - * text for clear-button - * @default `'Clear'` - */ - cleartext?: string; - /** - * Text for cancel-button - * @default `'Cancel'` - */ - canceltext?: string; - /** - * automatic close timepicker - * @default `false` - */ - autoclose?: boolean; - /** - * make AM PM clickable - * @default `true` - */ - ampmclickable?: boolean; - /** - * Function for after opening timepicker - */ - aftershow?: Function; - } -} - -declare var Materialize: Materialize.Materialize; - -interface JQuery { - /** - * open Fixed Action Button - */ - openFAB(): void; - /** - * close Fixed Action Button - */ - closeFAB(): void; - - /** - * Select allows user input through specified options. - * - * @param string method "destroy" destroy the material select - */ - material_select(method?: string): void; - - /** - * Use a character counter in fields where a character restriction is in place. - */ - characterCounter(): JQuery; - - /** - * Collapsibles are accordion elements that expand when clicked on. - * They allow you to hide content that is not immediately relevant to the user. - * - * @param CollapsibleOptions | string options the collapsible options or the string "destroy" to destroy the collapsible - */ - collapsible(options?: Materialize.CollapsibleOptions | string): JQuery; - - /** - * Programmatically trigger an event on a selected index - * - * @param string method the string "open" or "close" to open or to close the collapsible element on specified index - * @param number index the element index to trigger "open" or "close" function - */ - collapsible(method: string, index: number): JQuery; - - /** - * Tooltips are small, interactive, textual hints for mainly graphical elements. - * When using icons for actions you can use a tooltip to give people clarification on its function. - * - * @param TooltipOptions | string options the tooltip options or the string "remove" to remove the tooltip function - */ - tooltip(options?: Materialize.TooltipOptions | string): JQuery; - - /** - * Add a dropdown list to any button. - * Make sure that the data-activates attribute matches the id in the