Merge remote-tracking branch 'DefinitelyTyped/master'

This commit is contained in:
Mick Charuwichitratana
2017-12-14 10:58:10 +07:00
711 changed files with 30778 additions and 12229 deletions
+30
View File
@@ -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",
@@ -360,6 +372,12 @@
"sourceRepoURL": "https://github.com/elitechance/lambda-phi",
"asOfVersion": "1.0.1"
},
{
"libraryName": "left-pad",
"typingsPackageName": "left-pad",
"sourceRepoURL": "https://github.com/stevemao/left-pad",
"asOfVersion": "1.2.0"
},
{
"libraryName": "Linq.JS",
"typingsPackageName": "linq",
@@ -558,6 +576,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",
@@ -690,6 +714,12 @@
"sourceRepoURL": "https://github.com/JMPerez/spotify-web-api-js",
"asOfVersion": "0.21.0"
},
{
"libraryName": "striptags",
"typingsPackageName": "striptags",
"sourceRepoURL": "https://github.com/ericnorris/striptags",
"asOfVersion": "3.1.1"
},
{
"libraryName": "Sugar",
"typingsPackageName": "sugar",
+6 -5
View File
@@ -1,13 +1,14 @@
// Type definitions for accepts 1.3
// Project: https://github.com/jshttp/accepts
// Definitions by: Stefan Reichel <https://github.com/bomret>
// Brice BERNARD <https://github.com/brikou>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace accepts {
interface Headers {
[key: string]: string | string[];
}
/// <reference types="node" />
import { IncomingMessage } from "http";
declare namespace accepts {
interface Accepts {
/**
* Return the first accepted charset. If nothing in `charsets` is accepted, then `false` is returned.
@@ -55,6 +56,6 @@ declare namespace accepts {
}
}
declare function accepts(req: { headers: accepts.Headers }): accepts.Accepts;
declare function accepts(req: IncomingMessage): accepts.Accepts;
export = accepts;
+3
View File
@@ -0,0 +1,3 @@
import addZero from "add-zero";
addZero(5, 2);
+6
View File
@@ -0,0 +1,6 @@
// Type definitions for add-zero 1.0
// Project: https://github.com/rafaelrinaldi/add-zero#readme
// Definitions by: Giles Roadnight <https://github.com/Roaders>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export default function addZero(value: string | number, digits?: number): string;
+23
View File
@@ -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",
"add-zero-tests.ts"
]
}
+2 -2
View File
@@ -113,8 +113,8 @@ declare class Agenda extends EventEmitter {
* @param options The options for the job.
* @param handler The handler to execute.
*/
define(name: string, handler: (job?: Agenda.Job, done?: (err?: Error) => void) => void): void;
define(name: string, options: Agenda.JobOptions, handler: (job?: Agenda.Job, done?: (err?: Error) => void) => void): void;
define(name: string, handler: (job: Agenda.Job, done: (err?: Error) => void) => void): void;
define(name: string, options: Agenda.JobOptions, handler: (job: Agenda.Job, done: (err?: Error) => void) => void): void;
/**
* Runs job name at the given interval. Optionally, data and options can be passed in.
+779 -18
View File
@@ -4,15 +4,85 @@
// Huw <https://github.com/hoo29>
// pascalwhoop <https://github.com/pascalwhoop>
// Ben <https://github.com/blforce>
// rk-7 <https://github.com/rk-7>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
export function handler<T>(event: RequestBody<T>, context: Context, callback?: (err: any, response: any) => void): AlexaObject<T>;
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<T> extends Handler<T> {
_event: any;
@@ -38,12 +108,16 @@ export interface Handler<T> {
emitWithState: any;
state: any;
handler: any;
i18n: any;
locale: any;
event: RequestBody<T>;
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<T> {
version: string;
session: Session;
@@ -66,20 +160,22 @@ export interface RequestBody<T> {
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<T extends TemplateBuilder<T>> {
setTextContent(primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): T;
}
interface SetListItems<T extends TemplateBuilder<T>> {
setListItems(listItems: ListItem[]): T;
}
/**
* Refer https://developer.amazon.com/docs/custom-skills/display-interface-reference.html#image-sizes
*/
abstract class TemplateBuilder<T extends TemplateBuilder<T>> {
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<BodyTemplate1Builder> implements SetTextContent<BodyTemplate1Builder> {
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<BodyTemplate2Builder> implements SetTextContent<BodyTemplate2Builder> {
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<BodyTemplate3Builder> implements SetTextContent<BodyTemplate3Builder> {
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<BodyTemplate6Builder> implements SetTextContent<BodyTemplate6Builder> {
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<BodyTemplate7Builder> {
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<ListTemplate1Builder> implements SetListItems<ListTemplate1Builder> {
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<ListTemplate2Builder> implements SetListItems<ListTemplate2Builder> {
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<ApiClientResponse>
*/
post(uri: string, headers: object, body?: string): Promise<ApiClientResponse>;
/**
* 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<ApiClientResponse>
*/
put(uri: string, headers: object, body?: string): Promise<ApiClientResponse>;
/**
* 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<ApiClientResponse>
*/
get(uri: string, headers: object): Promise<ApiClientResponse>;
/**
* 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<ApiClientResponse>
*/
delete(uri: string, headers: object): Promise<ApiClientResponse>;
}
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<object>
*/
getFullAddress(deviceId: string, apiEndpoint: string, token: string): Promise<object>;
/**
* 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<object>
*/
getCountryAndPostalCode(deviceId: string, apiEndpoint: string, token: string): Promise<object>;
}
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<void>
*/
enqueue(directive: object, apiEndpoint: string, token: string): Promise<void>;
}
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<object>
*/
getListsMetadata(token: string): Promise<object>;
/**
* 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<object>
*/
createList(listObject: ListObject, token: string): Promise<object>;
/**
* 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<object>
*/
getList(listId: string, itemStatus: ListItemObjectStatus, token: string): Promise<object>;
/**
* 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<object>
*/
updateList(listId: string, listObject: ListObject, token: string): Promise<object>;
/**
* Delete a custom list
* @param listId unique Id associated with the list
* @param token bearer token for list management permission
* @returns Promise<object>
*/
deleteList(listId: string, token: string): Promise<object>;
/**
* 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<object>
*/
createListItem(listId: string, listItemObject: ListItemObject, token: string): Promise<object>;
/**
* 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<object>
*/
getListItem(listId: string, itemId: string, token: string): Promise<object>;
/**
* 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<object>
*/
updateListItem(listId: string, itemId: string, listItemObject: ListItemObject, token: string): Promise<object>;
/**
* 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<object>
*/
deleteListItem(listId: string, itemId: string, token: string): Promise<object>;
}
}
//#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<Request>);
/**
* 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
+1 -1
View File
@@ -20,4 +20,4 @@
"index.d.ts",
"alexa-sdk-tests.ts"
]
}
}
+10 -9
View File
@@ -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
}
}
+3 -3
View File
@@ -121,12 +121,12 @@ let _algoliaQueryParameters: AlgoliaQueryParameters = {
disableTypoToleranceOnAttributes: '',
aroundLatLng: '',
aroundLatLngViaIP: '',
aroundRadius: '',
aroundRadius: 0,
aroundPrecision: 0,
minimumAroundRadius: 0,
insideBoundingBox: '',
insideBoundingBox: [[0]],
queryType: '',
insidePolygon: '',
insidePolygon: [[0]],
removeWordsIfNoResults: '',
advancedSyntax: false,
optionalWords: [''],
+20 -18
View File
@@ -49,6 +49,9 @@ declare namespace algoliasearch {
*/
params: string;
}
interface AlgoliaMultiResponse {
results: AlgoliaResponse[];
}
/*
Interface for the algolia client object
*/
@@ -71,8 +74,8 @@ declare namespace algoliasearch {
indexName: string;
query: string;
params: AlgoliaQueryParameters;
},
cb: (err: Error, res: any) => void
}[],
cb: (err: Error, res: AlgoliaMultiResponse) => void
): void;
/**
* Query on multiple index
@@ -84,7 +87,7 @@ declare namespace algoliasearch {
indexName: string;
query: string;
params: AlgoliaQueryParameters;
}): Promise<AlgoliaResponse>;
}[]): Promise<AlgoliaMultiResponse>;
/**
* clear browser cache
* https://github.com/algolia/algoliasearch-client-js#cache
@@ -319,8 +322,8 @@ declare namespace algoliasearch {
getLogs(options: LogsOptions): Promise<any>;
}
/**
* Interface for the index algolia object
*/
* Interface for the index algolia object
*/
interface AlgoliaIndex {
/**
* Gets a specific object
@@ -783,7 +786,7 @@ declare namespace algoliasearch {
* @param err() error callback
* https://github.com/algolia/algoliasearch-client-js#search-in-an-index---search
*/
search(params: AlgoliaQueryParameters): Promise<any>;
search(params: AlgoliaQueryParameters): Promise<AlgoliaResponse>;
/**
* Search in an index
* @param params query parameter
@@ -793,7 +796,7 @@ declare namespace algoliasearch {
*/
search(
params: AlgoliaQueryParameters,
cb: (err: Error, res: any) => void
cb: (err: Error, res: AlgoliaResponse) => void
): void;
/**
* Search in an index
@@ -809,8 +812,7 @@ declare namespace algoliasearch {
}: {
facetName: string;
facetQuery: string;
} & AlgoliaQueryParameters
): Promise<any>;
} & AlgoliaQueryParameters): Promise<any>;
/**
* Search in an index
* @param params query parameter
@@ -1071,8 +1073,8 @@ Interface describing options available for gettings the logs
type?: string;
}
/**
* Describe the action object used for batch operation
*/
* Describe the action object used for batch operation
*/
interface AlgoliaAction {
/**
* Type of the batch action
@@ -1098,8 +1100,8 @@ Interface describing options available for gettings the logs
body: {};
}
/**
* Describes the option used when creating user key
*/
* Describes the option used when creating user key
*/
interface AlgoliaApiKeyOptions {
/**
* Add a validity period. The key will be valid for a specific period of time (in seconds).
@@ -1364,8 +1366,8 @@ Interface describing options available for gettings the logs
}
/**
* Describes the settings available for configure your index
*/
* Describes the settings available for configure your index
*/
interface AlgoliaIndexSettings {
/**
* The list of attributes you want index
@@ -1770,7 +1772,7 @@ Interface describing options available for gettings the logs
* You can specify aroundRadius=all if you want to compute the geo distance without filtering in a geo area
* https://github.com/algolia/algoliasearch-client-js#aroundradius
*/
aroundRadius?: any;
aroundRadius?: number | 'all';
/**
* Control the precision of a geo search
* default: null
@@ -1788,7 +1790,7 @@ Interface describing options available for gettings the logs
* default: null
* https://github.com/algolia/algoliasearch-client-js#insideboundingbox
*/
insideBoundingBox?: string;
insideBoundingBox?: number[][];
/**
* Selects how the query words are interpreted
* default: 'prefixLast'
@@ -1803,7 +1805,7 @@ Interface describing options available for gettings the logs
* defauly: ''
* https://github.com/algolia/algoliasearch-client-js#insidepolygon
*/
insidePolygon?: string;
insidePolygon?: number[][];
/**
* This option is used to select a strategy in order to avoid having an empty result page
* default: 'none'
+722 -1
View File
@@ -1549,7 +1549,7 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val
/** Hides cursor. */
hideCursor(): void;
/** You can force cursor to appear at specified cateogry or date. */
showCursorAt(category: string): void;
showCursorAt(category: string | Date): void;
/** Adds event listener of the type "changed" to the object.
@param type Always "changed".
@param handler Dispatched when cursor position is changed. "index" is a series index over which chart cursors currently is. "zooming" specifies if user is currently zooming (is selecting) the chart. mostCloseGraph property is set only when oneBalloonOnly is set to true.*/
@@ -1652,6 +1652,727 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val
zoomToIndexes(start: Date, end: Date): void;
}
// AmAngularGauge Extension for AmChart to create gauge charts.
class AmAngularGauge extends AmChart {
/** When enabled, chart adds aria-label attributes to columns, bullets or map objects. You can control values of these labels using properties like accessibleLabel of AmGraph. Note, not all screen readers support these tags. We tested this mostly with NVDA Screen reader. WAI-ARIA is now official W3 standard, so in future more readers will handle this well. We will be improving accessibility on our charts, so we would be glad to hear your feedback.
@default true
*/
accessible: boolean;
/** Description which will be added to node of SVG element. Most of the screen readers will read this description. */
accessibleDescription: string;
/** Description which is added to of a SVG element. Some of the screen readers will read this description. */
accessibleTitle: string;
/** Specifies, if class names should be added to chart elements.
@default false
*/
addClassNames: boolean;
/** Uses the whole space of the canvas to draw the gauge.
@default true
*/
adjustSize: boolean;
/** Array of Labels. Example of label object, with all possible properties:
{"x": 20, "y": 20, "text": "this is label", "align": "left", "size": 12, "color": "#CC0000", "alpha": 1, "rotation": 0, "bold": true, "url": "http://www.amcharts.com"}
@default []
*/
allLabels: [Label]
/** Array of arrows. */
arrows: [GaugeArrow];
/** If you set it to true the chart will automatically monitor changes of display style of charts container (or any of its parents) and will render chart correctly if it is changed from none to block. We recommend setting it to true if you change this style at a run time, as it affects performance a bit.
@default false
*/
autoDisplay: boolean;
/** Set this to false if you don't want chart to resize itself whenever its parent container size changes.
@default true
*/
autoResize: boolean;
/** If you set it to true and your chart div (or any of the parent div) has css scale applied, the chart will position mouse at a correct position. Default value is false because this operation consumes some CPU and quite a few people are using css transfroms.
@default false
*/
autoTransform: boolean;
/** Array of axes.
@default [GaugeAxis]
*/
axes: [GaugeAxis];
/** Opacity of background. Set it to >0 value if you want backgroundColor to work. However we recommend changing div's background-color style for changing background color.
@default 0
*/
backgroundAlpha: number;
/** Background color. You should set backgroundAlpha to >0 value in order background to be visible. We recommend setting background color directly on a chart's DIV instead of using this property.
@default #FFFFFF
*/
backgroundColor: string;
/** The chart creates AmBalloon class itself. If you want to customize balloon, get balloon instance using this property, and then change balloon's properties.
@default AmBalloon
*/
balloon: AmBalloon;
/** Opacity of chart's border. Value range is 0 - 1.
@default 0
*/
borderAlpha: number;
/** Color of chart's border. You should set borderAlpha >0 in order border to be visible. We recommend setting border color directly on a chart's DIV instead of using this property.
@default #000000
*/
borderColor: string;
/** This prefix is added to all class names which are added to all visual elements of a chart in case addClassNames is set to true.
@default amcharts
*/
classNamePrefix: string;
/** In case you use gauge to create a clock, set this to true.
@default false
*/
clockWiseOnly: boolean;
/** Text color.
@default #000000
*/
color: string;
/** Non-commercial version only. Specifies position of link to amCharts site. Allowed values are: top-left, top-right, bottom-left and bottom-right.
@default 'top - left'
*/
creditsPosition: string;
/** A config object for Data Loader plugin. Please refer to the following page for more information. */
dataLoader: Object;
/** Array of data objects, for example: [{country:"US", value:524},{country:"UK", value:624},{country:"Lithuania", value:824}]. You can have any number of fields and use any field names. In case of AmMap, data provider should be MapData object.
The data set data.
Important: if you are using date/time-based category axis, the data points needs to come pre-ordered in ascending order. Data with incorrect order might result in visual and functional glitches on the chart. */
dataProvider: [Object];
/** Decimal separator.
@default .
*/
decimalSeparator: string;
/** Using this property you can add any additional information to SVG, like SVG filters or clip paths. The structure of this object should be identical to XML structure of a object you are adding, only in JSON format. */
defs: Object;
/** Export config. Specifies how export to image/data export/print/annotate menu will look and behave. You can find a lot of examples in amcharts/plugins/export folder. More details can be found here. */
export: ExportSettings;
/** Gauge face opacity.
@default 0
*/
faceAlpha: number;
/** Gauge face border opacity.
@default 0
*/
faceBorderAlpha: number;
/** Gauge face border color.
@default #555555
*/
faceBorderColor: string;
/** Gauge face border width.
@default 1
*/
faceBorderWidth: number;
/** Gauge face color, requires faceAlpha > 0
@default #FAFAFA
*/
faceColor: string;
/** Gauge face image-pattern.
Example: {"url":"../amcharts/patterns/black/pattern1.png", "width":4, "height":4}
fontFamily String Verdana Font family.
fontSize Number 11 Font size. */
facePattern: Object;
/** Gauge's horizontal position in pixel, origin is the center. Centered by default. */
gaugeX: number;
/** Gauge's vertical position in pixel, origin is the center. Centered by default. */
gaugeY: number;
/** If you set this to true, the lines of the chart will be distorted and will produce hand-drawn effect. Try to adjust chart.handDrawScatter and chart.handDrawThickness properties for a more scattered result.
@default false
*/
handDrawn: boolean;
/** Defines by how many pixels hand-drawn line (when handDrawn is set to true) will fluctuate.
@default 2
*/
handDrawScatter: number;
/** Defines by how many pixels line thickness will fluctuate (when handDrawn is set to true).
@default 1
*/
handDrawThickness: number;
/** Time, in milliseconds after which balloon is hidden if the user rolls-out of the object. Might be useful for AmMap to avoid balloon flickering while moving mouse over the areas. Note, this is not duration of fade-out. Duration of fade-out is set in AmBalloon class.
@default 150
*/
hideBalloonTime: number;
/** Allows changing language easily. Note, you should include language js file from amcharts/lang or ammap/lang folder and then use variable name used in this file, like chart.language = "de"; Note, for maps this works differently - you use language only for country names, as there are no other strings in the maps application. */
language: string;
/** Legend of a chart. */
legend: AmLegend;
/** Read-only. Reference to the div of the legend. */
legendDiv: HTMLElement;
/** You can add listeners of events using this property. Example: listeners = [{"event":"dataUpdated", "method":handleEvent}];
@default [Object]
*/
listeners: [Object];
/** Bottom spacing between chart and container.
@default 10
*/
marginBottom: number;
/** Left-hand spacing between chart and container.
@default 10
*/
marginLeft: number;
/** Right-hand spacing between chart and container.
@default 10
*/
marginRight: number;
/** Top spacing between chart and container.
@default 10
*/
marginTop: number;
/** Minimum radius of a gauge.
@default 10
*/
minRadius: number;
/** This setting affects touch-screen devices only. If a chart is on a page, and panEventsEnabled are set to true, the page won't move if the user touches the chart first. If a chart is big enough and occupies all the screen of your touch device, the user wont be able to move the page at all. If you think that selecting/panning the chart or moving/pinching the map is a primary purpose of your users, you should set panEventsEnabled to true, otherwise - false.
@default true
*/
panEventsEnabled: boolean;
/** Specifies absolute or relative path to amCharts files, i.e."amcharts/". (where all.js files are located)
If relative URLs are used, they will be relative to the current web page, displaying the chart.
You can also set path globally, using global JavaScript variable AmCharts_path.If this variable is set, and "path" is not set in chart config, the chart will assume the path from the global variable.This allows setting amCharts path globally.I.e.:
var AmCharts_path = "/libs/amcharts/";
"path" parameter will be used by the charts to locate it's files, like images, plugins or patterns.
@default 'amcharts/'
*/
path: string;
/** Specifies path to the folder where images like resize grips, lens and similar are.
IMPORTANT: Since V3.14.12, you should use "path" to point to amCharts directory instead. The "pathToImages" will be automatically set and does not need to be in the chart config, unless you keep your images separately from other amCharts files. */
pathToImages: string;
/** Precision of percent values. -1 means percent values won't be rounded at all and show as they are.
@default 2
*/
percentPrecision: number;
/** Precision of values. -1 means values won't be rounded at all and show as they are.
@default -1
*/
precision: number;
/**Prefixes which are used to make big numbers shorter: 2M instead of 2000000, etc.Prefixes are used on value axes and in the legend.To enable prefixes, set usePrefixes property to true.
@default [{ "number": 1e+3, "prefix": "k" }, { "number": 1e+6, "prefix": "M" }, { "number": 1e+9, "prefix": "G" }, { "number": 1e+12, "prefix": "T" }, { "number": 1e+15, "prefix": "P" }, { "number": 1e+18, "prefix": "E" }, { "number": 1e+21, "prefix": "Z" }, { "number": 1e+24, "prefix": "Y" }]
*/
prefixesOfBigNumbers: [Object];
/** Prefixes which are used to make small numbers shorter: 2μ instead of 0.000002, etc.Prefixes are used on value axes and in the legend.To enable prefixes, set usePrefixes property to true.
@default [{ "number": 1e-24, "prefix": "y" }, { "number": 1e-21, "prefix": "z" }, { "number": 1e-18, "prefix": "a" }, { "number": 1e-15, "prefix": "f" }, { "number": 1e-12, "prefix": "p" }, { "number": 1e-9, "prefix": "n" }, { "number": 1e-6, "prefix": "μ" }, { "number": 1e-3, "prefix": "m" }]
*/
prefixesOfSmallNumbers: [Object];
/** If processTimeout is > 0, 1000 data items will be parsed at a time, then the chart will make pause and continue parsing data until it finishes.
@default 1000
*/
processCount: number;
/** If you set it to 1 millisecond or some bigger value, chart will be built in chunks instead of all at once. This is useful if you work with a lot of data and the initial build of the chart takes a lot of time, which freezes the whole web application by not allowing other processes to do their job while the chart is busy.
@default 0
*/
processTimeout: number;
/** A config object for Responsive plugin. Please refer to the following page for more information. */
responsive: Object
/** Duration of arrow animation.
@default 1
*/
startDuration: number;
/** Transition effect of the arrows, possible effects: easeOutSine, easeInSine, elastic, bounce.
@default easeInSine
*/
startEffect: string;
/** Charts will use SVG icons (some are loaded from images folder and some are drawn inline) if browser supports SVG. his makes icons look good on retina displays on all resolutions.
@default true
*/
svgIcons: boolean;
/** Charts which require gestures like swipe (charts with scrollbar/cursor) or pinch (maps) used to prevent regular page scrolling and could result page to stick to the same spot if the chart occupied whole screen. Now, in order these gestures to start working user has to touch the chart/maps once. Regular touch events like touching on the bar/slice/map area do not require the first tap and will show balloons and perform other tasks as usual. If you have a map or chart which occupies full screen and your page does not require scrolling, set tapToActivate to false this will bring old behavior back.
@default true
*/
tapToActivate: boolean;
/** Theme of a chart. Config files of themes can be found in amcharts/themes/ folder. More info about using themes.
@default none
*/
theme: string;
/** Thousands separator.
@default ,
*/
thousandsSeparator: string;
/** Array of Title objects.
@default []
*/
titles: [Title];
/** If you set it to 200 (milliseconds) or so, the chart will fire clickGraphItem or clickSlice (AmSlicedChart) or clickMapObject only if user holds his/her finger for 0.2 seconds (200 ms) on the column/bullet/slice/map object.
@default 0
*/
touchClickDuration: number;
/** Type of a chart. Required when creating chart using JSON. Possible types are: serial, pie, xy, radar, funnel, gauge, map, gantt, stock. */
type: string;
/** If true, prefixes will be used for big and small numbers.You can set arrays of prefixes via prefixesOfSmallNumbers and prefixesOfBigNumbers properties.
@default false
*/
usePrefixes: boolean;
/** Read-only. Indicates current version of a script. */
version: string;
/** Adds arrow to the chart. */
addArrow(arrow: GaugeArrow): void;
/** Adds axis to angular gauge. */
addAxis(axis: GaugeAxis): void;
/** Adds a label on a chart. You can use it for labeling axes, adding chart title, etc. x and y coordinates can be set in number, percent, or a number with ! in front of it - coordinate will be calculated from right or bottom instead of left or top. */
addLabel(x: number, y: number, text: string, align: string, size: number, color: string, rotation: number, alpha: number, bold: boolean, url: string): void;
/** Adds a legend to the chart. By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter. (NOTE: This method will not work on StockPanel.) */
addLegend(legend: AmLegend, legendDivId?: string): void;
/** Adds a legend to the chart.
By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter.
(NOTE: This method will not work on StockPanel.)
@param legend
@param legendDiv - Legend div (optional).
*/
addLegend(legend: AmLegend, legendDiv: HTMLElement): void;
/** Adds event listener to the object. */
addListener(type: string, handler: Function): void;
/** Adds title to the top of the chart. Pie, Radar positions are updated so that they won't overlap. Plot area of Serial/XY chart is also updated unless autoMargins property is set to false. You can add any number of titles - each of them will be placed in a new line. To remove titles, simply clear titles array: chart.titles = []; and call chart.validateNow() method. */
addTitle(text: string, size: number, color: string, alpha: number, bold: boolean): void;
/** Clears the chart area, intervals, etc. */
clear(): void;
/** Removes all labels added to the chart. */
clearLabels(): void;
/** Use this method to force the chart to resize to it's current container size. */
invalidateSize(): void;
/** This method allows to create charts with a single config. */
makeChart(container: string, config: any, delay: number): AmChart;
/** Removes arrow from the chart. */
removeArrow(arrow: GaugeArrow): void;
/** Removes axis from the chart. */
removeAxis(axis: GaugeAxis): void;
/** Removes chart's legend. */
removeLegend(): void;
/** Removes event listener from chart object. */
removeListener(chart: AmChart, type: string, handler: any): void;
/** This method should be called after data in your data provider changed or a new array was set to dataProvider. After calling this method the chart will parse data and redraw. */
validateData(): void;
/** This method should be called after you changed one or more properties of any class. The chart will redraw after this method is called.Both attributes, validateData and skipEvents are optional (false by default). */
validateNow(): void;
/** Adds chart to the specified DIV.
@param container DIV object which will hold the chart. */
write(container: HTMLElement): void;
/** Adds chart to the specified DIV.
@param container Id of a DIV which will hold the chart. */
write(container: string): void;
}
class GaugeArrow {
/** Opacity of an arrow.
@default 1
*/
alpha: number;
/** Axis of the arrow. You can use reference to the axis or id of the axis. If you don't set any axis, the first axis of a chart will be used.
@default GaugeAxis
*/
axis: GaugeAxis
/** Opacity of arrow border.
@default 1
*/
borderAlpha: number;
/** In case you need the arrow to rotate only clock-wise, set this property to true.
@default false
*/
clockWiseOnly: boolean;
/** Color of an arrow.
@default #000000
*/
color: string;
/** Unique id of an arrow. */
id: string;
/** Inner radius of an arrow.
@default 0
*/
innerRadius: any;
/** Opacity of a nail, holding the arrow.
@default 1
*/
nailAlpha: number;
/** Opacity of nail border.
@default 0
*/
nailBorderAlpha: number;
/** Thickness of nail border.
@default 1
*/
nailBorderThickness: number;
/** Radius of a nail, holding the arrow.
@default 8
*/
nailRadius: number;
/** Radius of an arrow.
@default '90%'
*/
radius: any;
/** Width of arrow root.
@default 8
*/
startWidth: number;
/** Value to which the arrow should point at. */
value: number;
/** Sets value for the arrow. Arrow will animate to this value if you do it after chart is written to it's container. */
setValue(value: number): void;
}
class GaugeAxis {
/** Axis opacity.
@default 1
*/
axisAlpha: number;
/** Axis color.
@default #000000
*/
axisColor: string;
/** Thickness of the axis outline.
@default 1
*/
axisThickness: number;
/** Opacity of band fills.
@default 1
*/
bandAlpha: number;
/** Example: [-0.2, 0, -0.2]. Will make bands to be filled with color gradients. Negative value means the color will be darker than the original, and positive number means the color will be lighter.
@default []
*/
bandGradientRatio: [number];
/** Opacity of band outlines.
@default 0
*/
bandOutlineAlpha: number;
/** Color of band outlines.
@default #000000
*/
bandOutlineColor: string;
/** Thickness of band outlines.
@default 0
*/
bandOutlineThickness: number;
/** Array of bands - GaugeBand objects. Bands are used to draw color fills between specified values. */
bands: [GaugeBand];
/** Text displayed below the axis center. */
bottomText: string;
/** Specifies if text should be bold.
@default true
*/
bottomTextBold: boolean;
/** Bottom text color. */
bottomTextColor: string;
/** Font size of bottom text. */
bottomTextFontSize: number;
/** Y offset of bottom text.
@default 0
*/
bottomTextYOffset: number;
/** X position of the axis, relative to the center of the gauge.
@default '0%'
*/
centerX: any;
/** Y position of the axis, relative to the center of the gauge.
@default '0%'
*/
centerY: any;
/** Specifies labels color of the axis. */
color: string
/** Axis end angle. Valid values are from - 180 to 180.
@default 120
*/
endAngle: number;
/** Axis end (max) value */
endValue: number;
/** Font size for axis labels. */
fontSize: number;
/** Number of grid lines. Note, GaugeAxis doesn't adjust gridCount, so you should check your values and choose a proper gridCount which would result grids at round numbers.
@default 5
*/
gridCount: number;
/** Specifies if grid should be drawn inside or outside the axis.
@default true
*/
gridInside: boolean;
/** Unique id of an axis. */
id: any;
/** Specifies if labels should be placed inside or outside the axis.
@default true
*/
inside: boolean;
/** Frequency of labels.
@default 1
*/
labelFrequency: number;
/** You can use this function to format axis labels. This function is called and value is passed as a attribute: labelFunction(value); */
labelFunction: Function;
/** Distance from axis to the labels.
@default 15
*/
labelOffset: number;
/** Specifies if labels on the axis should be shown.
@default true
*/
labelsEnabled: boolean;
/** You can add listeners of events using this property. Example: listeners = [{"event":"clickBand", "method":handleClick}]; */
listeners: Object[];
/** Interval, at which minor ticks should be placed. */
minorTickInterval: number;
/** Length of a minor tick.
@default 5
*/
minorTickLength: number
/** Axis radius.
@default '95%'
*/
radius: any;
/** Specifies if the first label should be shown.
@default true
*/
showFirstLabel: boolean;
/** Specifies if the last label should be shown.
@default true
*/
showLastLabel: boolean;
/** Axis start angle. Valid values are from - 180 to 180.
@default -120
*/
startAngle: number;
/** Axis start (min) value.
@default 0
*/
startValue: number;
/** Opacity of axis ticks.
@default 1
*/
tickAlpha: number;
/** Color of axis ticks.
@default #555555
*/
tickColor: string;
/** Length of a major tick.
@default 10
*/
tickLength: number;
/** Tick thickness.
@default 1
*/
tickThickness: number;
/** Text displayed above the axis center. */
topText: string
/** Specifies if text should be bold.
@default true
*/
topTextBold: boolean;
/** Color of top text. */
topTextColor: string
/** Font size of top text. */
topTextFontSize: number
/** Y offset of top text.
@default 0
*/
topTextYOffset: number;
/** A string which can be placed next to axis labels. */
unit: string;
/** Position of the unit.
@default right
*/
unitPosition: string;
/** Specifies if small and big numbers should use prefixes to make them more readable.
@default false
*/
usePrefixes: boolean;
/** Interval, at which ticks with values should be placed. */
valueInterval: number;
/** Adds event listener to the object. */
addListener(type: string, handler: any);
/** Removes event listener from chart object. */
removeListener(chart: AmChart, type: string, handler: any);
/** Sets bottom text. */
setBottomText(text: string);
/** Sets top text. */
setTopText(textstring);
/** Returns angle of the value. */
value2angle(value: number);
}
class GaugeBand {
/** Opacity of band fill. Will use axis.bandAlpha if not set any. */
alpha: number;
/** When rolled-over, band will display balloon if you set some text for this property. */
balloonText: string;
/** Color of a band. */
color: string;
/** End value of a fill. */
endValue: number
/** Example: [-0.2, 0, -0.2]. Will make bands to be filled with color gradients. Negative value means the color will be darker than the original, and positive number means the color will be lighter.
@default []
*/
gradientRatio: [number];
/** Unique id of a band. */
id: string;
/** Inner radius of a band. If not set any, the band will end with the end of minor ticks. Set 0 if you want the band to be drawn to the axis center. */
innerRadius: any;
/** Band radius. If not set any, the band will start with the axis outline. */
radius: any;
/** Start value of a fill. */
startValue: number;
/** Gauge band can be clickable and can lead to some page. */
url: string;
/** Sets end value for the band. */
setEndValue(value);
/** Sets start value for the band. */
setStartValue(value);
}
class PeriodSelector {
/** Date format of date input fields. Check [[http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/formatters/DateFormatter.html DD-MM-YYYY */
dateFormat: string;
@@ -1,69 +1,62 @@
let dummySocket: ng.websocket.IWebSocket;
let dummyPromise: ng.IPromise<void>;
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<void>, 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;
};
+40 -35
View File
@@ -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 <https://github.com/nickveys>
// 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<void>;
interface IWebSocketQueueItem {
message: any;
defered: IPromise<void>;
}
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<any>;
send(data: string | {}): IPromise<any>;
/**
* 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
+8 -8
View File
@@ -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
}
}
},
"files": [
"index.d.ts",
"angular-websocket-tests.ts"
]
}
+1 -74
View File
@@ -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
}
}
+13
View File
@@ -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']
+7
View File
@@ -0,0 +1,7 @@
// Type definitions for ansi-regex 3.0
// Project: https://github.com/chalk/ansi-regex#readme
// Definitions by: Manish Vachharajani <https://github.com/mvachhar>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function r(): RegExp;
export = r;
+23
View File
@@ -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"
]
}
+47
View File
@@ -0,0 +1,47 @@
import appdmg = require("appdmg");
import { Options, Specification, SpecificationOptions } from "appdmg";
const proc = appdmg({
target: "/foo/bar.dmg",
basepath: "/baz",
specification: {
title: "Happy",
icon: "happy.icns",
background: "happy.tiff",
format: "UDBZ",
"icon-size": 98,
contents: [
{
x: 405,
y: 150,
type: "link",
path: "/Applications"
},
{
x: 127,
y: 150,
type: "file",
path: "/foo/bar.app"
}
]
}
});
proc.on("progress", info => {
if (info.type === "step-begin") {
process.stdout.write(`${info.title}... `);
}
if (info.type === "step-end") {
process.stdout.write(`${info.status}\n`);
}
});
proc.on("finish", () => {
console.log('Installer was created successfully!');
});
proc.on("error", (err) => {
console.error('Installer could not be created', err);
process.exit(1);
});
+70
View File
@@ -0,0 +1,70 @@
// Type definitions for appdmg 0.5
// Project: https://github.com/LinusU/node-appdmg#readme
// Definitions by: Daniel Perez Alvarez <https://github.com/unindented>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
declare namespace appdmg {
interface Progress {
current: number;
total: number;
type: "step-begin" | "step-end";
title: string;
status: "ok" | "skip" | "fail";
}
interface EventEmitter extends NodeJS.EventEmitter {
on(event: "progress", listener: (info: Progress) => void): this;
on(event: "finish", listener: () => void): this;
on(event: "error", listener: (err: any) => void): this;
}
interface SpecificationOptions {
app: string;
background: string;
icon: string;
iconSize: number;
title: string;
}
interface SpecificationWindow {
position?: { x: number; y: number };
size?: { width: number; height: number };
}
interface SpecificationContents {
x: number;
y: number;
type: "link" | "file" | "position";
path: string;
name?: string;
}
interface SpecificationCodeSign {
"signing-identity": string;
identifier?: string;
}
interface Specification {
title: string;
icon?: string;
background?: string;
"background-color"?: string;
"icon-size"?: number;
window?: SpecificationWindow;
format: "UDRW" | "UDRO" | "UDCO" | "UDZO" | "UDBZ" | "ULFO";
contents: SpecificationContents[];
"code-sign"?: SpecificationCodeSign;
}
interface Options {
target: string;
basepath: string;
specification: Specification;
}
}
declare function appdmg(options?: appdmg.Options): appdmg.EventEmitter;
export = appdmg;
+23
View File
@@ -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",
"appdmg-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+51 -9
View File
@@ -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";
});
});
+322 -52
View File
@@ -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 <https://martincostello.com/>
// Definitions by: Martin Costello <https://github.com/martincostello>
// 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<boolean>;
/**
* 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<boolean>;
/**
* 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 contacts 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;
}
+1 -1
View File
@@ -1,6 +1,6 @@
import * as ascii2mathml from 'ascii2mathml';
const fn = ascii2mathml({}); // $ExpectType any
const fn = ascii2mathml({}); // $ExpectType ascii2mathml
fn(''); // $ExpectType string
ascii2mathml('', {}); // $ExpectType string
+37 -37
View File
@@ -9,16 +9,16 @@
import { EventEmitter } from "events";
export abstract class AsyncIterator<T> extends NodeJS.EventEmitter {
protected static STATES: ['INIT', 'OPEN', 'CLOSING', 'CLOSED', 'ENDED'];
protected static INIT: 0;
protected static OPEN: 1;
protected static CLOSING: 2;
protected static CLOSED: 3;
protected static ENDED: 4;
static STATES: ['INIT', 'OPEN', 'CLOSING', 'CLOSED', 'ENDED'];
static INIT: 0;
static OPEN: 1;
static CLOSING: 2;
static CLOSED: 3;
static ENDED: 4;
protected _state: number;
protected _readable: boolean;
protected _destination?: AsyncIterator<any>;
_state: number;
_readable: boolean;
_destination?: AsyncIterator<any>;
readable: boolean;
closed: boolean;
@@ -30,11 +30,11 @@ export abstract class AsyncIterator<T> extends NodeJS.EventEmitter {
each(callback: (data: T) => void, self?: any): void;
close(): void;
protected _changeState(newState: number, eventAsync?: boolean): void;
_changeState(newState: number, eventAsync?: boolean): void;
private _hasListeners(eventName: string | symbol): boolean;
// tslint:disable-next-line ban-types
private _addSingleListener(eventName: string | symbol, listener: Function): void;
protected _end(): void;
_end(): void;
getProperty(propertyName: string, callback?: (value: any) => void): any;
setProperty(propertyName: string, value: any): void;
@@ -43,7 +43,7 @@ export abstract class AsyncIterator<T> extends NodeJS.EventEmitter {
copyProperties(source: AsyncIterator<any>, propertyNames: string[]): void;
toString(): string;
protected _toStringDetails(): string;
_toStringDetails(): string;
transform<T2>(options?: SimpleTransformIteratorOptions<T, T2>): SimpleTransformIterator<T, T2>;
map<T2>(mapper: (item: T) => T2, self?: object): SimpleTransformIterator<T, T2>;
@@ -78,9 +78,9 @@ export interface IntegerIteratorOptions {
}
export class IntegerIterator extends AsyncIterator<number> {
protected _step: number;
protected _last: number;
protected _next: number;
_step: number;
_last: number;
_next: number;
constructor(options?: IntegerIteratorOptions);
}
@@ -92,16 +92,16 @@ export interface BufferedIteratorOptions {
export class BufferedIterator<T> extends AsyncIterator<T> {
maxBufferSize: number;
protected _pushedCount: number;
protected _buffer: T[];
_pushedCount: number;
_buffer: T[];
protected _init(autoStart: boolean): void;
protected _begin(done: () => void): void;
protected _read(count: number, done: () => void): void;
protected _push(item: T): void;
protected _fillBuffer(): void;
protected _completeClose(): void;
protected _flush(done: () => void): void;
_init(autoStart: boolean): void;
_begin(done: () => void): void;
_read(count: number, done: () => void): void;
_push(item: T): void;
_fillBuffer(): void;
_completeClose(): void;
_flush(done: () => void): void;
constructor(options?: BufferedIteratorOptions);
}
@@ -112,12 +112,12 @@ export interface TransformIteratorOptions<S> extends BufferedIteratorOptions {
}
export class TransformIterator<S, T> extends BufferedIterator<T> {
protected _optional: boolean;
_optional: boolean;
source: AsyncIterator<S>;
protected _validateSource(source: AsyncIterator<S>, allowDestination?: boolean): void;
protected _transform(item: S, done: (result: T) => void): void;
protected _closeWhenDone(): void;
_validateSource(source: AsyncIterator<S>, allowDestination?: boolean): void;
_transform(item: S, done: (result: T) => void): void;
_closeWhenDone(): void;
constructor(source?: AsyncIterator<S> | TransformIteratorOptions<S>, options?: TransformIteratorOptions<S>);
}
@@ -134,16 +134,16 @@ export interface SimpleTransformIteratorOptions<S, T> extends TransformIteratorO
}
export class SimpleTransformIterator<S, T> extends TransformIterator<S, T> {
protected _offset: number;
protected _limit: number;
protected _prepender?: ArrayIterator<T>;
protected _appender?: ArrayIterator<T>;
_offset: number;
_limit: number;
_prepender?: ArrayIterator<T>;
_appender?: ArrayIterator<T>;
protected _filter?(item: S): boolean;
protected _map?(item: S): T;
protected _transform(item: S, done: (result: T) => void): void;
_filter?(item: S): boolean;
_map?(item: S): T;
_transform(item: S, done: (result: T) => void): void;
protected _insert(inserter: AsyncIterator<S>, done: () => void): void;
_insert(inserter: AsyncIterator<S>, done: () => void): void;
constructor(source?: AsyncIterator<S> | SimpleTransformIteratorOptions<S, T>,
options?: SimpleTransformIteratorOptions<S, T>);
@@ -152,7 +152,7 @@ export class SimpleTransformIterator<S, T> extends TransformIterator<S, T> {
export class MultiTransformIterator<S, T> extends TransformIterator<S, T> {
_transformerQueue: S[];
protected _createTransformer(): AsyncIterator<S>;
_createTransformer(element: S): AsyncIterator<T>;
constructor(source?: AsyncIterator<S> | TransformIteratorOptions<S>, options?: TransformIteratorOptions<S>);
}
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://github.com/atom/atom-keymap
// Definitions by: GlenCFL <https://github.com/GlenCFL>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
// TypeScript Version: 2.3
import { Disposable } from "event-kit";
+26 -2
View File
@@ -844,9 +844,12 @@ function testDock() {
}
// Emitter ====================================================================
interface TestEmissions {
"test-event": string;
}
function testEmitter() {
emitter = new Atom.Emitter();
emitter.clear();
emitter.dispose();
@@ -858,6 +861,27 @@ function testEmitter() {
// Event Emission
emitter.emit("test-event");
emitter.emit("test-event", 42);
// Optional Value Emitter
const optEmitter = new Atom.Emitter<{ "test-event": string }>();
optEmitter.emit("test-event");
optEmitter.emit("test-event", "test");
optEmitter.on("test-event", value => {
str = value ? value : "";
});
// Required Value Emitter
const reqEmitter = new Atom.Emitter<{}, TestEmissions>();
reqEmitter.on("test-event", value => {
str = value;
});
reqEmitter.emit("test-event", "test");
// Mixed Value Emitter
const mixedEmitter = new Atom.Emitter<{ "t1": "test" }, { "t2": "test" }>();
mixedEmitter.emit("t1");
mixedEmitter.emit("t1", "test");
mixedEmitter.emit("t2", "test");
}
// File =======================================================================
@@ -2939,7 +2963,7 @@ function testTooltipManager() {
subscription = atom.tooltips.add(element, { class: "test-class" });
subscription = atom.tooltips.add(element, { placement: "top" });
subscription = atom.tooltips.add(element, { placement: () => "left" });
subscription = atom.tooltips.add(element, { placement: () => "auto left" });
subscription = atom.tooltips.add(element, { trigger: "click" });
subscription = atom.tooltips.add(element, { delay: { hide: 42, show: 42 }});
+45 -37
View File
@@ -717,7 +717,9 @@ export class Disposable implements DisposableLike {
* Utility class to be used when implementing event-based APIs that allows
* for handlers registered via ::on to be invoked with calls to ::emit.
*/
export class Emitter implements DisposableLike {
// tslint:disable-next-line:no-any
export class Emitter<OptionalEmissions = { [key: string]: any }, RequiredEmissions = {}>
implements DisposableLike {
/** Construct an emitter. */
constructor();
@@ -729,27 +731,47 @@ export class Emitter implements DisposableLike {
// Event Subscription
/** Registers a handler to be invoked whenever the given event is emitted. */
on<T extends keyof Emissions>(eventName: T, handler: (value?: Emissions[T]) => void):
Disposable;
on<T extends keyof OptionalEmissions>(eventName: T, handler: (value?:
OptionalEmissions[T]) => void): Disposable;
/** Registers a handler to be invoked whenever the given event is emitted. */
on<T extends keyof RequiredEmissions>(eventName: T, handler: (value:
RequiredEmissions[T]) => void): Disposable;
/**
* Register the given handler function to be invoked the next time an event
* with the given name is emitted via ::emit.
*/
once<T extends keyof Emissions>(eventName: T, handler: (value?: Emissions[T]) => void):
Disposable;
once<T extends keyof OptionalEmissions>(eventName: T, handler: (value?:
OptionalEmissions[T]) => void): Disposable;
/**
* Register the given handler function to be invoked the next time an event
* with the given name is emitted via ::emit.
*/
once<T extends keyof RequiredEmissions>(eventName: T, handler: (value:
RequiredEmissions[T]) => void): Disposable;
/**
* Register the given handler function to be invoked before all other
* handlers existing at the time of subscription whenever events by the
* given name are emitted via ::emit.
*/
preempt<T extends keyof Emissions>(eventName: T, handler: (value?: Emissions[T]) => void):
Disposable;
preempt<T extends keyof OptionalEmissions>(eventName: T, handler: (value?:
OptionalEmissions[T]) => void): Disposable;
/**
* Register the given handler function to be invoked before all other
* handlers existing at the time of subscription whenever events by the
* given name are emitted via ::emit.
*/
preempt<T extends keyof RequiredEmissions>(eventName: T, handler: (value:
RequiredEmissions[T]) => void): Disposable;
// Event Emission
/** Invoke the handlers registered via ::on for the given event name. */
emit<T extends keyof Emissions>(eventName: T, value?: Emissions[T]): void;
emit<T extends keyof OptionalEmissions>(eventName: T, value?:
OptionalEmissions[T]): void;
/** Invoke the handlers registered via ::on for the given event name. */
emit<T extends keyof RequiredEmissions>(eventName: T, value:
RequiredEmissions[T]): void;
}
/**
@@ -1015,10 +1037,7 @@ export class Point {
* Create a Point from an array containing two numbers representing the
* row and column.
*/
static fromObject(object: [number, number]): Point;
/** Create a Point from an existing object which implements PointLike. */
static fromObject(object: PointLike, copy?: boolean): Point;
static fromObject(object: PointCompatible, copy?: boolean): Point;
/** Construct a Point object */
constructor(row?: number, column?: number);
@@ -1775,7 +1794,8 @@ export class TextEditor {
void;
/** Add a cursor at the given position in buffer coordinates. */
addCursorAtBufferPosition(bufferPosition: PointCompatible): Cursor;
addCursorAtBufferPosition(bufferPosition: PointCompatible, options?:
{ autoscroll?: boolean }): Cursor;
/** Add a cursor at the position in screen coordinates. */
addCursorAtScreenPosition(screenPosition: PointCompatible): Cursor;
@@ -2403,27 +2423,25 @@ export interface TextEditorRegistry {
observe(callback: (editor: TextEditor) => void): Disposable;
}
export type TooltipPlacement =
|"top"|"bottom"|"left"|"right"
|"auto"|"auto top"|"auto bottom"|"auto left"|"auto right";
/** Associates tooltips with HTML elements or selectors. */
export interface TooltipManager {
/** Add a tooltip to the given element. */
add(target: HTMLElement, options: {
title?: string,
html?: boolean,
item?: HTMLElement|{ element: HTMLElement },
class?: string,
placement?: "top"|"bottom"|"left"|"right"|"auto"|(() => string),
trigger?: "click"|"hover"|"focus"|"manual",
delay?: { show: number, hide: number },
keyBindingCommand?: string,
keyBindingTarget?: HTMLElement
item?: object,
} | {
title?: string|(() => string),
html?: boolean,
item?: HTMLElement|{ element: HTMLElement },
class?: string,
placement?: "top"|"bottom"|"left"|"right"|"auto"|(() => string),
keyBindingCommand?: string,
keyBindingTarget?: HTMLElement
} & {
class?: string;
placement?: TooltipPlacement|(() => TooltipPlacement),
trigger?: "click"|"hover"|"focus"|"manual",
delay?: { show: number, hide: number },
delay?: { show: number, hide: number }
}): Disposable;
/** Find the tooltips that have been applied to the given element. */
@@ -5795,16 +5813,6 @@ export interface ConfigValues {
[key: string]: any;
}
/**
* Allows you to strongly type event emissions across your codebase. Additional
* key:value pairings merged into this interface will result in emissions under
* the value of each key being templated by the type of the associated value.
*/
export interface Emissions {
// tslint:disable-next-line:no-any
[key: string]: any;
}
// Options ====================================================================
// The option objects that the user is expected to fill out and provide to
// specific API call.
@@ -6094,7 +6102,7 @@ export interface SharedDecorationOptions {
* An HTMLElement or a model Object with a corresponding view registered. Only
* applicable to the gutter, overlay and block types.
*/
item?: HTMLElement;
item?: object;
/**
* If true, the decoration will only be applied to the head of the DisplayMarker.
+20 -1
View File
@@ -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
});
@@ -172,6 +174,23 @@ webAuth.login({username: 'bar', password: 'foo'}, (err, data) => {});
webAuth.crossOriginAuthenticationCallback();
webAuth.checkSession({
audience: 'https://mystore.com/api/v2',
scope: 'read:order write:order',
redirectUri: 'https://example.com/auth/silent-callback'
}, (err, authResult) => {
// Authentication tokens or error
});
webAuth.checkSession({
audience: 'https://mystore.com/api/v2',
scope: 'read:order write:order',
redirectUri: 'https://example.com/auth/silent-callback',
usePostMessage: true
}, (err, authResult) => {
// Renewed tokens or error
});
const authentication = new auth0.Authentication({
domain: 'me.auth0.com',
clientID: '...',
+78 -2
View File
@@ -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 <https://github.com/adrianchia>
// Matt Durrant <https://github.com/mdurrant>
// Peter Blazejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export as namespace auth0;
@@ -267,6 +268,14 @@ export class WebAuth {
* @param options:
*/
passwordlessVerify(options: PasswordlessVerifyOptions, callback: Auth0Callback<any>): void;
/**
* Renews an existing session on Auth0's servers using `response_mode=web_message` (i.e. Auth0's hosted login page)
*
* @param options options used in {@link authorize} call
* @param callback: any(err, token_payload)
*/
checkSession(options: CheckSessionOptions, callback: Auth0Callback<any>): void;
}
export class Redirect {
@@ -525,14 +534,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 +681,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 {
@@ -692,3 +761,10 @@ export interface AuthorizeOptions {
scope?: string;
audience?: string;
}
export interface CheckSessionOptions extends AuthorizeOptions {
/**
* optional parameter for auth0 to use postMessage to communicate between the silent callback and the SPA.
*/
usePostMessage?: boolean;
}
+13 -2
View File
@@ -10,6 +10,17 @@ lock.show();
lock.hide();
lock.logout(() => {});
lock.checkSession({}, function(error: auth0.Auth0Error, authResult: AuthResult): void {
if (error || !authResult) {
lock.show();
} else {
// user has an active session, so we can use the accessToken directly.
lock.getUserInfo(authResult.accessToken, function(error, profile) {
console.log(error, profile);
});
}
});
// Show supports UI arguments
const showOptions : Auth0LockShowOptions = {
@@ -37,7 +48,7 @@ lock.show(showOptions);
// "on" event-driven example
lock.on("authenticated", function(authResult : any) {
lock.on("authenticated", function(authResult: AuthResult) {
lock.getProfile(authResult.idToken, function(error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) {
if (error) {
// Handle error
@@ -49,7 +60,7 @@ lock.on("authenticated", function(authResult : any) {
});
});
lock.on("authenticated", function(authResult : any) {
lock.on("authenticated", function(authResult: AuthResult) {
lock.getUserInfo(authResult.accessToken, function(error, profile) {
if (error) {
// Handle error
+1
View File
@@ -154,6 +154,7 @@ interface Auth0LockStatic {
// deprecated
getProfile(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void;
getUserInfo(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void;
checkSession(options: any, callback: (error: auth0.Auth0Error, authResult: AuthResult | undefined) => void): void;
// https://github.com/auth0/lock#resumeauthhash-callback
resumeAuth(hash: string, callback: (error: auth0.Auth0Error, authResult: AuthResult) => void): void;
show(options?: Auth0LockShowOptions): void;
+9
View File
@@ -111,3 +111,12 @@ management
// Update app metadata using callback
management
.updateAppMetadata({id: "user_id"}, {"key": "value"}, (err: Error, users: auth0.User) => {});
management.getUsersByEmail('email@address.com', (err, users) => {
console.log(users);
});
management.getUsersByEmail('email@address.com').then((users) => {
console.log(users);
});
+3
View File
@@ -482,6 +482,9 @@ export class ManagementClient {
getUser(params: ObjectWithId): Promise<User>;
getUser(params: ObjectWithId, cb?: (err: Error, user: User) => void): void;
getUsersByEmail(email: string): Promise<User[]>;
getUsersByEmail(email: string, cb?: (err: Error, users: User[]) => void): void;
createUser(data: CreateUserData): Promise<User>;
createUser(data: CreateUserData, cb: (err: Error, user: User) => void): void;
@@ -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'
-10
View File
@@ -1,10 +0,0 @@
// Type definitions for autobind-decorator v1.3.3
// Project: https://github.com/andreypopp/autobind-decorator
// Definitions by: Ivo Stratev <https://github.com/NoHomey>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'autobind-decorator' {
function autobind<TFunction extends Function>(target: TFunction): TFunction | void;
function autobind<T extends Function>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T> | void;
export = autobind;
}
+223
View File
@@ -109,6 +109,101 @@ str = apiGwEvt.queryStringParameters["example"];
str = apiGwEvt.stageVariables["example"];
apiGwEvtReqCtx = apiGwEvt.requestContext;
/* DynamoDB Stream Event */
var dynamoDBStreamEvent: AWSLambda.DynamoDBStreamEvent = {
Records: [
{
eventID: '1',
eventVersion: '1.0',
dynamodb: {
Keys: {
Id: {
N: 101
}
},
NewImage: {
Message: {
S: 'New item!'
},
Id: {
N: 101
}
},
StreamViewType: 'NEW_AND_OLD_IMAGES',
SequenceNumber: '111',
SizeBytes: 26
},
awsRegion: 'us-west-2',
eventName: 'INSERT',
eventSourceARN:
'arn:aws:dynamodb:us-west-2:account-id:table/ExampleTableWithStream/stream/2015-06-27T00:48:05.899',
eventSource: 'aws:dynamodb'
},
{
eventID: '2',
eventVersion: '1.0',
dynamodb: {
OldImage: {
Message: {
S: 'New item!'
},
Id: {
N: 101
}
},
SequenceNumber: '222',
Keys: {
Id: {
N: 101
}
},
SizeBytes: 59,
NewImage: {
Message: {
S: 'This item has changed'
},
Id: {
N: 101
}
},
StreamViewType: 'NEW_AND_OLD_IMAGES'
},
awsRegion: 'us-west-2',
eventName: 'MODIFY',
eventSourceARN:
'arn:aws:dynamodb:us-west-2:account-id:table/ExampleTableWithStream/stream/2015-06-27T00:48:05.899',
eventSource: 'aws:dynamodb'
},
{
eventID: '3',
eventVersion: '1.0',
dynamodb: {
Keys: {
Id: {
N: 101
}
},
SizeBytes: 38,
SequenceNumber: '333',
OldImage: {
Message: {
S: 'This item has changed'
},
Id: {
N: 101
}
},
StreamViewType: 'NEW_AND_OLD_IMAGES'
},
awsRegion: 'us-west-2',
eventName: 'REMOVE',
eventSourceARN:
'arn:aws:dynamodb:us-west-2:account-id:table/ExampleTableWithStream/stream/2015-06-27T00:48:05.899',
eventSource: 'aws:dynamodb'
}
]
};
/* SNS Event */
snsEvtRecs = snsEvt.Records;
@@ -294,6 +389,9 @@ function callback(cb: AWSLambda.Callback) {
cb(null);
cb(error);
cb(null, anyObj);
cb(null, b);
cb(null, str);
cb(null, num);
}
/* Proxy Callback */
@@ -312,6 +410,131 @@ function customAuthorizerCallback(cb: AWSLambda.CustomAuthorizerCallback) {
cb(null, authResponse);
}
/* CloudFront events, see http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html */
var CloudFrontRequestEvent: AWSLambda.CloudFrontRequestEvent = {
"Records": [
{
"cf": {
"config": {
"distributionId": "EDFDVBD6EXAMPLE",
"requestId": "MRVMF7KydIvxMWfJIglgwHQwZsbG2IhRJ07sn9AkKUFSHS9EXAMPLE=="
},
"request": {
"clientIp": "2001:0db8:85a3:0:0:8a2e:0370:7334",
"method": "GET",
"uri": "/picture.jpg",
"querystring": "size=large",
"headers": {
"host": [
{
"key": "Host",
"value": "d111111abcdef8.cloudfront.net"
}
],
"user-agent": [
{
"key": "User-Agent",
"value": "curl/7.51.0"
}
]
},
"origin": {
"custom": {
"customHeaders": {
"my-origin-custom-header": [
{
"key": "My-Origin-Custom-Header",
"value": "Test"
}
]
},
"domainName": "example.com",
"keepaliveTimeout": 5,
"path": "/custom_path",
"port": 443,
"protocol": "https",
"readTimeout": 5,
"sslProtocols": [
"TLSv1",
"TLSv1.1"
]
},
"s3": {
"authMethod": "origin-access-identity",
"customHeaders": {
"my-origin-custom-header": [
{
"key": "My-Origin-Custom-Header",
"value": "Test"
}
]
},
"domainName": "my-bucket.s3.amazonaws.com",
"path": "/s3_path",
"region": "us-east-1"
}
}
}
}
}
]
};
var CloudFrontResponseEvent: AWSLambda.CloudFrontResponseEvent = {
"Records": [
{
"cf": {
"config": {
"distributionId": "EDFDVBD6EXAMPLE",
"requestId": "xGN7KWpVEmB9Dp7ctcVFQC4E-nrcOcEKS3QyAez--06dV7TEXAMPLE=="
},
"request": {
"clientIp": "2001:0db8:85a3:0:0:8a2e:0370:7334",
"method": "GET",
"uri": "/picture.jpg",
"querystring": "size=large",
"headers": {
"host": [
{
"key": "Host",
"value": "d111111abcdef8.cloudfront.net"
}
],
"user-agent": [
{
"key": "User-Agent",
"value": "curl/7.18.1"
}
]
}
},
"response": {
"status": "200",
"statusDescription": "OK",
"headers": {
"server": [
{
"key": "Server",
"value": "MyCustomOrigin"
}
],
"set-cookie": [
{
"key": "Set-Cookie",
"value": "theme=light"
},
{
"key": "Set-Cookie",
"value": "sessionToken=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT"
}
]
}
}
}
}
]
};
/* Compatibility functions */
context.done();
context.done(error);
+100 -1
View File
@@ -8,7 +8,10 @@
// Yoriki Yamaguchi <https://github.com/y13i>
// wwwy3y3 <https://github.com/wwwy3y3>
// Ishaan Malhi <https://github.com/OrthoDex>
// Michael Marner <https://github.com/MichaelMarner>
// Daniel Cottone <https://github.com/daniel-cottone>
// Kostya Misura <https://github.com/kostya-misura>
// Markus Tacker <https://github.com/coderbyheart>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -63,6 +66,53 @@ interface CustomAuthorizerEvent {
requestContext?: APIGatewayEventRequestContext;
}
// Context
// http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_AttributeValue.html
interface AttributeValue {
B?: string;
BS?: Array<string>;
BOOL?: boolean;
L?: Array<AttributeValue>;
M?: { [id: string]: AttributeValue };
N?: number;
NS?: Array<string>;
NULL?: boolean;
S?: string;
SS?: Array<string>;
}
// Context
// http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_StreamRecord.html
interface StreamRecord {
ApproximateCreationTime?: number;
Keys?: { [key: string]: AttributeValue };
NewImage?: { [key: string]: AttributeValue };
OldImage?: { [key: string]: AttributeValue };
SequenceNumber?: string;
SizeBytes?: number;
StreamViewType?: 'KEYS_ONLY' | 'NEW_IMAGE' | 'OLD_IMAGE' | 'NEW_AND_OLD_IMAGES';
}
// Context
// http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_Record.html
interface DynamoDBRecord {
awsRegion?: string;
dynamodb?: StreamRecord;
eventID?: string;
eventName?: 'INSERT' | 'MODIFY' | 'REMOVE';
eventSource?: string;
eventSourceARN?: string;
eventVersion?: string;
userIdentity?: any;
}
// AWS Lambda Stream event
// Context
// http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-ddb-update
interface DynamoDBStreamEvent {
Records: Array<DynamoDBRecord>;
}
// SNS "event"
interface SNSMessageAttribute {
Type: string;
@@ -345,6 +395,55 @@ interface AuthResponseContext {
[name: string]: string | number | boolean;
}
/**
* CloudFront events
* http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html
*/
type CloudFrontHeaders = {
[name: string]: {
key: string;
value: string;
}[]
};
type CloudFrontResponse = {
status: string;
statusDescription: string;
headers: CloudFrontHeaders;
};
type CloudFrontRequest = {
clientIp: string;
method: string;
uri: string;
querystring: string;
headers: CloudFrontHeaders;
};
type CloudFrontEvent = {
config: {
distributionId: string;
requestId: string;
}
}
export type CloudFrontResponseEvent = {
Records: {
cf: CloudFrontEvent & {
request: CloudFrontRequest;
response: CloudFrontResponse;
}
}[]
};
export type CloudFrontRequestEvent = {
Records: {
cf: CloudFrontEvent & {
request: CloudFrontRequest;
}
}[]
};
/**
* AWS Lambda handler function.
* http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
@@ -364,7 +463,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;
+79 -13
View File
@@ -1,16 +1,82 @@
import { Azure } from 'azure-sb';
import AzureSB = require('azure-sb');
import Models = Azure.ServiceBus.Results.Models;
var nh = new Azure.ServiceBus.NotificationHubService();
nh.send('tag', '<payload></payload>', function (error, result) {});
nh.send('tag', '<payload></payload>', { headers: {} }, function (error, result) {});
function createResultCallback<T>() {
return (err: Error | null, result: T, response: Azure.ServiceBus.Response) => {
};
}
nh.apns.send('tag', { payload: { } }, function (error, result) {});
nh.apns.send(['tag'], { payload: { } }, function (error, result) {});
nh.gcm.send('tag', { }, function (error, result) {});
nh.gcm.send(['tag'], { }, function (error, result) {});
nh.wns.send('tag', '<payload></payload>', 'wns/toast', function (error, result) {});
nh.wns.send(['tag'], '<payload></payload>', 'wns/toast', function (error, result) {});
nh.wns.send('tag', '<payload></payload>', 'wns/toast', { headers: {} }, function (error, result) {});
nh.wns.sendToastText01('tag', '<payload></payload>', function (error, result) {});
nh.wns.sendToastText01(['tag'], '<payload></payload>', function (error, result) {});
nh.wns.sendToastText01('tag', '<payload></payload>', { headers: {} }, function (error, result) {});
function ResponseCallback(err: Error | null, response: Azure.ServiceBus.Response) {
}
const ServiceBus = AzureSB.createServiceBusService('connectionstring');
// Queues
ServiceBus.listQueues('', createResultCallback<Models.Queue[]>());
ServiceBus.createQueue('test', createResultCallback<Models.Queue>());
ServiceBus.createQueueIfNotExists('test', createResultCallback<boolean>());
ServiceBus.getQueue('test', createResultCallback<Models.Queue>());
ServiceBus.deleteQueue('test', ResponseCallback);
// Topics
ServiceBus.listTopics('', createResultCallback<Models.Topic[]>());
ServiceBus.createTopic('test', createResultCallback<Models.Topic>());
ServiceBus.createTopicIfNotExists('test', createResultCallback<boolean>());
ServiceBus.getTopic('test', createResultCallback<Models.Topic>());
ServiceBus.deleteTopic('test', ResponseCallback);
// Subscriptions
ServiceBus.listSubscriptions('test', createResultCallback<Models.Subscription[]>());
ServiceBus.createSubscription('test', 'test', createResultCallback<Models.Subscription>());
ServiceBus.createSubscription('test', 'test', {
DefaultMessageTimeToLive: 'PT10M'
}, createResultCallback<Models.Subscription>());
ServiceBus.getSubscription('test', 'test', createResultCallback<Models.Subscription>());
ServiceBus.deleteSubscription('test', 'test', ResponseCallback);
ServiceBus.listRules('testTopic', 'testSub', createResultCallback<Models.Rule[]>());
ServiceBus.createRule('testTopic', 'testSub', 'testRule', createResultCallback<Models.Rule>());
ServiceBus.getRule('testTopic', 'testSub', 'testRule', createResultCallback<Models.Rule>());
ServiceBus.deleteRule('testTopic', 'testSub', 'testRule', ResponseCallback);
// Messages
ServiceBus.sendQueueMessage('testTopic', 'My data', ResponseCallback);
ServiceBus.sendQueueMessage('testTopic', {
body: '{"data":"MyData"}',
contentType: 'application/json',
brokerProperties: {
CorrelationId: '123'
}
}, ResponseCallback);
ServiceBus.receiveQueueMessage('testQueue', createResultCallback<Azure.ServiceBus.Message>());
ServiceBus.sendTopicMessage('testTopic', 'My data', ResponseCallback);
ServiceBus.sendTopicMessage('testTopic', {
body: '{"data":"MyData"}',
contentType: 'application/json',
brokerProperties: {
CorrelationId: '123'
}
}, ResponseCallback);
ServiceBus.receiveSubscriptionMessage('testTopic', 'testSub', createResultCallback<Azure.ServiceBus.Message>());
ServiceBus.renewLockForMessage('test', ResponseCallback);
ServiceBus.unlockMessage('test', ResponseCallback);
ServiceBus.deleteMessage('test', ResponseCallback);
// NotificationHub
const nh = AzureSB.createNotificationHubService('test');
nh.send('tag', '<payload></payload>', ResponseCallback);
nh.send('tag', '<payload></payload>', { headers: {} }, ResponseCallback);
nh.apns.send('tag', { payload: {} }, ResponseCallback);
nh.apns.send(['tag'], { payload: {} }, ResponseCallback);
nh.gcm.send('tag', {}, ResponseCallback);
nh.gcm.send(['tag'], {}, ResponseCallback);
nh.wns.send('tag', '<payload></payload>', 'wns/toast', ResponseCallback);
nh.wns.send(['tag'], '<payload></payload>', 'wns/toast', ResponseCallback);
nh.wns.send('tag', '<payload></payload>', 'wns/toast', { headers: {} }, ResponseCallback);
nh.wns.sendToastText01('tag', '<payload></payload>', ResponseCallback);
nh.wns.sendToastText01(['tag'], '<payload></payload>', ResponseCallback);
nh.wns.sendToastText01('tag', '<payload></payload>', { headers: {} }, ResponseCallback);
+299 -149
View File
@@ -2,172 +2,322 @@
// Project: https://github.com/Azure/azure-sdk-for-node/tree/master/lib/services/serviceBus
// Definitions by: Microsoft Azure <https://github.com/Azure>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
declare namespace Azure.ServiceBus {
interface Callback {
(error: any, response: any): void;
export import ServiceBusService = require('./lib/servicebusservice');
export import NotificationHubService = require('./lib/notificationhubservice');
export import WrapService = require('./lib/wrapservice');
export function createServiceBusService(namespaceOrConnectionString?: string,
accessKey?: string,
issuer?: string,
acsNamespace?: string,
host?: string,
authenticationProvider?: object): ServiceBusService;
export function createNotificationHubService(hubName: string,
endpointOrConnectionString?: string,
sharedAccessKeyName?: string,
sharedAccessKeyValue?: string): NotificationHubService;
export function createWrapService(acsHost: string,
issuer?: string,
accessKey?: string): WrapService;
export namespace Azure.ServiceBus {
export type Duration = string;
export type DateString = string;
export interface Dictionary<T> {
[k: string]: T;
}
interface NotificationHubRegistration {
RegistrationId: string;
export interface ReceiveQueueMessageOptions {
timeoutIntervalInS?: number;
}
export interface ReceiveSubscriptionMessageOptions extends ReceiveQueueMessageOptions {
isPeekLock?: boolean;
}
interface IBrokerPropertiesResponse {
readonly DeliveryCount: number;
readonly LockedUntil: DateString;
readonly LockToken: string;
readonly SequenceNumber: number;
}
interface IBrokerProperties {
CorrelationId: string;
Label: string;
MessageId: string;
PartitionKey: string;
ReplyTo: string;
ReplyToSessionId: string;
ScheduledEnqueueTimeUtc: string;
SessionId: string;
TimeToLive: string;
To: string;
}
export interface Message {
body: string;
brokerProperties?: BrokerProperties;
contentType?: string;
customProperties?: Dictionary<any>;
}
/*
* Options interfaces
*/
interface CreateOptions {
DefaultMessageTimeToLive: string;
DuplicateDetectionHistoryTimeWindow: string;
EnablePartitioning: boolean;
MaxSizeInMegaBytes: number;
RequiresDuplicateDetection: boolean;
}
interface IQueueOptions extends CreateOptions {
AutoDeleteOnIdle: string;
DeadLetteringOnMessageExpiration: boolean;
LockDuration: string;
RequiresSession: boolean;
}
interface ICreateTopicOptions extends CreateOptions {
EnableBatchedOperations: boolean;
SizeInBytes: boolean;
SupportOrdering: boolean;
}
interface ICreateTopicIfNotExistsOptions extends ICreateTopicOptions {
EnableDeadLetteringOnFilterEvaluationExceptions: boolean;
EnableDeadLetteringOnMessageExpiration: boolean;
MaxCorrelationFiltersPerTopic: number;
MaxSqlFiltersPerTopic: number;
MaxSubscriptionsPerTopic: number;
}
interface ICreateSubscriptionOptions {
DefaultMessageTimeToLive: string;
EnableDeadLetteringOnFilterEvaluationExceptions: boolean;
EnableDeadLetteringOnMessageExpiration: boolean;
LockDuration: string;
RequiresSession: boolean;
}
interface PaginationOptions {
top: number;
skip: number;
}
interface ICreateRuleOptions {
trueFilter: string;
falseFilter: string;
sqlExpressionFilter: string;
correlationIdFilter: string;
sqlRuleAction: string;
}
interface ICreateNotificationHubOptions {
apns: Dictionary<string>;
gcm: Dictionary<string>;
mpns: Dictionary<string>;
wns: Dictionary<string>;
}
export interface NotificationHubRegistration {
BodyTemplate?: any;
ChannelUri?: string;
DeviceToken?: string;
gcmRegistrationId?: string;
Tags?: string;
BodyTemplate?: any;
WnsHeaders?: any;
MpnsHeaders?: any;
Expiry?: Date;
gcmRegistrationId?: string;
MpnsHeaders?: any;
RegistrationId: string;
Tags?: string;
WnsHeaders?: any;
}
export class NotificationHubService {
new(hubName: string, endpointOrConnectionString: string, sharedAccessKeyName?: string, sharedAccessKeyValue?: string): NotificationHubService;
hubName: string;
wns: Wns.Service;
apns: Apns.Service;
gcm: Gcm.Service;
mpns: Mpns.Service;
send(tags: string, payload: Object | string, optionsOrCallback?: { headers: Object } | Callback, callback?: Callback): void;
createOrUpdateInstallation(installation: string, options: any, callback?: Callback): void;
patchInstallation(installationId: string, partialUpdateOperations: any[], options: any, callback?: Callback): void;
deleteInstallation(installationId: string, options: any, callback?: Callback): void;
getInstallation(installationId: string, options: any, callback?: Callback): void;
/*
// old school?
createRegistrationId(callback?: Callback): void;
getRegistration(registrationId: string, options: any, callback?: Callback): void;
deleteRegistration(registrationId: string, options?: { etag: any }, callback?: Callback): void;
updateRegistration(registration: NotificationHubRegistration, options?: { etag: any }, callback?: Callback): void;
createOrUpdateRegistration(registration: NotificationHubRegistration, options?: { etag: any }, callback?: Callback): void;
listRegistrations(options?: { top: number, skip: number }, callback?: Callback): void;
listRegistrationsByTag(tag: string, options?: { top: number, skip: number }, callback?: Callback): void;
*/
export interface Response {
body: Dictionary<string | object>;
headers: Dictionary<string>;
isSuccessful: boolean;
md5?: string;
statusCode: number;
}
export module Apns {
interface Payload {
expiry?: Date;
aps?: Object;
badge?: number;
alert?: string;
sound?: string;
payload: Object;
export interface ErrorResponse extends Response {
body: {
Error: {
Code: string;
Detail: string;
};
};
}
export namespace Results.Models {
export enum EntityStatus {
Active = 'Active',
Creating = 'Creating',
Deleting = 'Deleting',
Disabled = 'Disabled',
ReceiveDisabled = 'ReceiveDisabled',
Renaming = 'Renaming',
Restoring = 'Restoring',
SendDisabled = 'SendDisabled',
Unknown = 'Unknown'
}
interface Service {
new(service: NotificationHubService): Service;
send(tags: string | string[], payload: Apns.Payload, callback?: Callback): void;
createNativeRegistration(token: string, tags: string | string[], optionsOrCallback?: Object | Callback, callback?: Callback): void;
createOrUpdateNativeRegistration(registrationId: string, token: string, tags: string | string[], optionsOrCallback?: Object | Callback, callback?: Callback): void;
createTemplateRegistration(token: string, tags: string | string[], template: Apns.Payload, optionsOrCallback?: Object | Callback, callback?: Callback): void;
createOrUpdateTemplateRegistration(registrationId: string, token: string, tags: string | string[], template: Apns.Payload, optionsOrCallback?: Object | Callback, callback?: Callback): void;
updateTemplateRegistration(registrationId: string, token: string, tags: string | string[], template: Apns.Payload, optionsOrCallback?: Object | Callback, callback?: Callback): void;
listRegistrationsByToken(token: string, optionsOrCallback?: { top: number, skip: number } | Callback, callback?: Callback): void;
export enum EntityAvailabilityStatus {
Available = 'Available',
Limited = 'Limited',
Renaming = 'Renaming',
Restoring = 'Restoring',
Unknown = 'Unknown'
}
}
export module Gcm {
interface Service {
new(service: NotificationHubService): Service;
send(tags: string | string[], payload: any, callback?: Callback): void;
createNativeRegistration(gcmRegistrationId: string, tags: string | string[], optionsOrCallback?: Object | Callback, callback?: Callback): void;
createOrUpdateNativeRegistration(registrationId: string, gcmRegistrationId: string, tags: string | string[], optionsOrCallback?: Object | Callback, callback?: Callback): void;
createTemplateRegistration(gcmRegistrationId: string, tags: string | string[], template: any, optionsOrCallback?: Object | Callback, callback?: Callback): void;
createOrUpdateTemplateRegistration(registrationId: string, gcmRegistrationId: string, tags: string | string[], template: any, optionsOrCallback?: Object | Callback, callback?: Callback): void;
updateTemplateRegistration(registrationId: string, gcmRegistrationId: string, tags: string | string[], template: any, optionsOrCallback?: Object | Callback, callback?: Callback): void;
listRegistrationsByGcmRegistrationId(gcmRegistrationId: string, optionsOrCallback?: { top: number, skip: number } | Callback, callback?: Callback): void;
interface Base {
_: {
ContentRootElement: string;
id: string;
title: string;
published: DateString;
updated: DateString;
author?: {
name: string;
};
link: string;
};
CreatedAt: DateString;
}
interface ExtendedBase extends Base {
AuthorizationRules: string;
AutoDeleteOnIdle: string;
DefaultMessageTimeToLive: string;
DuplicateDetectionHistoryTimeWindow: Duration;
EnableBatchedOperations: string;
EnableExpress: string;
EnablePartitioning: string;
EntityAvailabilityStatus: string;
IsAnonymousAccessible: string;
MaxSizeInMegabytes: string;
RequiresDuplicateDetection: string;
SizeInBytes: string;
Status: EntityStatus;
UpdatedAt: DateString;
}
// export interface Generic extends Base {
// [x: string]: string | Dictionary<string | object>;
// }
export interface Topic extends ExtendedBase {
AccessedAt: DateString;
CountDetails: {
'd2p1:ActiveMessageCount': string;
'd2p1:DeadLetterMessageCount': string;
'd2p1:ScheduledMessageCount': string;
'd2p1:TransferMessageCount': string;
'd2p1:TransferDeadLetterMessageCount': string;
};
EnableSubscriptionPartitioning: string;
FilteringMessagesBeforePublishing: string;
IsExpress: string;
SubscriptionCount: string;
SupportOrdering: string;
TopicName: string;
}
export interface Queue extends ExtendedBase {
DeadLetteringOnMessageExpiration: string;
LockDuration: Duration;
MaxDeliveryCount: string;
MessageCount: string;
QueueName: string;
RequiresSession: string;
SupportOrdering: string;
}
export interface Subscription extends ExtendedBase {
CountDetails: {
'd3p1:ActiveMessageCount': string;
'd3p1:DeadLetterMessageCount': string;
'd3p1:ScheduledMessageCount': string;
'd3p1:TransferMessageCount': string;
'd3p1:TransferDeadLetterMessageCount': string;
};
DeadLetteringOnFilterEvaluationExceptions: string;
DeadLetteringOnMessageExpiration: string;
LockDuration: string;
MaxDeliveryCount: string;
MessageCount: string;
RequiresSession: string;
SubscriptionName: string;
TopicName: string;
}
/**
* @see https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-messaging-sql-filter
*/
interface SqlFilter {
readonly CompatibilityLevel: string;
Parameters?: Dictionary<any>;
RequiresPreprocessing?: string;
SqlExpression: string;
}
type CorrelationFilter = Partial<{
ContentType: string;
CorrelationId: string;
Label: string;
Properties: string;
ReplyTo: string;
ReplyToSessionId: string;
RequiresPreprocessing: string;
SessionId: string;
To: string;
}>;
export interface Rule extends Base {
Action: string | SqlFilter;
Filter: SqlFilter | CorrelationFilter;
Name: string;
TopicName: string;
SubscriptionName: string;
RuleName: string;
}
}
export module Mpns { interface Service { } }
/*
* Callbacks
*/
export type ResponseCallback = (error: Error | null, response: Response) => void;
export module Wns {
interface Payload {
text1?: string;
text2?: string;
text3?: string;
text4?: string;
image1src?: string;
image1alt?: string;
image2src?: string;
image2alt?: string;
image3src?: string;
image3alt?: string;
image4src?: string;
image4alt?: string;
lang?: string;
type?: string;
}
export type ResultAndResponseCallback = (error: Error | null,
result: boolean | Results.Models.Base | Results.Models.Base[],
response: Response) => void;
interface Options {
headers: Object;
}
export type TypedResultAndResponseCallback<T> = (error: Error | null,
result: T,
response: Response) => void;
interface Service {
new(service: NotificationHubService): Service;
sendTileSquareBlock(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquareText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquareText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquareText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquareText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText05(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText06(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText07(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText08(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText09(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText10(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText11(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquareImage(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquarePeekImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquarePeekImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquarePeekImageAndText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquarePeekImageAndText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideImage(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideImageCollection(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideBlockAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideBlockAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideSmallImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideSmallImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideSmallImageAndText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideSmallImageAndText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideSmallImageAndText05(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection05(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection06(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage05(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage06(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastImageAndText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastImageAndText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
// badges = ['none','activity','alert','available','away','busy','newMessage','paused','playing','unavailable','error', 'attention']
sendBadge(tags: string | string[], value: string | number, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendRaw(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
// types = ['wns/toast', 'wns/badge', 'wns/tile', 'wns/raw']
send(tags: string | string[], payload: string, type: string, optionsOrCallback?: Options | Callback, callback?: Callback): void;
createNativeRegistration(channel: string, tags: string | string[], optionsOrCallback?: Options | Callback, callback?: Callback): void;
createOrUpdateNativeRegistration(registrationId: string, channel: string, tags: string | string[], optionsOrCallback?: Options | Callback, callback?: Callback): void;
listRegistrationsByChannel(channel: string, optionsOrCallback?: { top: number, skip: number } | Callback, callback?: Callback): void;
}
}
/*
* Options interfaces with all properties as optional
*/
export type BrokerProperties = Partial<IBrokerProperties>;
export type BrokerPropertiesResponse = IBrokerPropertiesResponse & Partial<IBrokerProperties>;
export type CreateQueueOptions = Partial<IQueueOptions>;
export type CreateTopicOptions = Partial<ICreateTopicOptions>;
export type CreateTopicIfNotExistsOptions = Partial<ICreateTopicIfNotExistsOptions>;
export type CreateSubscriptionOptions = Partial<ICreateSubscriptionOptions>;
export type ListSubscriptionsOptions = Partial<PaginationOptions>;
export type ListRulesOptions = Partial<PaginationOptions>;
export type CreateRuleOptions = Partial<ICreateRuleOptions>;
export type CreateNotificationHubOptions = Partial<ICreateNotificationHubOptions>;
export type ListNotificationHubsOptions = Partial<PaginationOptions>;
export type MessageOrName = Message | string;
}
+83
View File
@@ -0,0 +1,83 @@
import { Azure } from '../index';
import NotificationHubService = require('azure-sb/lib/notificationhubservice');
import ResponseCallback = Azure.ServiceBus.ResponseCallback;
import NotificationHubRegistration = Azure.ServiceBus.NotificationHubRegistration;
import ListNotificationHubsOptions = Azure.ServiceBus.ListNotificationHubsOptions;
import Dictionary = Azure.ServiceBus.Dictionary;
type Template = Partial<{
expiry: Date;
aps: object;
badge: number;
alert: string;
sound: string;
payload: object;
}>;
declare class ApnsService {
constructor(notificationHubService: NotificationHubService);
public notificationHubService: NotificationHubService;
public send(tags: string | string[],
payload: object | string,
callback: ResponseCallback): void;
public send(tags: string | string[],
payload: object | string,
options: { headers: Dictionary<string> },
callback: ResponseCallback): void;
public createNativeRegistration(token: string,
tags: string | string[],
callback: ResponseCallback): void;
public createNativeRegistration(token: string,
tags: string | string[],
options: object,
callback: ResponseCallback): void;
public createOrUpdateNativeRegistration(registrationId: string,
token: string,
tags: string | string[],
callback: ResponseCallback): void;
public createOrUpdateNativeRegistration(registrationId: string,
token: string,
tags: string | string[],
options: object,
callback: ResponseCallback): void;
public createTemplateRegistration(token: string,
tags: string | string[],
template: Template | string,
callback: ResponseCallback): void;
public createTemplateRegistration(token: string,
tags: string | string[],
template: Template | string,
options: object,
callback: ResponseCallback): void;
public updateTemplateRegistration(registrationId: string,
token: string,
tags: string | string[],
template: Template | string,
callback: ResponseCallback): void;
public updateTemplateRegistration(registrationId: string,
token: string,
tags: string | string[],
template: Template | string,
options: { headers: Dictionary<string> },
callback: ResponseCallback): void;
public listRegistrationsByToken(token: string,
callback: ResponseCallback): void;
public listRegistrationsByToken(token: string,
options: ListNotificationHubsOptions,
callback: ResponseCallback): void;
}
export = ApnsService;
+71
View File
@@ -0,0 +1,71 @@
import { Azure } from '../index';
import NotificationHubService = require('azure-sb/lib/notificationhubservice');
import ResponseCallback = Azure.ServiceBus.ResponseCallback;
import NotificationHubRegistration = Azure.ServiceBus.NotificationHubRegistration;
import ListNotificationHubsOptions = Azure.ServiceBus.ListNotificationHubsOptions;
import Dictionary = Azure.ServiceBus.Dictionary;
type Template = Partial<{}>;
declare class GcmService {
constructor(notificationHubService: NotificationHubService);
public notificationHubService: NotificationHubService;
public send(tags: string | string[],
payload: object | string,
callback: ResponseCallback): void;
public createNativeRegistration(gcmRegistrationId: string,
tags: string | string[],
callback: ResponseCallback): void;
public createNativeRegistration(token: string,
tags: string | string[],
options: object,
callback: ResponseCallback): void;
public createOrUpdateNativeRegistration(registrationId: string,
gcmRegistrationId: string,
tags: string | string[],
callback: ResponseCallback): void;
public createOrUpdateNativeRegistration(registrationId: string,
gcmRegistrationId: string,
tags: string | string[],
options: object,
callback: ResponseCallback): void;
public createTemplateRegistration(gcmRegistrationId: string,
tags: string | string[],
template: Template | string,
callback: ResponseCallback): void;
public createTemplateRegistration(gcmRegistrationId: string,
tags: string | string[],
template: Template | string,
options: object,
callback: ResponseCallback): void;
public updateTemplateRegistration(registrationId: string,
gcmRegistrationId: string,
tags: string | string[],
template: Template | string,
callback: ResponseCallback): void;
public updateTemplateRegistration(registrationId: string,
gcmRegistrationId: string,
tags: string | string[],
template: Template | string,
options: { headers: Dictionary<string> },
callback: ResponseCallback): void;
public listRegistrationsByGcmRegistrationId(gcmRegistrationId: string,
callback: ResponseCallback): void;
public listRegistrationsByGcmRegistrationId(gcmRegistrationId: string,
options: ListNotificationHubsOptions,
callback: ResponseCallback): void;
}
export = GcmService;
+29
View File
@@ -0,0 +1,29 @@
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
import { Azure } from 'azure-sb';
import Dictionary = Azure.ServiceBus.Dictionary;
export namespace Azure.ServiceBus.Results {
export interface AcsTokenResponse extends Dictionary<string | Dictionary<string>> {
WrapAccessToken: Dictionary<string>;
WrapAccessTokenExpiresIn: Dictionary<string>;
}
export interface AcsTokenResult {
parse(acsTokenQueryString: string): AcsTokenResponse;
}
}
+26
View File
@@ -0,0 +1,26 @@
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
import { Azure } from 'azure-sb';
import Dictionary = Azure.ServiceBus.Dictionary;
export namespace Azure.ServiceBus.Results {
export interface NotificationHubResult {
serialize(resource: Azure.ServiceBus.CreateNotificationHubOptions): string;
parse(xml: object): object | object[];
}
}
+40
View File
@@ -0,0 +1,40 @@
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Module dependencies.
import { Azure } from 'azure-sb';
import Dictionary = Azure.ServiceBus.Dictionary;
export namespace Azure.ServiceBus.Results {
export interface QueueResponse {
body: any;
headers: Dictionary<string>
}
export interface QueueMessageResponse {
body: any;
brokerProperties?: Azure.ServiceBus.BrokerProperties;
customProperties?: Dictionary<any>;
contentType?: string;
location?: string;
}
export interface QueueMessageResult {
parse(responseObject: object): QueueMessageResponse;
isRFC1123(value: string | any): boolean;
}
}
+41
View File
@@ -0,0 +1,41 @@
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
import { Azure } from 'azure-sb';
import Dictionary = Azure.ServiceBus.Dictionary;
export namespace Azure.ServiceBus.Results {
export interface QueueProperties {
DeadLetteringOnMessageExpiration: string;
DefaultMessageTimeToLive: string;
DuplicateDetectionHistoryTimeWindow: string;
EnableBatchedOperations: boolean;
EnablePartitioning: boolean;
LockDuration: string;
MaxDeliveryCount: number;
MaxSizeInMegabytes: number;
MessageCount: number;
RequiresDuplicateDetection: boolean;
RequiresSession: boolean;
SizeInBytes: number;
}
export interface QueueResult {
serialize(resource: QueueProperties): string;
parse(xml: object): object | object[];
}
}
+26
View File
@@ -0,0 +1,26 @@
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
import { Azure } from 'azure-sb';
import Dictionary = Azure.ServiceBus.Dictionary;
export namespace Azure.ServiceBus.Results {
export interface RegistrationResult {
serialize(type: string, resource: object, properties: string[]): string;
parse(xml: object): object | object[];
}
}
+28
View File
@@ -0,0 +1,28 @@
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
import { Azure } from 'azure-sb';
import Dictionary = Azure.ServiceBus.Dictionary;
export namespace Azure.ServiceBus.Results {
export interface ResourceResult {
setName(entry: Dictionary<any> | { _: { id: string } }, nameProperty: string): void;
serialize(resourceName: string, resource: object, properties: string[]): string;
parse(resourceName: string, nameProperty: string, xml: object): object | object[];
}
}
+26
View File
@@ -0,0 +1,26 @@
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Module dependencies.
import { Azure } from 'azure-sb';
export namespace Azure.ServiceBus.Results {
export interface RuleResult {
serialize(rule: Azure.ServiceBus.CreateRuleOptions): string;
parse(xml: object): object | object[];
}
}
+37
View File
@@ -0,0 +1,37 @@
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
import { Azure } from 'azure-sb';
export namespace Azure.ServiceBus.Results {
export interface SubscriptionProperties {
LockDuration: string;
RequiresSession: boolean;
DefaultMessageTimeToLive: string;
DeadLetteringOnMessageExpiration: string;
DeadLetteringOnFilterEvaluationExceptions: string;
MessageCount: number;
MaxDeliveryCount: number;
EnableBatchedOperations: boolean;
AutoDeleteOnIdle: boolean;
}
export interface SubscriptionResult {
serialize(resource: SubscriptionProperties): string;
parse(xml: object): object | object[];
}
}
+32
View File
@@ -0,0 +1,32 @@
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
export namespace Azure.ServiceBus.Results {
export interface TopicProperties {
DefaultMessageTimeToLive: string;
MaxSizeInMegabytes: number;
RequiresDuplicateDetection: boolean;
DuplicateDetectionHistoryTimeWindow: string;
EnableBatchedOperations: boolean;
SizeInBytes: number;
SupportOrdering: boolean;
EnablePartitioning: boolean;
}
}
export function serialize(resource: Azure.ServiceBus.Results.TopicProperties): string;
export function parse(xml: object): object | object[];
+116
View File
@@ -0,0 +1,116 @@
import { Azure } from '../index';
import NotificationHubService = require('azure-sb/lib/notificationhubservice');
import ResponseCallback = Azure.ServiceBus.ResponseCallback;
import NotificationHubRegistration = Azure.ServiceBus.NotificationHubRegistration;
import ListNotificationHubsOptions = Azure.ServiceBus.ListNotificationHubsOptions;
import Dictionary = Azure.ServiceBus.Dictionary;
type Template = TileTemplate | FlipTileTemplate | ToastTemplate;
interface TileTemplate {
backgroundImage: string;
count: string;
title: string;
backBackgroundImage: string;
backTitle: string;
backContent: string;
id: string;
}
interface FlipTileTemplate extends TileTemplate {
smallBackgroundImage: string;
wideBackgroundImage: string;
wideBackContent: string;
wideBackBackgroundImage: string;
}
interface ToastTemplate {
text1: string;
text2: string;
param?: string;
}
declare class MpnsService {
constructor(notificationHubService: NotificationHubService);
public notificationHubService: NotificationHubService;
public send(tags: string | string[],
payload: object | string,
targetName: string,
notificationClass: string,
callback: ResponseCallback): void;
public send(tags: string | string[],
payload: object | string,
targetName: string,
notificationClass: string,
options: { headers: Dictionary<string> },
callback: ResponseCallback): void;
public createNativeRegistration(channel: string,
tags: string | string[],
callback: ResponseCallback): void;
public createNativeRegistration(channel: string,
tags: string | string[],
options: object,
callback: ResponseCallback): void;
public createOrUpdateNativeRegistration(registrationId: string,
channel: string,
tags: string | string[],
callback: ResponseCallback): void;
public createOrUpdateNativeRegistration(registrationId: string,
channel: string,
tags: string | string[],
options: object,
callback: ResponseCallback): void;
public createRawTemplateRegistration(channel: string,
tags: string | string[],
template: Template | string,
callback: ResponseCallback): void;
public createRawTemplateRegistration(channel: string,
tags: string | string[],
template: Template | string,
options: object,
callback: ResponseCallback): void;
public createOrUpdateRawTemplateRegistration(registrationId: string,
channel: string,
tags: string | string[],
template: Template | string,
callback: ResponseCallback): void;
public createOrUpdateRawTemplateRegistration(registrationId: string,
channel: string,
tags: string | string[],
template: Template | string,
options: object,
callback: ResponseCallback): void;
public updatesRawTemplateRegistration(registrationId: string,
channel: string,
tags: string | string[],
template: Template | string,
callback: ResponseCallback): void;
public updatesRawTemplateRegistration(registrationId: string,
channel: string,
tags: string | string[],
template: Template | string,
options: object,
callback: ResponseCallback): void;
public listRegistrationsByChannel(channel: string,
callback: ResponseCallback): void;
public listRegistrationsByChannel(channel: string,
options: ListNotificationHubsOptions,
callback: ResponseCallback): void;
}
export = MpnsService;
+102
View File
@@ -0,0 +1,102 @@
import { Azure } from 'azure-sb';
import Callback = Azure.ServiceBus.ResponseCallback;
import NotificationHubRegistration = Azure.ServiceBus.NotificationHubRegistration;
import ListNotificationHubsOptions = Azure.ServiceBus.ListNotificationHubsOptions;
import ApnsService = require('./apnsservice');
import GcmService = require('./gcmservice');
import MpnsService = require('./mpnservice');
import WnsService = require('./wnsservice');
declare class NotificationHubService {
constructor(hubName: string,
endpointOrConnectionString: string,
sharedAccessKeyName: string,
sharedAccessKeyValue: string);
public hubName: string;
public wns: WnsService;
public apns: ApnsService;
public gcm: GcmService;
public mpns: MpnsService;
public send(tags: string,
payload: object | string,
callback: Callback): void;
public send(tags: string,
payload: object | string,
options: { headers: object },
callback: Callback): void;
public createOrUpdateInstallation(installation: string,
callback: Callback): void;
public createOrUpdateInstallation(installation: string,
options: any,
callback: Callback): void;
public patchInstallation(installationId: string,
partialUpdateOperations: any[],
callback: Callback): void;
public patchInstallation(installationId: string,
partialUpdateOperations: any[],
options: any,
callback: Callback): void;
public deleteInstallation(installationId: string,
callback: Callback): void;
public deleteInstallation(installationId: string,
options: any,
callback: Callback): void;
public getInstallation(installationId: string,
callback: Callback): void;
public getInstallation(installationId: string,
options: any,
callback: Callback): void;
public createRegistrationId(callback: Callback): void;
public getRegistration(registrationId: string,
callback: Callback): void;
public getRegistration(registrationId: string,
options: any,
callback: Callback): void;
public deleteRegistration(registrationId: string,
callback: Callback): void;
public deleteRegistration(registrationId: string,
options: { etag: any },
callback: Callback): void;
public updateRegistration(registration: NotificationHubRegistration,
callback: Callback): void;
public updateRegistration(registration: NotificationHubRegistration,
options: { etag: any },
callback: Callback): void;
public createOrUpdateRegistration(registration: NotificationHubRegistration,
options: { etag: any },
callback: Callback): void;
public listRegistrations(callback: Callback): void;
public listRegistrations(options: ListNotificationHubsOptions,
callback: Callback): void;
public listRegistrationsByTag(tag: string,
callback: Callback): void;
public listRegistrationsByTag(tag: string,
options: ListNotificationHubsOptions,
callback: Callback): void;
}
export = NotificationHubService;
+206
View File
@@ -0,0 +1,206 @@
import { Azure } from '../index';
import ServiceBusServiceBase = require('./servicebusservicebase');
import CreateNotificationHubOptions = Azure.ServiceBus.CreateNotificationHubOptions;
import CreateQueueOptions = Azure.ServiceBus.CreateQueueOptions;
import CreateRuleOptions = Azure.ServiceBus.CreateRuleOptions;
import CreateSubscriptionOptions = Azure.ServiceBus.CreateSubscriptionOptions;
import CreateTopicIfNotExistsOptions = Azure.ServiceBus.CreateTopicIfNotExistsOptions;
import CreateTopicOptions = Azure.ServiceBus.CreateTopicOptions;
import ListNotificationHubsOptions = Azure.ServiceBus.ListNotificationHubsOptions;
import ListRulesOptions = Azure.ServiceBus.ListRulesOptions;
import ListSubscriptionsOptions = Azure.ServiceBus.ListSubscriptionsOptions;
import MessageOrName = Azure.ServiceBus.MessageOrName;
import Queue = Azure.ServiceBus.Results.Models.Queue;
import ReceiveQueueMessageOptions = Azure.ServiceBus.ReceiveQueueMessageOptions;
import ReceiveSubscriptionMessageOptions = Azure.ServiceBus.ReceiveSubscriptionMessageOptions;
import ResponseCallback = Azure.ServiceBus.ResponseCallback;
import ResultAndResponseCallback = Azure.ServiceBus.ResultAndResponseCallback;
import Rule = Azure.ServiceBus.Results.Models.Rule;
import Subscription = Azure.ServiceBus.Results.Models.Subscription;
import Topic = Azure.ServiceBus.Results.Models.Topic;
import TypedResultAndResponseCallback = Azure.ServiceBus.TypedResultAndResponseCallback;
import Message = Azure.ServiceBus.Message;
declare class ServiceBusService extends ServiceBusServiceBase {
constructor(configOrNamespaceOrConnectionString?: string,
accessKey?: string,
issuer?: string,
acsNamespace?: string,
host?: string,
authenticationProvider?: object);
public receiveQueueMessage(queuePath: string,
callback: TypedResultAndResponseCallback<Message>): void;
public receiveQueueMessage(queuePath: string,
options: ReceiveQueueMessageOptions,
callback: TypedResultAndResponseCallback<Message>): void;
public receiveSubscriptionMessage(topicPath: string,
subscriptionPath: string,
callback: TypedResultAndResponseCallback<Message>): void;
public receiveSubscriptionMessage(topicPath: string,
subscriptionPath: string,
options: ReceiveSubscriptionMessageOptions,
callback: TypedResultAndResponseCallback<Message>): void;
public deleteMessage(message: MessageOrName,
callback: ResponseCallback): void;
public unlockMessage(message: MessageOrName,
callback: ResponseCallback): void;
public renewLockForMessage(message: MessageOrName,
callback: ResponseCallback): void;
public sendQueueMessage(queuePath: string,
message: MessageOrName,
callback: ResponseCallback): void;
public sendTopicMessage(topicPath: string,
message: MessageOrName,
callback: ResponseCallback): void;
/*
* Queue Management functions
*/
public createQueue(queuePath: string,
callback: TypedResultAndResponseCallback<Queue>): void;
public createQueue(queuePath: string,
options: CreateQueueOptions,
callback: TypedResultAndResponseCallback<Queue>): void;
public createQueueIfNotExists(queuePath: string,
callback: TypedResultAndResponseCallback<boolean>): void;
public createQueueIfNotExists(queuePath: string,
options: CreateQueueOptions,
callback: TypedResultAndResponseCallback<boolean>): void;
public deleteQueue(queuePath: string,
callback: ResponseCallback): void;
public getQueue(queuePath: string,
callback: TypedResultAndResponseCallback<Queue>): void;
public listQueues(queuePath: string,
callback: TypedResultAndResponseCallback<Queue[]>): void;
/*
* Topic Management functions
*/
public createTopic(topicPath: string,
callback: TypedResultAndResponseCallback<Topic>): void;
public createTopic(topicPath: string,
options: CreateTopicOptions,
callback: TypedResultAndResponseCallback<Topic>): void;
public createTopicIfNotExists(topicPath: string,
callback: TypedResultAndResponseCallback<boolean>): void;
public createTopicIfNotExists(topicPath: string,
options: CreateTopicIfNotExistsOptions,
callback: TypedResultAndResponseCallback<boolean>): void;
public deleteTopic(topicPath: string,
callback: ResponseCallback): void;
public getTopic(topicPath: string,
callback: TypedResultAndResponseCallback<Topic>): void;
public listTopics(topicPath: string,
callback: TypedResultAndResponseCallback<Topic[]>): void;
/*
* Subscription functions
*/
public createSubscription(topicPath: string,
subscriptionPath: string,
callback: TypedResultAndResponseCallback<Subscription>): void;
public createSubscription(topicPath: string,
subscriptionPath: string,
options: CreateSubscriptionOptions,
callback: TypedResultAndResponseCallback<Subscription>): void;
public deleteSubscription(topicPath: string,
subscriptionPath: string,
callback: ResponseCallback): void;
public getSubscription(topicPath: string,
subscriptionPath: string,
callback: TypedResultAndResponseCallback<Subscription>): void;
public listSubscriptions(topicPath: string,
callback: TypedResultAndResponseCallback<Subscription[]>): void;
public listSubscriptions(topicPath: string,
options: ListSubscriptionsOptions,
callback: TypedResultAndResponseCallback<Subscription[]>): void;
/*
* Rule functions
*/
public createRule(topicPath: string,
subscriptionPath: string,
rulePath: string,
callback: TypedResultAndResponseCallback<Rule>): void;
public createRule(topicPath: string,
subscriptionPath: string,
rulePath: string,
options: CreateRuleOptions,
callback: TypedResultAndResponseCallback<Rule>): void;
public deleteRule(topicPath: string,
subscriptionPath: string,
rulePath: string,
callback: ResponseCallback): void;
public getRule(topicPath: string,
subscriptionPath: string,
rulePath: string,
callback: TypedResultAndResponseCallback<Rule>): void;
public listRules(topicPath: string,
subscriptionPath: string,
callback: TypedResultAndResponseCallback<Rule[]>): void;
public listRules(topicPath: string,
subscriptionPath: string,
options: ListRulesOptions,
callback: TypedResultAndResponseCallback<Rule[]>): void;
/*
* NotificationHub functions
*/
public createNotificationHub(hubPath: string,
callback: ResultAndResponseCallback): void;
public createNotificationHub(hubPath: string,
options: CreateNotificationHubOptions,
callback: ResultAndResponseCallback): void;
public getNotificationHub(hubPath: string,
callback: ResultAndResponseCallback): void;
public listNotificationHubs(callback: ResultAndResponseCallback): void;
public listNotificationHubs(options: ListNotificationHubsOptions,
callback: ResultAndResponseCallback): void;
public deleteNotificationHub(hubPath: string,
callback: ResponseCallback): void;
}
export = ServiceBusService;
+12
View File
@@ -0,0 +1,12 @@
import ServiceBusServiceClient = require('azure-sb/lib/servicebusserviceclient');
declare class ServiceBusServiceBase extends ServiceBusServiceClient {
constructor(configOrNamespaceOrConnectionString: string,
accessKey?: string,
issuer?: string,
acsNamespace?: string,
host?: string,
authenticationProvider?: object);
}
export = ServiceBusServiceBase;
+14
View File
@@ -0,0 +1,14 @@
/// <reference types="node" />
import EventEmitter = NodeJS.EventEmitter;
declare class ServiceBusServiceClient extends EventEmitter {
constructor(accessKey?: string,
issuer?: string,
sharedAccessKeyName?: string,
sharedAccessKeyValue?: string,
host?: string,
acsHost?: string,
authenticationProvider?: object);
}
export = ServiceBusServiceClient;
+377
View File
@@ -0,0 +1,377 @@
import NotificationHubService = require('azure-sb/lib/notificationhubservice');
import Callback = Azure.ServiceBus.ResponseCallback;
import { Azure } from 'azure-sb';
import ListNotificationHubsOptions = Azure.ServiceBus.ListNotificationHubsOptions;
import Dictionary = Azure.ServiceBus.Dictionary;
type Payload = Partial<{
text1: string;
text2: string;
text3: string;
text4: string;
image1src: string;
image1alt: string;
image2src: string;
image2alt: string;
image3src: string;
image3alt: string;
image4src: string;
image4alt: string;
lang: string;
type: string;
}>;
interface Options {
headers: Dictionary<string>;
}
type badges =
'none'
| 'activity'
| 'alert'
| 'available'
| 'away'
| 'busy'
| 'newMessage'
| 'paused'
| 'playing'
| 'unavailable'
| 'error'
| 'attention';
type types = 'wns/toast' | 'wns/badge' | 'wns/tile' | 'wns/raw';
declare class WnsService {
constructor(service: NotificationHubService);
public notificationHubService: NotificationHubService;
sendTileSquareBlock(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileSquareText01(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileSquareText02(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileSquareText03(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileSquareText04(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideText01(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideText02(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideText03(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideText04(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideText05(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideText06(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideText07(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideText08(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideText09(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideText10(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideText11(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileSquareImage(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileSquarePeekImageAndText01(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileSquarePeekImageAndText02(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileSquarePeekImageAndText03(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileSquarePeekImageAndText04(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideImage(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideImageCollection(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideImageAndText01(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideImageAndText02(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideBlockAndText01(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideBlockAndText02(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideSmallImageAndText01(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideSmallImageAndText02(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideSmallImageAndText03(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideSmallImageAndText04(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWideSmallImageAndText05(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWidePeekImageCollection01(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWidePeekImageCollection02(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWidePeekImageCollection03(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWidePeekImageCollection04(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWidePeekImageCollection05(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWidePeekImageCollection06(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWidePeekImageAndText01(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWidePeekImageAndText02(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWidePeekImage01(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWidePeekImage02(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWidePeekImage03(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWidePeekImage04(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWidePeekImage05(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendTileWidePeekImage06(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendToastText01(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendToastText02(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendToastText03(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendToastText04(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendToastImageAndText01(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendToastImageAndText02(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendToastImageAndText03(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendToastImageAndText04(tags: string | string[],
payload: any,
optionsOrCallback: Options | Callback,
callback?: Callback): void;
sendBadge(tags: badges | badges[],
value: string | number,
callback?: Callback): void;
sendBadge(tags: badges | badges[],
value: string | number,
options: Options,
callback?: Callback): void;
sendRaw(tags: string | string[],
payload: any,
callback?: Callback): void;
sendRaw(tags: string | string[],
payload: any,
options: Options,
callback?: Callback): void;
send(tags: string | string[],
payload: string,
type: types,
callback?: Callback): void;
send(tags: string | string[],
payload: string,
type: types,
options: Options,
callback: Callback): void;
createNativeRegistration(channel: string,
tags: string | string[],
callback: Callback): void;
createNativeRegistration(channel: string,
tags: string | string[],
options: Options,
callback: Callback): void;
createOrUpdateNativeRegistration(registrationId: string,
channel: string,
tags: string | string[],
callback: Callback): void;
createOrUpdateNativeRegistration(registrationId: string,
channel: string,
tags: string | string[],
options: Options,
callback: Callback): void;
listRegistrationsByChannel(channel: string,
callback: Callback): void;
listRegistrationsByChannel(channel: string,
options: ListNotificationHubsOptions,
callback: Callback): void;
}
export = WnsService;
+21
View File
@@ -0,0 +1,21 @@
import { Azure } from 'azure-sb';
declare class WrapService {
constructor(acsHost: string, issuer?: string, accessKey?: string);
public issuer?: string;
public accessKey?: string;
public authenticationProvider: {
signRequest(webResource: any, callback: () => void): void;
};
public strictSSL: boolean;
public wrapAccessToken(uri: string,
callback: Azure.ServiceBus.ResponseCallback): void;
public wrapAccessToken(uri: string,
options: object,
callback: Azure.ServiceBus.ResponseCallback): void;
}
export = WrapService;
+22 -3
View File
@@ -17,7 +17,26 @@
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"azure-sb-tests.ts"
"lib/servicebusservice.d.ts",
"lib/wrapservice.d.ts",
"lib/servicebusservicebase.d.ts",
"lib/notificationhubservice.d.ts",
"lib/models/topicresult.d.ts",
"lib/models/queuemessageresult.d.ts",
"lib/models/acstokenresult.d.ts",
"lib/models/registrationresult.d.ts",
"lib/models/ruleresult.d.ts",
"lib/models/queueresult.d.ts",
"lib/models/subscriptionresult.d.ts",
"lib/models/notificationhubresult.d.ts",
"lib/models/resourceresult.d.ts",
"lib/servicebusserviceclient.d.ts",
"lib/gcmservice.d.ts",
"lib/wnsservice.d.ts",
"lib/mpnservice.d.ts",
"lib/apnsservice.d.ts",
"azure-sb-tests.ts",
"index.d.ts"
]
}
}
+1 -1
View File
@@ -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;
+31 -10
View File
@@ -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 <https://github.com/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<WheelOption> | boolean;
/**
* for slide
* snap: {
@@ -77,14 +88,14 @@ interface BsOption {
* listenFlick: true
* }
*/
snap?: SlideOption | boolean;
snap?: Partial<SlideOption> | boolean;
/**
* for scrollbar
* scrollbar: {
* fade: true
* }
*/
scrollbar?: ScrollBarOption | boolean;
scrollbar?: Partial<ScrollBarOption> | boolean;
/**
* for pull down and refresh
* pullDownRefresh: {
@@ -92,20 +103,30 @@ interface BsOption {
* stop: 20
* }
*/
pullDownRefresh?: PullDownOption | boolean;
pullDownRefresh?: Partial<PullDownOption> | boolean;
/**
* for pull up and load
* pullUpLoad: {
* threshold: 50
* }
*/
pullUpLoad?: PullUpOption | boolean;
pullUpLoad?: Partial<PullUpOption> | 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 数据已加载
+4
View File
@@ -0,0 +1,4 @@
import bindings = require('bindings');
// Use your bindings defined in your C files
const result = bindings('binding.node').your_c_function();
+13
View File
@@ -0,0 +1,13 @@
// Type definitions for bindings 1.3
// Project: https://github.com/TooTallNate/node-bindings
// Definitions by: Daniel Perez Alvarez <https://github.com/unindented>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* The main `bindings()` function loads the compiled bindings for a given module.
* It uses V8's Error API to determine the parent filename that this function is
* being invoked from, which is then used to find the root directory.
*/
declare function bindings(mod: string): any;
export = bindings;
+23
View File
@@ -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",
"bindings-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+31
View File
@@ -0,0 +1,31 @@
import * as React from "react";
import * as BraftEditor from "braft-editor";
import {
RawDraftContentState,
} from 'draft-js';
class BraftEditorTest extends React.Component<BraftEditor.editorProps> {
state = {
content: null
};
render() {
const editorProps = {
height: 500,
initialContent: this.state.content,
onChange: this.handleChange,
onHTMLChange: this.handleHTMLChange
};
return (
<div>
<BraftEditor
{...editorProps}
/>
</div>
);
}
private handleChange = (content: RawDraftContentState) => {
console.log(content);
}
private handleHTMLChange = (html: string) => {
console.log(html);
}
}
+59
View File
@@ -0,0 +1,59 @@
// Type definitions for braft-editor 1.1
// Project: https://github.com/margox/braft#readme
// Definitions by: My Self <https://github.com/me>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import * as React from "react";
import { RawDraftContentState } from 'draft-js';
export as namespace BraftEditor;
export = BraftEditor;
declare namespace BraftEditor {
interface fontFamiliesRange {
name: string;
family: string;
}
interface editorProps {
editorState?: any;
contentFormat?: RawDraftContentState;
initialContent?: RawDraftContentState | null;
onChange?: (content: RawDraftContentState) => void;
onRawChange?: (content: RawDraftContentState) => void;
onHTMLChange?: (content: string) => void;
controls?: string[];
extendControls?: any[];
height?: number;
language?: string;
placeholder?: string;
viewWrapper?: string;
colors?: string[];
fontSizes?: number[];
fontFamilies?: fontFamiliesRange[];
media?: { [key: string]: any };
getContent?: (format?: string) => RawDraftContentState;
setContent?: (content: RawDraftContentState, format?: string) => void;
toggleSelectionBlockType?: (blockquote: string) => any;
toggleSelectionInlineStyle?: (style: string, stylesToBeRemoved?: string[]) => any;
insertMedias?: (medias: Array<{ type: string, name: string, url: string }>) => void;
insertText?: (text: string, replace?: boolean) => void;
toggleSelectionLink?: (href: string, target: string) => void;
toggleSelectionAlignment?: (alignment: string) => any;
toggleSelectionColor?: (hexColor: string) => void;
toggleSelectionBackgroundColor?: (hexColor: string) => void;
toggleSelectionFontSize?: (fontSize: number) => void;
toggleSelectionFontFamily?: (fontFamily: string) => void;
selectionCollapsed?: () => boolean;
selectionHasInlineStyle?: () => boolean;
getSelectionBlockType?: () => string;
getEditorState?: () => void;
forceRender?: () => void;
getDraftInstance?: () => any;
getMediaLibraryInstance?: () => any;
getSelectionInlineStyle?: () => any;
undo?: () => any;
redo?: () => any;
focus?: () => void;
blur?: () => void;
}
}
declare class BraftEditor extends React.Component<BraftEditor.editorProps> { }
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"jsx": "react",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"braft-editor-tests.tsx"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+6
View File
@@ -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 */
@@ -55,6 +58,9 @@ export class Code {
}
export class DBRef {
constructor(namespace: string, oid: ObjectID, db?: string);
namespace: string;
oid: ObjectID;
db?: string;
}
export class Double {
constructor(value: number);
+32
View File
@@ -0,0 +1,32 @@
import CanCan = require('cancan');
const cancan = new CanCan();
// $ExpectType void
cancan.allow('admin', 'manage', 'all');
// $ExpectType void
cancan.allow('user', 'read', 'post', {public: true});
// $ExpectType boolean
cancan.can('user', 'read', 'post');
// $ExpectType boolean
cancan.cannot('user', 'delete', 'post');
// $ExpectType void
cancan.authorize('user', 'delete', 'post');
// $ExpectType boolean
cancan.can('user', 'read', 'post', {fields: ['title']});
// $ExpectType boolean
cancan.cannot('user', 'delete', 'post', {fields: ['title']});
// $ExpectType void
cancan.authorize('user', 'delete', 'post', {fields: ['title']});
const cancanWithOption = new CanCan({
instanceOf: (_instance, _model) => true,
createError: () => true
});
+29
View File
@@ -0,0 +1,29 @@
// Type definitions for cancan 3.1
// Project: https://github.com/vadimdemedes/cancan
// Definitions by: Vincent Pang <https://github.com/Vincent-Pang>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
declare namespace CanCan {
interface Option {
instanceOf?: (instance: any, model: any) => boolean;
createError?: () => any;
}
}
declare class CanCan {
constructor(options?: CanCan.Option);
allow<T>(model: any,
actions: string | ReadonlyArray<string>,
targets: T | ReadonlyArray<T> | string | ReadonlyArray<string>,
condition?: object | ((performer: any, target: any, options?: any) => boolean)): void;
can(performer: any, action: string, target: any, options?: any): boolean;
cannot(performer: any, action: string, target: any, options?: any): boolean;
authorize(performer: any, action: string, target: any, options?: any): void;
}
export = CanCan;
+23
View File
@@ -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",
"cancan-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+42 -45
View File
@@ -1,3 +1,4 @@
/// <reference types="node" />
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);
});
@@ -1372,13 +1370,13 @@ suite('assert', () => {
});
test('nestedInclude', () => {
assert.nestedInclude({'.a': {'b': 'x'}}, {'\\.a.[b]': 'x'});
assert.nestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'x'});
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'});
assert.notNestedInclude({'.a': {b: 'x'}}, {'\\.a.b': 'y'});
assert.notNestedInclude({a: {'[b]': 'x'}}, {'a.\\[b\\]': 'y'});
});
test('deepNestedInclude', () => {
@@ -1387,7 +1385,7 @@ suite('assert', () => {
});
test('notDeepNestedInclude', () => {
assert.notDeepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {y: 1}})
assert.notDeepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {y: 1}});
assert.notDeepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {y: 2}});
});
@@ -1548,7 +1546,6 @@ suite('assert', () => {
assert.sameMembers([1, 54], [6, 1, 54]);
});
test('isAbove', () => {
assert.isAbove(10, 5);
assert.isAbove(1, 5);
@@ -1738,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<any,any>([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']);
assert.hasAllKeys(new Map<any, any>([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']);
assert.hasAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']);
});
@@ -1747,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<any,any>([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}]);
assert.containsAllKeys(new Map<any,any>([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']);
assert.containsAllKeys(new Map<any, any>([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}]);
assert.containsAllKeys(new Map<any, any>([[{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']);
});
@@ -1756,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<any,any>([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']);
assert.doesNotHaveAnyKeys(new Map<any, any>([[{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<any,any>([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']);
assert.doesNotHaveAllKeys(new Map<any, any>([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']);
assert.doesNotHaveAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{one: 'two'}, 'example']);
});
test('hasAnyDeepKeys', () => {
assert.hasAnyDeepKeys(new Map<any,any>([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'});
assert.hasAnyDeepKeys(new Map<any,any>([[{one: 'one'}, 'valueOne'], [1, 2]]), [{one: 'one'}, {two: 'two'}]);
assert.hasAnyDeepKeys(new Map<any,any>([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]);
assert.hasAnyDeepKeys(new Map<any, any>([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'});
assert.hasAnyDeepKeys(new Map<any, any>([[{one: 'one'}, 'valueOne'], [1, 2]]), [{one: 'one'}, {two: 'two'}]);
assert.hasAnyDeepKeys(new Map<any, any>([[{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'}]);
@@ -1778,28 +1775,28 @@ suite('assert', () => {
test('hasAllDeepKeys', () => {
assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne']]), {one: 'one'});
assert.hasAllDeepKeys(new Map<any,any>([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]);
assert.hasAllDeepKeys(new Map<any, any>([[{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<any,any>([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'});
assert.containsAllDeepKeys(new Map<any,any>([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]);
assert.containsAllDeepKeys(new Map<any, any>([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'});
assert.containsAllDeepKeys(new Map<any, any>([[{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<any,any>([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'});
assert.doesNotHaveAnyDeepKeys(new Map<any,any>([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {fifty: 'fifty'}]);
assert.doesNotHaveAnyDeepKeys(new Map<any, any>([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'});
assert.doesNotHaveAnyDeepKeys(new Map<any, any>([[{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<any,any>([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'});
assert.doesNotHaveAllDeepKeys(new Map<any,any>([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {one: 'one'}]);
assert.doesNotHaveAllDeepKeys(new Map<any, any>([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'});
assert.doesNotHaveAllDeepKeys(new Map<any, any>([[{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'}]);
});
+18 -56
View File
@@ -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 <https://github.com/jedmao>,
// Bart van der Schoor <https://github.com/Bartvds>,
@@ -13,7 +13,6 @@
// <reference types="assertion-error"/>
declare namespace Chai {
interface ChaiStatic {
expect: ExpectStatic;
should(): Should;
@@ -55,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;
}
@@ -219,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;
@@ -236,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 {
@@ -698,21 +688,11 @@ declare namespace Chai {
/**
* Asserts that haystack does not include needle.
*
* @param haystack Container string.
* @param haystack Container string or array.
* @param needle Potential expected substring of haystack.
* @param message Message to display on error.
*/
notInclude(haystack: string, needle: any, message?: string): void;
/**
* Asserts that haystack does not include needle.
*
* @param haystack Container array.
* @param needle Potential value contained in haystack.
* @param message Message to display on error.
*/
notInclude(haystack: any[], needle: any, message?: string): void;
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.
@@ -735,20 +715,11 @@ declare namespace Chai {
/**
* Asserts that haystack does not include needle. Can be used to assert the absence of a value in an array or a subset of properties in an object. Deep equality is used.
*
* @param haystack Container string.
* @param haystack Container string or array.
* @param needle Potential expected substring of haystack.
* @param message Message to display on error.
*/
notDeepInclude(haystack: string, needle: any, message?: string): void;
/**
* Asserts that haystack does not include needle. Can be used to assert the absence of a value in an array or a subset of properties in an object. Deep equality is used.
*
* @param haystack
* @param needle
* @param message Message to display on error.
*/
notDeepInclude(haystack: any[], needle: any, message?: string): void;
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.
@@ -1014,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
@@ -1289,7 +1251,7 @@ declare namespace Chai {
* @param property Property of object expected to be modified.
* @param message Message to display on error.
*/
changes<T>(modifier: Function, object: T, property: string /* keyof T */, message?: string): void
changes<T>(modifier: Function, object: T, property: string /* keyof T */, message?: string): void;
/**
* Asserts that a function does not change the value of a property.
@@ -1300,7 +1262,7 @@ declare namespace Chai {
* @param property Property of object expected not to be modified.
* @param message Message to display on error.
*/
doesNotChange<T>(modifier: Function, object: T, property: string /* keyof T */, message?: string): void
doesNotChange<T>(modifier: Function, object: T, property: string /* keyof T */, message?: string): void;
/**
* Asserts that a function increases an object property.
@@ -1311,7 +1273,7 @@ declare namespace Chai {
* @param property Property of object expected to be increased.
* @param message Message to display on error.
*/
increases<T>(modifier: Function, object: T, property: string /* keyof T */, message?: string): void
increases<T>(modifier: Function, object: T, property: string /* keyof T */, message?: string): void;
/**
* Asserts that a function does not increase an object property.
@@ -1322,7 +1284,7 @@ declare namespace Chai {
* @param property Property of object expected not to be increased.
* @param message Message to display on error.
*/
doesNotIncrease<T>(modifier: Function, object: T, property: string /* keyof T */, message?: string): void
doesNotIncrease<T>(modifier: Function, object: T, property: string /* keyof T */, message?: string): void;
/**
* Asserts that a function decreases an object property.
@@ -1333,7 +1295,7 @@ declare namespace Chai {
* @param property Property of object expected to be decreased.
* @param message Message to display on error.
*/
decreases<T>(modifier: Function, object: T, property: string /* keyof T */, message?: string): void
decreases<T>(modifier: Function, object: T, property: string /* keyof T */, message?: string): void;
/**
* Asserts that a function does not decrease an object property.
@@ -1344,7 +1306,7 @@ declare namespace Chai {
* @param property Property of object expected not to be decreased.
* @param message Message to display on error.
*/
doesNotDecrease<T>(modifier: Function, object: T, property: string /* keyof T */, message?: string): void
doesNotDecrease<T>(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.
+1 -66
View File
@@ -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
}
}
+2 -1
View File
@@ -44,7 +44,8 @@ const chart: Chart = new Chart(new CanvasRenderingContext2D(), {
zeroLineBorderDashOffset: 2
}
}]
}
},
plugins: { arbitraryPlugin: {option: "value"} }
}
});
chart.update();
+3 -1
View File
@@ -176,6 +176,8 @@ declare namespace Chart {
cutoutPercentage?: number;
circumference?: number;
rotation?: number;
// Plugins can require any options
plugins?: any;
}
interface ChartFontOptions {
@@ -362,7 +364,7 @@ declare namespace Chart {
interface TickOptions {
autoSkip?: boolean;
autoSkipPadding?: boolean;
autoSkipPadding?: number;
callback?(value: any, index: any, values: any): string|number;
display?: boolean;
fontColor?: ChartColor;
+17 -152
View File
@@ -10,7 +10,6 @@ interface ChocolateChipStatic {
*
* @param selector A string containing a selector expression
* @param context A DOM HTMLElement to use as context
* @return HTMLElement[]
*/
(selector: string | HTMLElement | Document, context?: HTMLElement | ChocolateChipElementArray): ChocolateChipElementArray;
@@ -18,7 +17,6 @@ interface ChocolateChipStatic {
* Binds a function to be executed when the DOM has finished loading.
*
* @param callback A function to execute after the DOM is ready.
* @return void
*/
(callback: () => any): void;
@@ -26,7 +24,6 @@ interface ChocolateChipStatic {
* Accepts a string containing a CSS selector which is then used to match a set of elements.
*
* @param element A DOM element to wrap in an array.
* @return HTMLElement[]
*/
(element: HTMLElement): ChocolateChipElementArray;
@@ -34,7 +31,6 @@ interface ChocolateChipStatic {
* Accepts a string containing a CSS selector which is then used to match a set of elements.
*
* @param elementArray An array of DOM elements to convert into a ChocolateChip Collection.
* @return HTMLElement[]
*/
(elementArray: ChocolateChipElementArray): ChocolateChipElementArray;
@@ -42,13 +38,11 @@ interface ChocolateChipStatic {
* Accepts the document element and returns it wrapped in an array.
*
* @param document The document object.
* @return document[]
*/
(document: Document): Document[];
/**
* If no argument is provided, return the document as a ChocolateChipElementArray.
* @return Document[]
*/
(): Document[];
@@ -94,8 +88,6 @@ interface ChocolateChipStatic {
/**
* An empty function.
*
* @return void.
*/
noop(): void;
@@ -106,40 +98,27 @@ interface ChocolateChipStatic {
/**
* Create a random number to use as a uuid.
*
* @return number.
*/
uuidNum(): number;
/**
* Creates a uuid using uuidNum().
*
* @return A string.
*/
makeUuid(): string;
/**
* Create a ChocolateChip collection object by creating elements from an HTML string.
*
* @param selector
* @return any
*/
make(selector: string): ChocolateChipElementArray;
/**
* Create a ChocolateChip collection object by creating elements from an HTML string. This is an alias for $.make.
*
* @param selector
* @return any
*/
html(selector: string): ChocolateChipElementArray;
/**
* Replace one element with another.
*
* @param new HTMLElement
* @param old HTMLElement
* @return HTMLElement[]
* @return {HTMLElement[]}
*/
replace(newElement: ChocolateChipElementArray, oldElement: ChocolateChipElementArray): void;
@@ -148,7 +127,7 @@ interface ChocolateChipStatic {
*
* @param url A string containing the URL where the script resides.
* @param callback A callback function that is executed after the script loads.
* @return void
* @return {void}
*/
require(url: string, callback: Function): Function;
@@ -157,7 +136,7 @@ interface ChocolateChipStatic {
*
* @param url A string containing the URL where the script resides.
* @param callback A callback function that is executed after the script loads.
* @return Function
* @return {Function}
*/
processJSON(json: string, name?: string): any;
@@ -173,7 +152,6 @@ interface ChocolateChipStatic {
* Parse the data in a Promise response as JSON.
*
* @param response The response from a Promise.
* @result
*/
json(reponse: Response): JSON;
@@ -182,7 +160,6 @@ interface ChocolateChipStatic {
*
* @param callback A function to execute.
* @param duration The number of milliseconds to delay execution.
* @return any
*/
delay(callback: Function, duration?: number): any;
@@ -190,7 +167,6 @@ interface ChocolateChipStatic {
* The method will defer the execution of its callback until the call stack is clear.
*
* @param callback A callback to execute after a delay.
* @return Function.
*/
defer(callback: Function): Function;
@@ -215,16 +191,14 @@ interface ChocolateChipStatic {
/**
* This method will concatenate strings or values as a cleaner alternative to using the '+' operator.
*
* @param string or number A comma separated series of strings to concatenate.
* @return string
* @param {string | number} A comma separated series of strings to concatenate.
*/
concat(...string: string[]): string;
/**
* This method takes a space-delimited string of words and returns it as an array where the individual words are indices.
*
* @param string Any string with values separated by spaces.
* @return string[]
* @param Any string with values separated by spaces.
*/
w(string: string): string[];
@@ -232,7 +206,6 @@ interface ChocolateChipStatic {
* This method converts a string of hyphenated tokens into a camel cased string.
*
* @param string A string of hyphenated tokens.
* @return string
*/
camelize(string: string): string;
@@ -240,16 +213,11 @@ interface ChocolateChipStatic {
* This method converts a camel case string into lowercase with hyphens.
*
* @param string A camel case string.
* @return string
*/
deCamelize(string: string): string;
/**
* This method capitalizes the first letter of a string.
*
* @param string A string.
* @param boolean A boolean value.
* @return string
*/
capitalize(string: string, boolean?: boolean): string;
@@ -257,7 +225,6 @@ interface ChocolateChipStatic {
* Determine whether the argument is a string.
*
* @param obj Object to test whether or not it is a string.
* @return boolean
*/
isString(obj: any): boolean;
@@ -265,7 +232,6 @@ interface ChocolateChipStatic {
* Determine whether the argument is an array.
*
* @param obj Object to test whether or not it is an array.
* @return boolean
*/
isArray(obj: any): boolean;
@@ -273,7 +239,6 @@ interface ChocolateChipStatic {
* Determine whether the argument is a function.
*
* @param obj Object to test whether or not it is an function.
* @return boolean
*/
isFunction(obj: any): boolean;
@@ -281,7 +246,6 @@ interface ChocolateChipStatic {
* Determine whether the argument is an object.
*
* @param obj Object to test whether or not it is an object.
* @return boolean
*/
isObject(obj: any): boolean;
@@ -297,7 +261,6 @@ interface ChocolateChipStatic {
* Determine whether the argument is an empty object.
*
* @param obj Object to test whether or not it is an empty object.
* @return boolean
*/
isEmptyObject(obj: any): boolean;
@@ -305,7 +268,6 @@ interface ChocolateChipStatic {
* Determine whether the argument is a number.
*
* @param obj Object to test whether or not it is a number.
* @return boolean
*/
isNumber(obj: any): boolean;
@@ -313,7 +275,6 @@ interface ChocolateChipStatic {
* Determine whether the argument is an integer.
*
* @param obj Object to test whether or not it is an integer.
* @return boolean
*/
isInteger(obj: any): boolean;
@@ -321,7 +282,6 @@ interface ChocolateChipStatic {
* Determine whether the argument is a float.
*
* @param obj Object to test whether or not it is a float.
* @return boolean
*/
isFloat(obj: any): boolean;
@@ -443,8 +403,8 @@ interface ChocolateChipStatic {
/**
* Grabs values from a form and converts them into a JSON object.
*
* @param rootNode: string | HTMLElement A form whose values you want to convert to JSON.
* @param delimiter string A delimiter to namespace your form values. The default is "."
* @param rootNode: A form whose values you want to convert to JSON.
* @param delimiter A delimiter to namespace your form values. The default is "."
* You use the form input's name to set up the namespace structure for your JSON, e.g. name="newUser.name.first".
*/
form2JSON(rootNode: string | HTMLElement, delimiter: string): Object;
@@ -453,35 +413,33 @@ interface ChocolateChipStatic {
* Subscribe to a publication. You provide the topic you want to subscribe to, as well as a callback to execute when a publication occurs.
* Any data passed by the publisher is exposed to the callback as its second parameter. The callback's first parameter is the published topic.
*
* @param topic string A topic to subscribe to. This can be a single term, or any type of namespaced term with delimiters.
* @data any You can receive any type: string, number, array, object, etc.
* @return any
* @param topic A topic to subscribe to. This can be a single term, or any type of namespaced term with delimiters.
* @param callback You can receive any type: string, number, array, object, etc.
*/
subscribe(topic: string, callback: (topic: string, data: any) => any): boolean;
/**
* Unsubscribe from a topic. Pass this the topic you wish to unsubscribe from. The subscription will be terminated immediately.
*
* @param topic string The name of the topic to unsubscribe from.
* @return void
* @param topic The name of the topic to unsubscribe from.
*/
unsubscribe(topic: string): void;
/**
* Publish a topic with data for the topic's subscribers to receive.
*
* @param topic string The topic you wish to publish.
* @param topic The topic you wish to publish.
* @param data The data to send with the publication. This can be of any type: string, number, array, object, etc.
* @return void
* @return {void}
*/
publish(topic: string, data: any): string;
/**
* Object used to store string templates and parsed templates.
*
* @param string A string defining the template.
* @param string A label used to access an object's properties in the template. If none is provided it defaults to "data": [[= data.name]].
* @return void
* @param {strin} A string defining the template.
* @param {string} A label used to access an object's properties in the template. If none is provided it defaults to "data": [[= data.name]].
* @return {void}
*/
templates: Object;
@@ -495,7 +453,6 @@ interface ChocolateChipStatic {
*
* @param template A string of markup to use as a template.
* @param variable An option name to use in the template. If it were "myData": [[= myData.name]]. Otherwise it defaults to "data": [[= data.name]].
* @return A function.
*/
(template: string, variable?: string): Function;
@@ -514,7 +471,6 @@ interface ChocolateChipStatic {
* @param element The target container into which the content will be inserted.
* @param template A string of markup.
* @param data The iterable data the template will consume.
* @return void.
*/
(element: ChocolateChipElementArray, template: string, data: any): void;
}
@@ -523,7 +479,6 @@ interface ChocolateChipStatic {
* An object that holds the reference to the controller for a repeater.
* This is used to cache the data that a repeater uses. After the repeater is rendered, the reference is deleted from this object.
* Example: $.template.data["myRepeater"] = [{name: "Joe"}, {name: "Sue"}];
*
*/
data: any;
@@ -567,16 +522,11 @@ interface ChocolateChipStatic {
interface ChocolateChipElementArray extends Array<HTMLElement> {
/**
* Iterate over an Array object, executing a function for each matched element.
*
* @param Function
* @return void
*/
each(func: (ctx: any, idx: number) => void): void;
/**
* Sorts an array and removes duplicates before returning it.
*
* @return Array
*/
unique(): ChocolateChipElementArray;
@@ -585,16 +535,13 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* When dealing with document nodes, this allows you to cherry pick a node from its collection based on its
* position amongst its siblings.
*
* @param number Index value indicating the node you wish to access from a collection. This is zero-based.
* @return HTMLElement
* @param index Value indicating the node you wish to access from a collection. This is zero-based.
*/
eq(index: number): ChocolateChipElementArray;
/**
* Search for a given element from among the matched elements on a collection.
* This method returns the index value as an integer.
*
* @return number
*/
index(): number;
@@ -603,7 +550,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* This method returns the index value as an integer.
*
* @param selector A selector representing an element to look for in a collection of elements.
* @return number
*/
index(selector: string | HTMLElement[]): number;
@@ -612,7 +558,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* if it matches the given arguments.
*
* @param selector A string containing a selector expression to match elements against.
* @return HTMLElement[]
*/
is(selector: string): ChocolateChipElementArray;
@@ -621,7 +566,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* if it matches the given arguments.
*
* @param elements One or more elements to match the current set of elements against.
* @ return HTMLElement[]
*/
is(element: any): ChocolateChipElementArray;
@@ -630,7 +574,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* if it does not match the given arguments.
*
* @param selector A string containing a selector expression to match elements against.
* @ return HTMLElement[]
*/
isnt(selector: string): ChocolateChipElementArray;
@@ -639,7 +582,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* if it does not match the given arguments.
*
* @param elements One or more elements to match the current set of elements against.
* @ return HTMLElement[]
*/
isnt(element: any): ChocolateChipElementArray;
@@ -647,7 +589,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.
*
* @param selector A string containing a selector expression to match elements against.
* @ return HTMLElement[]
*/
has(selector: string): ChocolateChipElementArray;
@@ -655,7 +596,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.
*
* @param contained A DOM element to match elements against.
* @ return HTMLElement[]
*/
has(contained: HTMLElement): ChocolateChipElementArray;
@@ -671,7 +611,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Reduce the set of matched elements to those that have a descendant that does not match the selector or DOM element.
*
* @param contained A DOM element to match elements against.
* @ return HTMLElement[]
*/
hasnt(contained: HTMLElement): ChocolateChipElementArray;
@@ -684,7 +623,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Get the descendants of each element in the current set of matched elements, filtered by a selector or element.
*
* @param selector A string containing a selector expression to match elements against.
* @ return HTMLElement[]
*/
find(selector: string): ChocolateChipElementArray;
@@ -692,21 +630,16 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Get the descendants of each element in the current set of matched elements, filtered by a selector or element.
*
* @param element An element to match elements against.
* @ return HTMLElement[]
*/
find(element: HTMLElement): ChocolateChipElementArray;
/**
* Get the immediately preceding sibling of each element in the set of matched elements.
*
* @ return HTMLElement[]
*/
prev(): ChocolateChipElementArray;
/**
* Get the immediately following sibling of each element in the set of matched elements.
*
* @ return HTMLElement[]
*/
next(): ChocolateChipElementArray;
@@ -717,8 +650,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
/**
* Reduce the set of matched elements to the last in the set.
*
* @return HTMLElement[]
*/
last(): ChocolateChipElementArray;
@@ -726,7 +657,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Get the children of each element in the set of matched elements, optionally filtered by a selector.
*
* @param selector A string containing a selector expression to match elements against.
* @return HTMLElement[]
*/
children(selector?: string): ChocolateChipElementArray;
@@ -735,7 +665,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* If multiple elements have the same parent, only one instance of the parent is returned.
*
* @param selector A string containing a selector expression to match elements against.
* @return HTMLElement[]
*/
parent(selector?: string): ChocolateChipElementArray;
@@ -745,7 +674,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* retrieving that ancestor based on its distance from the element.
*
* @param selector A string containing a selector expression to match elements against.
* @return HTMLElement[]
*/
ancestor(selector: string | number): ChocolateChipElementArray;
@@ -754,7 +682,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* itself and traversing up through its ancestors in the DOM tree.
*
* @param selector A string containing a selector expression to match elements against.
* @return HTMLElement[]
*/
closest(selector: string | number): ChocolateChipElementArray;
@@ -762,14 +689,11 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
*
* @param selector A string containing a selector expression to match elements against.
* @return HTMLElement[]
*/
siblings(selector?: string): ChocolateChipElementArray;
/**
* Get the HTML contents of the first element in the set of matched elements.
*
* @return HTMLElement[]
*/
html(): ChocolateChipElementArray;
@@ -777,7 +701,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Set the HTML contents of each element in the set of matched elements.
*
* @param htmlString A string of HTML to set as the content of each matched element.
* @return HTMLElement[]
*/
html(htmlString: string): ChocolateChipElementArray;
@@ -785,7 +708,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Get the value of style properties for the first element in the set of matched elements.
*
* @param propertyName A CSS property.
* @return string
*/
css(propertyName: string): string;
@@ -794,7 +716,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
*
* @param propertyName A CSS property name.
* @param value A value to set for the property.
* @return HTMLElement[]
*/
css(propertyName: string, value: string): ChocolateChipElementArray;
@@ -802,7 +723,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Set one or more CSS properties for the set of matched elements.
*
* @param properties An object of property-value pairs to set.
* @return HTMLElement[]
*/
css(properties: Object): ChocolateChipElementArray;
@@ -819,7 +739,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
*
* @param attributeName A string indicating the attribute to set.
* @param value A string indicating the value to set the attribute to.
* @return HTMLElement[]
*/
attr(attributeName: string, value: string): ChocolateChipElementArray;
@@ -827,7 +746,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Remove an attribute from a node.
*
* @param attributeName A string indicating the attribute to remove.
* @return HTMLElement[]
*/
removeAttr(attributeName: string): ChocolateChipElementArray;
@@ -835,7 +753,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Return any of the matched elements that have the given attribute.
*
* @param className The class name to search for.
* @return HTMLElement[]
*/
hasAttr(attributeName: string): ChocolateChipElementArray;
@@ -843,7 +760,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Test whether an attribute exists on the first element in the set of matched elements. The value returned is a boolean.
*
* @param attributeName The name of the attribute to get.
* @return boolean
*/
prop(propertyName: string): boolean;
@@ -852,7 +768,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
*
* @param propertyName A string indicating the property to set.
* @param value A string indicating the value to set the property to.
* @return HTMLElement[]
*/
prop(propertyName: string, value: any | boolean): ChocolateChipElementArray;
@@ -860,7 +775,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Remove an element property.
*
* @param property The property to remove.
* @return HTMLElement[]
*/
removeProp(property: string): ChocolateChipElementArray;
@@ -868,7 +782,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Adds the specified class(es) to each of the set of matched elements.
*
* @param className One or more space-separated classes to be added to the class attribute of each matched element.
* @return HTMLElement[]
*/
addClass(className: string): ChocolateChipElementArray;
@@ -876,7 +789,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Remove a single class or multiple classes from each element in the set of matched elements.
*
* @param className One or more space-separated classes to be removed from the class attribute of each matched element.
* @return HTMLElement[]
*/
removeClass(className?: string): ChocolateChipElementArray;
@@ -884,7 +796,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Add or remove a classe from each element in the set of matched elements, depending on whether the class is present or not.
*
* @param className One or more class names (separated by spaces) to be toggled for each element in the matched set.
* @return HTMLElement[]
*/
toggleClass(className: string, swtch?: boolean): ChocolateChipElementArray;
@@ -892,7 +803,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Return any of the matched elements that have the given class.
*
* @param className The class name to search for.
* @return HTMLElement[]
*/
hasClass(className: string): ChocolateChipElementArray;
@@ -901,7 +811,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
*
* @param key A string naming the piece of data to set.
* @param value The new data value; it can be any Javascript type including Array or Object.
* @return HTMLElement[]
*/
data(key: string, value: any): ChocolateChipElementArray;
@@ -910,7 +819,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* data(name).
*
* @param key Name of the data stored.
* @return any
*/
data(key: string): any;
@@ -918,7 +826,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Remove the value at the named data store for the first element in the element collection, as set by data(name, value).
*
* @param key Name of the data stored.
* @return any
*/
removeData(key?: string): any;
@@ -927,7 +834,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
*
* @param key A string naming the piece of data to set.
* @param value The new data value; it must be a string. You can convert JSON into a string to use with this.
* @return HTMLElement[]
*/
dataset(key: string, value: any): ChocolateChipElementArray;
@@ -935,7 +841,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Retrieve a dataset key's value for the first element in the element collection.
*
* @param key A string naming the piece of data to set.
* @return HTMLElement[]
*/
dataset(key: string): ChocolateChipElementArray;
@@ -943,7 +848,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Return the value at the named data store for the first element in the element collection, as set by data(name, value).
*
* @param key Name of the data stored.
* @return any
*/
data(key: string): any;
@@ -952,7 +856,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
*
* @param key A string naming the piece of data to set.
* @param value The new data value; it can be any Javascript type including Array or Object.
* @return HTMLElement[]
*/
data(key: string, value?: any): ChocolateChipElementArray;
@@ -966,21 +869,16 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
*
* @param value A string of text or an array of strings corresponding to the value of each matched element
* to set as selected/checked.
* @return any
*/
val(value: string): ChocolateChipElementArray;
/**
* Set the property of an element to enabled by removing the "disabled" attribute.
*
* @return HTMLElement[]
*/
enable(): ChocolateChipElementArray;
/**
* Set the property of an element to "disabled".
*
* @return HTMLElement[]
*/
disable(): ChocolateChipElementArray;
@@ -989,7 +887,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
*
* @param speed A string or number determining how long the animation will run.
* @param callback A function to call once the animation is complete.
* @return HTMLElement[]
*/
show(duration?: number | string, callback?: Function): ChocolateChipElementArray;
@@ -998,7 +895,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
*
* @param duration A string or number determining how long the animation will run.
* @param callback A function to call once the animation is complete.
* @return HTMLElement[]
*/
hide(duration?: number | string, callback?: Function): ChocolateChipElementArray;
@@ -1006,7 +902,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Insert content, specified by the parameter, before each element in the set of matched elements.
*
* @param content HTML string, DOM element, array of elements to insert before each element in the set of matched elements.
* @return HTMLElement[]
*/
before(content: ChocolateChipElementArray | HTMLElement | string): ChocolateChipElementArray;
@@ -1014,7 +909,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Insert content, specified by the parameter, after each element in the set of matched elements.
*
* @param content HTML string, DOM element, array of elements to insert after each element in the set of matched elements.
* @return HTMLElement[]
*/
after(content: ChocolateChipElementArray | HTMLElement | string): ChocolateChipElementArray;
@@ -1023,7 +917,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
*
* @param content DOM element, array of elements, or HTML string to insert at the end of each element in the set
* of matched elements.
* @return HTMLElement[]
*/
append(content: ChocolateChipElementArray | HTMLElement | Text | string): ChocolateChipElementArray;
@@ -1031,7 +924,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Insert content, specified by the parameter, at the beginning of each element in the set of matched elements.
*
* @param content DOM element, array of elements, or HTML string to insert at the beginning of each element in the set of matched elements.
* @return HTMLElement[]
*/
prepend(content: ChocolateChipElementArray | HTMLElement | Text | string): ChocolateChipElementArray;
@@ -1039,7 +931,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Insert every element in the set of matched elements to the beginning of the target.
*
* @param target A selector, element, or HTML string. The matched set of elements will be inserted at the beginning of the element specified by this parameter.
* @return HTMLElement[]
*/
prependTo(target: any[] | HTMLElement | string): ChocolateChipElementArray;
@@ -1048,14 +939,11 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
*
* @param target A selector, element, or HTML string. The matched set of elements will be inserted at the end of the element specified by this parameter.
* If no position value is provided it will simply append the content to the target.
* @return HTMLElement[]
*/
appendTo(target: any[] | HTMLElement | string): ChocolateChipElementArray;
/**
* Insert element(s) into the target element.
*
* @return HTMLElement[]
*/
insert(content: string, position?: number | string): ChocolateChipElementArray;
@@ -1063,7 +951,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Create a copy of the set of matched elements.
*
* @param value A Boolean indicating whether to copy the element(s) with their children. A true value copies the children.
* @return HTMLElement[]
*/
clone(value?: boolean): ChocolateChipElementArray;
@@ -1071,14 +958,11 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Wrap an HTML structure around each element in the set of matched elements.
*
* @param wrappingElement A selector or HTML string specifying the structure to wrap around the matched elements.
* @return HTMLElement[]
*/
wrap(wrappingElement: string): ChocolateChipElementArray;
/**
* Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.
*
* @return HTMLElement[]
*/
unwrap(): ChocolateChipElementArray;
@@ -1086,21 +970,17 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Remove the set of matched elements from the DOM. If there are any attached events, this will remove them to prevent memory leaks.
*
* @param selector A selector expression that filters the set of matched elements to be removed.
* @return HTMLElement[]
*/
remove(selector?: string): ChocolateChipElementArray;
/**
* Remove all child nodes of the set of matched elements from the DOM.
*
* @return HTMLElement[]
*/
empty(): ChocolateChipElementArray;
/**
* Get an object of the current coordinates of the first element in the set of matched elements, relative to the document.
* These are: top, left, bottom and right. The values are numbers representing pixel values.
* @return Object
*/
offset(): {
top: number;
@@ -1112,23 +992,17 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
/**
* Get the current computed width for the first element in the set of matched elements,
* including padding but excluding borders.
*
* @return number
*/
width(): number;
/**
* Get the current computed height for the first element in the set of matched elements,
* including padding but excluding borders.
*
* @return number
*/
height(): number;
/**
* Get the combined text contents of each element in the set of matched elements, including their descendants.
*
* @return string
* Get the combined text contents of each element in the set of matched elements, including their descendants
*/
text(): string;
@@ -1139,7 +1013,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* The text to set as the content of each matched element.
* When Number is supplied, it will be converted to a String representation.
* To delete text, use ChocolateChipElementArray.empty() or ChocolateChipElementArray.remove().
* @return HTMLElement
*/
text(text: string | number): HTMLElement;
@@ -1149,7 +1022,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* @param options And object of key value pairs define the CSS properties and values to animate.
* @param duration A string representing the time. Should have a time identifier: "200s", "200ms", etc.
* @param easing A string indicating the easing for the animation, such as "ease-out", "ease-in", "ease-in-out".
* @return void
*/
animate(options: Object, duration?: string, easing?: string): void;
@@ -1159,7 +1031,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names.
* @param handler A function to execute each time the event is triggered.
* @param useCapture Setting the third argument to true will trigger event bubbling. The default is false.
* @return ChocolateChipStatic
*/
bind(eventType: string, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic;
@@ -1169,7 +1040,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names.
* @param handler A function to execute each time the event is triggered.
* @param useCapture Setting the third argument to true will trigger event bubbling. The default is false.
* @return ChocolateChipStatic
*/
unbind(eventType?: string, handler?: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic;
@@ -1181,7 +1051,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* @param handler A function to execute each time the event is triggered. The keyword "this" will refer
* to the element receiving the event.
* @param useCapture Setting the third argument to true will trigger event bubbling. The default is false.
* @return ChocolateChipStatic
*/
delegate(selector: any, eventType: string, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic;
@@ -1192,7 +1061,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names.
* @param handler A function handler assigned to this event.
* @param useCapture Setting the third argument to true will trigger event bubbling. The default is false.
* @return ChocolateChipStatic
*/
undelegate(selector?: any, eventType?: string, handler?: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic;
@@ -1203,7 +1071,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* @param selector A string defining the descendant elements are listening for the event.
* @param handler A function handler assigned to this event.
* @param useCapture Setting the third argument to true will trigger event bubbling. The default is false.
* @return ChocolateChipStatic
*/
on(eventType: string, selector: any, handler?: (eventObject: Event) => any, capturePhase?: boolean): ChocolateChipStatic;
@@ -1215,7 +1082,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* @param selector A string defining the descendant elements are listening for the event.
* @param handler A function handler assigned to this event.
* @param useCapture Setting the third argument to true will trigger event bubbling. The default is false.
* @return ChocolateChipStatic
*/
off(eventType?: string, selector?: any, handler?: (eventObject: Event) => any, capturePhase?: boolean): ChocolateChipStatic;
@@ -1223,7 +1089,6 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* Trigger an event on an element.
*
* @param eventType The event to trigger.
* @return void
*/
trigger(eventType: string): void;
}
+5 -1
View File
@@ -7,6 +7,10 @@
"dt-header": false,
"no-any-union": false,
"unified-signatures": false,
"no-unnecessary-generics": false
"no-unnecessary-generics": false,
// TODO: left in redundant jsdoc that conflicts with type declarations
// Need to go over each and decide whether the jsdoc or type is correct
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false
}
}
+2 -5
View File
@@ -1,4 +1,4 @@
// Type definitions for chokidar 1.7.1
// Type definitions for chokidar 1.7
// Project: https://github.com/paulmillr/chokidar
// Definitions by: Stefan Steinhart <https://github.com/reppners>
// Felix Becker <https://github.com/felixfbecker>
@@ -19,7 +19,6 @@ export interface WatchedPaths {
}
export class FSWatcher extends EventEmitter implements fs.FSWatcher {
/**
* Constructs a new FSWatcher instance with optional WatchOptions parameter.
*/
@@ -52,7 +51,6 @@ export class FSWatcher extends EventEmitter implements fs.FSWatcher {
}
export interface WatchOptions {
/**
* Indicates whether the process should continue to run as long as files are being watched. If
* set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`,
@@ -86,7 +84,7 @@ export interface WatchOptions {
* be relative to this.
*/
cwd?: string;
/**
* If set to true then the strings passed to .watch() and .add() are treated as literal path
* names, even if they look like globs. Default: false.
@@ -155,7 +153,6 @@ export interface WatchOptions {
}
export interface AwaitWriteFinishOptions {
/**
* Amount of time in milliseconds for a file size to remain constant before emitting its event.
*/
+1 -79
View File
@@ -1,79 +1 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}
{ "extends": "dtslint/dt.json" }
+28 -1
View File
@@ -1,6 +1,6 @@
// Type definitions for Chrome packaged application development
// Project: http://developer.chrome.com/apps/
// Definitions by: Adam Lay <https://github.com/AdamLay>, MIZUNE Pine <https://github.com/pine613>, MIZUSHIMA Junki <https://github.com/mzsm>, Ingvar Stepanyan <https://github.com/RReverser>
// Definitions by: Adam Lay <https://github.com/AdamLay>, MIZUNE Pine <https://github.com/pine613>, MIZUSHIMA Junki <https://github.com/mzsm>, Ingvar Stepanyan <https://github.com/RReverser>, Adam Pyle <https://github.com/pyle>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="index.d.ts"/>
@@ -21,12 +21,39 @@ declare namespace chrome.app {
// App Runtime
////////////////////
declare namespace chrome.app.runtime {
enum LaunchSource {
"untracked" = "untracked",
"app_launcher" = "app_launcher",
"new_tab_page" = "new_tab_page",
"reload" = "reload",
"restart" = "restart",
"load_and_launch" = "load_and_launch",
"command_line" = "command_line",
"file_handler" = "file_handler",
"url_handler" = "url_handler",
"system_tray" = "system_tray",
"about_page" = "about_page",
"keyboard" = "keyboard",
"extensions_page" = "extensions_page",
"management_api" = "management_api",
"ephemeral_app" = "ephemeral_app",
"background" = "background",
"kiosk" = "kiosk",
"chrome_internal" = "chrome_internal",
"test" = "test",
"installed_notification" = "installed_notification",
"context_menu" = "context_menu",
}
interface LaunchData {
id?: string;
items?: LaunchDataItem[];
url?: string;
referrerUrl?: string;
isKioskSession?: boolean;
isPublicSession?: boolean;
source?: LaunchSource;
actionData?: {};
}
interface LaunchDataItem {
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: http://developer.chrome.com/extensions/
// Definitions by: Matthew Kimber <https://github.com/matthewkimber>, otiai10 <https://github.com/otiai10>, couven92 <https://github.com/couven92>, RReverser <https://github.com/rreverser>, sreimer15 <https://github.com/sreimer15>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// TypeScript Version: 2.4
/// <reference types="filesystem" />
@@ -0,0 +1,22 @@
import clamp, { ClampOptions, ClampResponse } from 'clamp-js-main';
const element: HTMLElement = document.createElement('div');
element.style.setProperty('width', '5px');
element.style.setProperty('height', '5px');
element.style.setProperty('font-size', '12px');
const span: HTMLSpanElement = document.createElement('span');
span.textContent = "Lorem ipsum. Lorem ipsum";
element.appendChild(span);
const simpleClamp: ClampResponse = clamp(element);
const options: ClampOptions = {
clamp: 2,
useNativeClamp: false,
splitOnChars: ['.'],
animate: true,
truncationChar: '--',
truncationHTML: '<span></span>'
};
const clampWithOptions: ClampResponse = clamp(element, options);
+20
View File
@@ -0,0 +1,20 @@
// Type definitions for clamp-js-main 0.11
// Project: https://github.com/jmenglis/clamp-js-main#readme
// Definitions by: Sinziana Nicolae <https://github.com/sinziananicolae>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export interface ClampOptions {
clamp?: number|string;
useNativeClamp?: boolean;
splitOnChars?: string[];
animate?: boolean;
truncationChar?: string;
truncationHTML?: string | null;
}
export interface ClampResponse {
original: string;
clamped: string;
}
export default function clamp(element: HTMLElement, options?: ClampOptions): ClampResponse;
+24
View File
@@ -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",
"clamp-js-main-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+108
View File
@@ -0,0 +1,108 @@
import * as coinbase from "coinbase";
const client = new coinbase.Client({ apiKey: "key", apiSecret: "secret", version: "2017-10-22" });
client.getAccounts({}, (error: Error, result: coinbase.Account[]): void => undefined);
client.getAccount("abcdef", (error: Error, account: coinbase.Account): void => {
account.buy({ amount: "1", commit: false, currency: "BTC", payment_method: "abcdef" }, (error: Error, buy: coinbase.Buy): void => {
buy.commit((error: Error, buy: coinbase.Buy): void => undefined);
});
account.createAddress({ name: "foo" }, (error: Error, address: coinbase.Address): void => {
address.getTransactions({}, (error: Error, transactions: coinbase.Transaction[]): void => undefined);
});
account.delete((error: Error): void => undefined);
account.deposit({ amount: "1", commit: false, currency: "USD", payment_method: "abcdef" }, (error: Error, deposit: coinbase.Deposit): void => {
deposit.commit((error: Error, deposit: coinbase.Deposit): void => undefined);
});
account.getAddress("abcdef", (error: Error, address: coinbase.Address): void => undefined);
account.getAddresses((error: Error, address: coinbase.Address[]): void => undefined);
account.getBuy("abcdef", (error: Error, buy: coinbase.Buy): void => undefined);
account.getBuys((error: Error, buy: coinbase.Buy[]): void => undefined);
account.getDeposit("abcdef", (error: Error, deposit: coinbase.Deposit): void => undefined);
account.getDeposits((error: Error, deposit: coinbase.Deposit[]): void => undefined);
account.getSell("abcdef", (error: Error, deposit: coinbase.Sell): void => undefined);
account.getSells((error: Error, deposit: coinbase.Sell[]): void => undefined);
account.getTransaction("abcdef", (error: Error, deposit: coinbase.Transaction): void => undefined);
account.getTransactions((error: Error, deposit: coinbase.Transaction[]): void => undefined);
account.getWithdrawal("abcdef", (error: Error, deposit: coinbase.Withdrawal): void => undefined);
account.getWithdrawals((error: Error, deposit: coinbase.Withdrawal[]): void => undefined);
account.requestMoney(
{ amount: "1", currency: "EUR", description: "foo", to: "bar", type: "request" },
(error: Error, result: coinbase.Transaction) => undefined
);
account.requestMoney({ amount: "1", currency: "EUR", to: "bar", type: "request" }, (error: Error, tx: coinbase.Transaction) => {
tx.cancel((error: Error, tx: coinbase.Transaction): void => undefined);
tx.complete((error: Error, tx: coinbase.Transaction): void => undefined);
tx.resend((error: Error, tx: coinbase.Transaction): void => undefined);
});
account.sell(
{ agree_btc_amount_varies: true, amount: "1", commit: true, currency: "BTC", payment_method: "abcdef", quote: true},
(error: Error, sell: coinbase.Sell): void => {
sell.commit((error: Error, sell: coinbase.Sell): void => undefined);
}
);
account.sell(
{ currency: "BTC", payment_method: "abcdef", total: "3"},
(error: Error, sell: coinbase.Sell): void => {
sell.commit((error: Error, sell: coinbase.Sell): void => undefined);
}
);
account.sendMoney(
{ amount: "1", currency: "EUR", description: "foo", fee: "2", idem: "bar", to: "baz", type: "send" },
(error: Error, result: coinbase.Transaction) => undefined
);
account.setPrimary((error: Error, result: coinbase.Account): void => undefined);
account.transferMoney(
{ amount: "1", currency: "USD", description: "foo", to: "bar", type: "transfer" },
(error: Error, tx: coinbase.Transaction): void => undefined
);
account.update({ name: "foo" }, (error: Error, result: coinbase.Account): void => undefined);
account.withdraw({ amount: "1", commit: false, currency: "ETH", payment_method: "abcdef"}, (error: Error, result: coinbase.Withdrawal): void => {
result.commit((error: Error, result: coinbase.Withdrawal): void => undefined);
});
});
client.getBuyPrice({ currencyPair: "USD-BTC" }, (error: Error, result: coinbase.MoneyHash): void => undefined);
client.getCurrencies((error: Error, result: coinbase.Currency[]): void => undefined);
client.getExchangeRates({currency: "ETC"}, (error: Error, result: coinbase.ExchangeRate): void => undefined);
client.getPaymentMethod("foo", (error: Error, result: coinbase.PaymentMethod): void => undefined);
client.getPaymentMethods((error: Error, result: coinbase.PaymentMethod[]): void => undefined);
client.getSellPrice({ currencyPair: "USD-BTC" }, (error: Error, result: coinbase.MoneyHash): void => undefined);
client.getSpotPrice({ currencyPair: "USD-BTC" }, (error: Error, result: coinbase.MoneyHash): void => undefined);
client.getSpotPrice({ currencyPair: "USD-BTC", date: "2017-22-01" }, (error: Error, result: coinbase.MoneyHash): void => undefined);
client.getTime((error: Error, result: coinbase.Time): void => undefined);
client.getUser("abcdef", (error: Error, user: coinbase.User): void => {
user.showAuth((error: Error, auth: coinbase.Auth): void => undefined);
user.update({ name: "foo", time_zone: "bar", native_currency: "USD" }, (error: Error, user: coinbase.User): void => undefined);
});
+1333
View File
File diff suppressed because it is too large Load Diff
+23
View File
@@ -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",
"coinbase-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1 -1
View File
@@ -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;
/**
-99
View File
@@ -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] <file ...>')
.option('-i, --integer <n>', 'An integer argument', parseInt)
.option('-f, --float <n>', 'A float argument', parseFloat)
.option('-r, --range <a>..<b>', 'A range', range)
.option('-l, --list <items>', '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('<cmd> [env]')
.action((cmd, env) => {
console.log(cmd, env);
});
program.parse(process.argv);
console.log('stuff');
-299
View File
@@ -1,299 +0,0 @@
// Type definitions for commander 2.11
// Project: https://github.com/visionmedia/commander.js
// Definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
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 <path>', 'change the working directory')
* .option('-c, --config <path>', '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 <cmd>')
* .description('run the given remote command')
* .action(function(cmd) {
* console.log('exec "%s"', cmd);
* });
*
* program
* .command('teardown <dir> [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 <path>', '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;

Some files were not shown because too many files have changed in this diff Show More