This commit is contained in:
AJ Richardson
2018-04-14 16:11:10 -04:00
1400 changed files with 148689 additions and 56695 deletions
+5
View File
@@ -1,2 +1,7 @@
# Auto detect text files and perform LF normalization
* text=auto
# Checkout NPM package files with forced LF lineendings
# to prevent git conflicts when running npm commands
package.json text eol=lf
package-lock.json text eol=lf
+257 -121
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -10,7 +10,7 @@ Please fill in this template.
Select one of these and delete the others:
If adding a new definition:
- [ ] The package does not provide its own types, and you can not add them.
- [ ] The package does not already provide its own types, or cannot have its `.d.ts` files generated via `--declaration`
- [ ] If this is for an NPM package, match the name. If not, do not conflict with the name of an NPM package.
- [ ] Create it with `dts-gen --dt`, not by basing it on an existing project.
- [ ] `tslint.json` should be present, and `tsconfig.json` should have `noImplicitAny`, `noImplicitThis`, `strictNullChecks`, and `strictFunctionTypes` set to `true`.
+3 -2
View File
@@ -105,7 +105,7 @@ If it doesn't, you can do so yourself in the comment associated with the PR.
#### Create a new package
If you are the library author, or can make a pull request to the library, [bundle types](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) instead of publishing to DefinitelyTyped.
If you are the library author and your package is written in TypeScript, [bundle the autogenerated declaration files](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) in your package instead of publishing to DefinitelyTyped.
If you are adding typings for an NPM package, create a directory with the same name.
If the package you are adding typings for is not on NPM, make sure the name you choose for it does not conflict with the name of a package on NPM.
@@ -239,7 +239,8 @@ If types are part of a web standard, they should be contributed to [TSJS-lib-gen
#### A package uses `export =`, but I prefer to use default imports. Can I change `export =` to `export default`?
If default imports work in your environment, consider turning on the [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) compiler option.
If you are using TypeScript 2.7 or later, use `--esModuleInterop` in your project.
Otherwise, if default imports work in your environment (e.g. Webpack, SystemJS, esm), consider turning on the [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) compiler option.
Do not change the type definition if it is accurate.
For an NPM package, `export =` is accurate if `node -p 'require("foo")'` is the export, and `export default` is accurate if `node -p 'require("foo").default'` is the export.
-35
View File
@@ -1,35 +0,0 @@
// Type definitions for glue
// Project: https://github.com/hapijs/glue
// Definitions by: Gareth Parker
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.7
declare module "glue" {
import { Server, ServerOptions } from "hapi";
export interface Options {
relativeTo: string;
preConnections?: (Server:Server, next:(err:any)=>void ) => void;
preRegister?: (Server:Server, next:(err:any)=>void ) => void;
}
interface Plugin {
plugin: string | {
register:string;
options?:any;
};
options?: any;
routes?: any
}
interface Manifest {
server: ServerOptions;
register?: {
plugins: Array<Plugin>
}
}
export function compose(manifest: Manifest, options?: Options): Server;
}
+19 -1
View File
@@ -174,7 +174,7 @@
"sourceRepoURL": "https://github.com/MikeMcl/bignumber.js/",
"asOfVersion": "5.0.0"
},
{
{
"libraryName": "bingmaps",
"typingsPackageName": "bingmaps",
"sourceRepoURL": "https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions",
@@ -210,6 +210,12 @@
"sourceRepoURL": "https://github.com/blakeembrey/camel-case",
"asOfVersion": "1.2.1"
},
{
"libraryName": "catalog",
"typingsPackageName": "catalog",
"sourceRepoURL": "https://github.com/interactivethings/catalog",
"asOfVersion": "3.5.0"
},
{
"libraryName": "chalk",
"typingsPackageName": "chalk",
@@ -234,6 +240,12 @@
"sourceRepoURL": "https://github.com/saltyrtc/chunked-dc-js",
"asOfVersion": "0.2.2"
},
{
"libraryName": "colors.js (colors)",
"typingsPackageName": "colors",
"sourceRepoURL": "https://github.com/Marak/colors.js",
"asOfVersion": "1.2.1"
},
{
"libraryName": "commander",
"typingsPackageName": "commander",
@@ -1266,6 +1278,12 @@
"sourceRepoURL": "https://github.com/router5/router5",
"asOfVersion": "5.0.0"
},
{
"libraryName": "rrule",
"typingsPackageName": "rrule",
"sourceRepoURL": "https://github.com/jakubroztocil/rrule",
"asOfVersion": "2.2.9"
},
{
"libraryName": "rvo2",
"typingsPackageName": "rvo2",
+332 -5
View File
@@ -1,6 +1,7 @@
import * as express from 'express';
import { BasicCard, Carousel, ImageDisplays, List, OptionItem, RichResponse } from './response-builder';
import { BasicCard, BrowseCarousel, BrowseItem, Carousel, ImageDisplays, List, MediaObject,
MediaResponse, MediaValues, OptionItem, RichResponse, SimpleResponse } from './response-builder';
import { ActionPaymentTransactionConfig, Cart, GooglePaymentTransactionConfig, LineItem,
Location, Order, OrderUpdate, TransactionDecision, TransactionValues } from './transactions';
@@ -30,6 +31,8 @@ export enum StandardIntents {
DELIVERY_ADDRESS,
/** App fires TRANSACTION_DECISION intent when action asks for transaction decision. */
TRANSACTION_DECISION,
/** App fires PLACE intent when action asks for place. */
PLACE,
/** App fires CONFIRMATION intent when requesting affirmation from user. */
CONFIRMATION,
/** App fires DATETIME intent when requesting date/time from user. */
@@ -45,7 +48,11 @@ export enum StandardIntents {
/** App fires REGISTER_UPDATE intent when requesting user to register for proactive updates. */
REGISTER_UPDATE,
/** App receives CONFIGURE_UPDATES intent to indicate a REGISTER_UPDATE intent should be sent. */
CONFIGURE_UPDATES
CONFIGURE_UPDATES,
/** App fires LINK intent to request user to open to link. */
LINK,
/** App receives MEDIA_STATUS intent when the MediaResponse status is updated from user. */
MEDIA_STATUS
}
/**
@@ -101,6 +108,10 @@ export enum BuiltInArgNames {
* Transactions decision argument.
*/
TRANSACTION_DECISION_VALUE,
/**
* Place value argument.
*/
PLACE,
/**
* Confirmation argument.
*/
@@ -126,7 +137,11 @@ export enum BuiltInArgNames {
*/
NEW_SURFACE,
/** Update registration value argument. */
REGISTER_UPDATE
REGISTER_UPDATE,
/** Link request result argument. */
LINK,
/** MediaStatus value argument. */
MEDIA_STATUS
}
/**
@@ -173,6 +188,14 @@ export enum SurfaceCapabilities {
* The ability to output on a screen
*/
SCREEN_OUTPUT,
/**
* The ability to output a MediaResponse
*/
MEDIA_RESPONSE_AUDIO,
/**
* The ability to open a web URL
*/
WEB_BROWSER
}
/**
@@ -223,6 +246,18 @@ export enum SignInStatus {
ERROR
}
/**
* SKU (Stock Keeping Units) types for Play Package Entitlements.
*/
export enum EntitlementSkuTypes {
/** In app purchase */
IN_APP,
/** In app subscription */
SUBSCRIPTION,
/** Paid app. */
APP
}
/**
* Possible update trigger time context frequencies.
*/
@@ -259,10 +294,15 @@ export interface UserName {
familyName: string;
}
export interface LocationCoordinates {
latitude: number;
longitude: number;
}
/**
* User's permissioned device location.
* Location information.
*/
export interface DeviceLocation {
export interface Location {
/** Coordinates: {latitude, longitude}. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */
coordinates: Coordinates;
/** Full, formatted street address. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */
@@ -273,6 +313,22 @@ export interface DeviceLocation {
city: string;
}
/**
* User's permissioned device location.
*/
export type DeviceLocation = Location;
/**
* Place information.
*/
export interface Place extends Location {
/**
* Used with Places API to fetch details of a place.
* See {@link https://developers.google.com/places/web-service/place-id}
*/
placeId: string;
}
/**
* Coordinates containing latitude and longitude
*/
@@ -309,6 +365,33 @@ export interface User {
userStorage: string;
}
/**
* Google Play Android App Package Entitlements.
*/
export interface PackageEntitlement {
/** Name of the Android app package. */
packageName: string;
/** List of entitlements for a given app. */
entitlements: Entitlement[];
}
/**
* A user's digital entitlement.
*/
export interface Entitlement {
/** Product SKU. Matches getSku() in Google Play InApp Billing API. */
sku: string;
/** The type of SKU. One of EntitlementSkuType. */
skuType: string;
/** For in app purchases/subscriptions, relevant details. */
inAppDetails: {
/** JSON data of the in app purchase. */
inAppPurchaseData: object;
/** Matches IN_APP_DATA_SIGNATURE from getPurchases() method in Play InApp Billing API. */
inAppDataSignature: object;
};
}
/**
* Actions on Google Surface.
*/
@@ -437,6 +520,16 @@ export class AssistantApp {
*/
readonly Transactions: typeof TransactionValues;
/**
* Values related to supporting {@link Media}.
*/
readonly Media: typeof MediaValues;
/**
* SKU (Stock Keeping Units) types for Play Package Entitlements.
*/
readonly EntitlementSkuTypes: typeof EntitlementSkuTypes;
/**
* Possible update trigger time context frequencies.
*/
@@ -923,6 +1016,80 @@ export class AssistantApp {
*/
askForDeliveryAddress(reason: string, dialogState?: object): express.Response | null;
/**
* Asks user to provide a geo-located place, possibly using contextual information,
* like a store near the user's location or a contact's address.
*
* Developer provides custom text prompts to tailor the request handled by Google.
*
* @example
* // For DialogflowApp:
*
* // Dialogflow Actions
* const Actions = {
* WELCOME: 'input.welcome',
* PLACE: 'get.place' // Create Dialogflow Action with actions_intent_PLACE event
* };
*
* const app = new DialogflowApp({request, response});
*
* function handleWelcome (app) {
* const requestPrompt = 'Where do you want to get picked up?';
* const permissionContext = 'To find a place to pick you up';
* app.askForPlace(requestPrompt, permissionContext);
* }
*
* function handlePlace (app) {
* const place = app.getPlace();
* if (place) {
* app.tell(`Ah, I see. You want to get picked up at ${place.address}`);
* } else {
* app.tell(`Sorry, I couldn't find where you want to get picked up`);
* }
* }
*
* const actionMap = new Map();
* actionMap.set(Actions.WELCOME, handleWelcome);
* actionMap.set(Actions.PLACE, handlePlace);
* app.handleRequest(actionMap);
*
* // For ActionsSdkApp:
* const app = new ActionsSdkApp({ request, response });
*
* function handleWelcome (app) {
* const requestPrompt = 'Where do you want to get picked up?';
* const permissionContext = 'To find a place to pick you up';
* app.askForPlace(requestPrompt, permissionContext);
* }
*
* function handlePlace (app) {
* const place = app.getPlace();
* if (place) {
* app.tell(`Ah, I see. You want to get picked up at ${place.address}`);
* } else {
* app.tell(`Sorry, I couldn't find where you want to get picked up`);
* }
* }
*
* const actionsMap = new Map();
* actionsMap.set(app.StandardIntents.MAIN, handleWelcome);
* actionsMap.set(app.StandardIntents.PLACE, handlePlace);
* app.handleRequest(actionsMap);
*
* @param requestPrompt This is the initial response by location sub-dialog.
* For example: "Where do you want to get picked up?"
* @param permissionContext This is the context for seeking permissions.
* For example: "To find a place to pick you up"
* Prompt to user: "*To find a place to pick you up*, I just need to check your location.
* Can I get that from Google?".
* @param dialogState JSON object the app uses to hold dialog state that
* will be circulated back by Assistant.
* @return HTTP response.
* @actionssdk
* @dialogflow
*/
askForPlace(requestPrompt: string, permissionContext: string, dialogState?: object): express.Response | null;
/**
* Asks user for a confirmation.
*
@@ -1131,6 +1298,72 @@ export class AssistantApp {
*/
askToRegisterDailyUpdate(intent: string, intentArguments: IntentArgument[], dialogState?: object): express.Response | null;
/**
* Requests the user to transfer to a linked out Android app intent. Using this feature
* requires verifying the linked app in the (Actions console)[console.actions.google.com].
*
* @example
* // For DialogflowApp:
*
* // Dialogflow Actions
* const WELCOME_ACTION = 'input.welcome';
* const HANDLE_LINK = 'handle.link'; // Create Dialogflow Action with actions_intent_LINK event
*
* const app = new DialogflowApp({ request, response });
*
* console.log('Request headers: ' + JSON.stringify(request.headers));
* console.log('Request body: ' + JSON.stringify(request.body));
*
* function requestLink (app) {
* app.askToDeepLink('Great! Looks like we can do that in the app.', 'Google',
* 'example://gizmos', 'com.example.gizmos', 'handle this for you');
* }
*
* function handleLink (app) {
* const linkStatus = app.getLinkStatus();
* app.tell('Okay maybe we can take care of that another time.');
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_ACTION, requestLink);
* actionMap.set(HANDLE_LINK, handleLink);
* app.handleRequest(actionMap);
*
* // For ActionsSdkApp
* const app = new ActionsSdkApp({ request, response });
*
* console.log('Request headers: ' + JSON.stringify(request.headers));
* console.log('Request body: ' + JSON.stringify(request.body));
*
* function requestLink (app) {
* app.askToDeepLink('Great! Looks like we can do that in the app.', 'Google',
* 'example://gizmos', 'com.example.gizmos', 'handle this for you.');
* }
*
* function handleLink (app) {
* const linkStatus = app.getLinkStatus();
* app.tell('Okay maybe we can take care of that another time.');
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.MAIN, requestLink);
* actionMap.set(app.StandardIntents.LINK, handleLink);
* app.handleRequest(actionMap);
*
* @param prompt A simple response to prepend to the link request.
* @param destinationName The name of the link destination.
* @param url URL of Android deep link.
* @param packageName Android app package name to which to link.
* @param reason The reason to transfer the user. This may be appended to a
* Google-specified prompt.
* @param dialogState JSON object the app uses to hold dialog state that
* will be circulated back by Assistant. Used in {@link ActionsSdkApp}.
* @return HTTP response.
* @dialogflow
* @actionssdk
*/
askToDeepLink(prompt: string | SimpleResponse | null, destinationName: string, url: string, packageName: string, reason?: string | null, dialogState?: object): express.Response | null;
/**
* Gets the {@link User} object.
* The user object contains information about the user, including
@@ -1209,6 +1442,20 @@ export class AssistantApp {
*/
getLastSeen(): Date | null;
/**
* Get the the list of all digital goods that your user purchased from
* your published Android apps. To enable this feature, see the instructions
* in the (documentation)[https://developers.google.com/actions/identity/digital-goods].
*
* @example
* const app = new DialogflowApp({request, response});
* const packageEntitlements = app.getPackageEntitlements();
*
* @return The list of digital goods purchased by the user in
* any verified Android app package. Null if no Package Entitlements present in the request.
*/
getPackageEntitlements(): PackageEntitlement[] | null;
/**
* If granted permission to device's location in previous intent, returns device's
* location (see {@link AssistantApp#askForPermissions|askForPermissions}).
@@ -1273,6 +1520,15 @@ export class AssistantApp {
*/
getTransactionDecision(): TransactionDecision;
/**
* Gets the user provided place. Use after askForPlace.
*
* @return Place information given by the user. Null if no place given.
* @dialogflow
* @actionssdk
*/
getPlace(): Place | null;
/**
* Gets confirmation decision. Use after askForConfirmation.
*
@@ -1304,6 +1560,31 @@ export class AssistantApp {
*/
getSignInStatus(): string;
/**
* Get status of MEDIA_STATUS intent.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
*
* function mediaStatusIntent (app) {
* const status = app.getMediaStatus();
* if (status === app.Media.Status.FINISHED) {
* app.tell('Oh, I see you are done playing the media!');
* } else {
* app.tell(`I don't understand the current media status: ${status}`);
* }
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.MEDIA_STATUS, mediaStatusIntent);
* app.handleRequest(actionMap);
*
* @return Result of media status intent.
* @dialogflow
* @actionssdk
*/
getMediaStatus(): MediaValues.Status | null;
/**
* Returns true if user device has a given surface capability.
*
@@ -1464,6 +1745,16 @@ export class AssistantApp {
*/
isUpdateRegistered(): boolean;
/**
* Returns the status of a link request. Used with
* {@link AssistantApp#askToDeepLink}
*
* @return The status code of the request to link.
* @dialogflow
* @actionssdk
*/
getLinkStatus(): number;
// ---------------------------------------------------------------------------
// Response Builders
// ---------------------------------------------------------------------------
@@ -1500,6 +1791,13 @@ export class AssistantApp {
*/
buildCarousel(): Carousel;
/**
* Constructs a Browse Carousel with chainable property setters.
*
* @return Constructed Browse Carousel.
*/
buildBrowseCarousel(): BrowseCarousel;
/**
* Constructs OptionItem with chainable property setters.
*
@@ -1512,6 +1810,15 @@ export class AssistantApp {
*/
buildOptionItem(key?: string, synonyms?: string | string[]): OptionItem;
/**
* Constructs BrowseItem for the Browse Carousel with chainable property setters.
*
* @param title The displayed title of the Browse Carousel card.
* @param url The URL linked to by clicking the card.
* @return Constructed BrowseItem.
*/
buildBrowseItem(title?: string, url?: string): BrowseItem;
// ---------------------------------------------------------------------------
// Transaction Builders
// ---------------------------------------------------------------------------
@@ -1552,4 +1859,24 @@ export class AssistantApp {
* @return Constructed OrderUpdate.
*/
buildOrderUpdate(orderId: string, isGoogleOrderId: boolean): OrderUpdate;
// ---------------------------------------------------------------------------
// Media Builders
// ---------------------------------------------------------------------------
/**
* Constructs Media Response with chainable property setters.
*
* @return Constructed Media Response.
*/
buildMediaResponse(): MediaResponse;
/**
* Constructs MediaObject with chainable property setters.
*
* @param name Name of media file.
* @param contentUrl Location of media file.
* @return Constructed MediaObject.
*/
buildMediaObject(name: string, contentUrl: string): MediaObject;
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for actions-on-google 1.8
// Type definitions for actions-on-google 1.10
// Project: https://github.com/actions-on-google/actions-on-google-nodejs
// Definitions by: Joel Hegg <https://github.com/joelhegg>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+298
View File
@@ -27,6 +27,53 @@ export enum ImageDisplays {
CROPPED
}
/**
* Values related to supporting media.
*/
export namespace MediaValues {
/**
* Type of the media within a MediaResponse.
*/
enum Type {
/**
* Unspecified.
*/
MEDIA_TYPE_UNSPECIFIED,
/**
* Audio stream.
*/
AUDIO
}
/**
* List of media control status' returned.
*/
enum Status {
/**
* Unspecified.
*/
UNSPECIFIED,
/**
* Finished.
*/
FINISHED
}
/**
* List of possible item types.
*/
enum ImageType {
/**
* Icon.
*/
ICON,
/**
* Large image.
*/
LARGE
}
}
/**
* Simple Response type.
*/
@@ -155,6 +202,22 @@ export class RichResponse {
*/
addBasicCard(basicCard: BasicCard): RichResponse;
/**
* Adds media to this response.
*
* @param mediaResponse MediaResponse to include in response.
* @return Returns current constructed RichResponse.
*/
addMediaResponse(mediaResponse: MediaResponse): RichResponse;
/**
* Adds a Browse Carousel to list of items.
*
* @param browseCarousel Browse Carousel to present to user
* @return Returns current constructed RichResponse.
*/
addBrowseCarousel(browseCarousel: string | BrowseCarousel): RichResponse;
/**
* Adds a single suggestion or list of suggestions to list of items.
*
@@ -325,6 +388,43 @@ export class List {
addItems(optionItems: OptionItem | OptionItem[]): List;
}
/**
* Class for initializing and constructing BrowseCarousel with chainable interface.
*/
export class BrowseCarousel {
/**
* Constructor for BrowseCarousel. Accepts optional BrowseCarousel to
* clone or list of items to copy.
*
* @param carousel Either a carousel to clone
* or an array of BrowseItem to initialize a new carousel
*/
constructor(carousel?: BrowseCarousel | BrowseItem[]);
/**
* List of 2-20 items to show in this carousel. Required.
*/
items: BrowseItem[];
/**
* Adds a single item or list of items to the carousel.
*
* @param browseItems BrowseItems to add.
* @return Returns current constructed BrowseCarousel.
*/
addItems(browseItems: BrowseItem | BrowseItem[]): BrowseCarousel;
/**
* Sets the display options for the images in this carousel.
* Use one of the image display constants. If none is chosen,
* ImageDisplays.DEFAULT will be enforced.
*
* @param option The option for displaying the image.
* @return Returns current constructed BrowseCarousel.
*/
setImageDisplay(option: ImageDisplays): BrowseCarousel;
}
/**
* Class for initializing and constructing Carousel with chainable interface.
*/
@@ -350,6 +450,120 @@ export class Carousel {
* @return Returns current constructed Carousel.
*/
addItems(optionItems: OptionItem | OptionItem[]): Carousel;
/**
* Sets the display options for the images in this carousel.
* Use one of the image display constants. If none is chosen,
* ImageDisplays.DEFAULT will be enforced.
*
* @param option The option for displaying the image.
* @return Returns current constructed Carousel.
*/
setImageDisplay(option: ImageDisplays): Carousel;
}
/**
* Class for initializing and constructing Option Items with chainable interface.
*/
export class BrowseItem {
/**
* Constructor for BrowseItem. Accepts a title and URL for the Browse Item
* card.
*
* @param title The title of the Browse Item card.
* @param url The URL of the link opened by clicking the Browse Item card.
*/
constructor(title?: string, url?: string);
/**
* Title of the browse item. Required.
*/
title: string;
/**
* Description text of the item. Optional.
*/
description?: string;
/**
* Footer text of the item. Optional.
*/
footer?: string;
/**
* Image to show on item. Optional.
*/
image?: Image;
/**
* Url to that clicking the card opens. Optional.
*/
openUrlAction?: object;
/**
* @return Returns the possible valid values for URL type hints
*/
urlTypeHints(): object;
/**
* Sets the title for this Browse Item.
*
* @param title Title to show on item.
* @return Returns current constructed BrowseItem.
*/
setTitle(title: string): BrowseItem;
/**
* Sets the description for this Browse Item.
*
* @param description Description to show on item.
* @return Returns current constructed BrowseItem.
*/
setDescription(description: string): BrowseItem;
/**
* Sets the footer for this Browse Item.
*
* @param footerText text to show on item.
* @return Returns current constructed BrowseItem.
*/
setFooter(footerText: string): BrowseItem;
/**
* Sets the image for this Browse Item.
*
* @param url Image source URL.
* @param accessibilityText Text to replace for image for accessibility.
* @param width Width of the image.
* @param height Height of the image.
* @return Returns current constructed BrowseItem.
*/
setImage(url: string, accessibilityText: string, width?: number, height?: number): BrowseItem;
/**
* Sets the Open URL action - which includes the url and possibly the typeHint
*
* @param url Image source URL.
* @param urlTypeHint One of the typeHints enumerated by this.urlTypeHints()
* @return Returns the current constructed BrowseItem
*/
setOpenUrlAction(url: string, urlTypeHint?: string): BrowseItem;
/**
* Sets the URL target of the BrowseItem card
*
* @param url Image source URL.
* @return Returns the current constructed BrowseItem
*/
setUrl(url: string): BrowseItem;
/**
* Sets the URL type hint for the BrowseItem card
*
* @param urlTypeHint One of the typeHints enumerated by this.urlTypeHints()
* @return Returns the current constructed BrowseItem
*/
setUrlTypeHint(urlTypeHint: string): BrowseItem;
}
/**
@@ -430,6 +644,90 @@ export class OptionItem {
addSynonyms(synonyms: string | string[]): OptionItem;
}
/**
* Class for initializing and constructing MediaResponse with chainable interface.
*/
export class MediaResponse {
/**
* Constructor for MediaResponse.
* @param mediaType Type of the media which defaults to MediaValues.Type.AUDIO
*/
constructor(mediaType: MediaValues.Type);
/**
* Array of MediaObject held in the MediaResponse.
*/
mediaObjects: MediaObject[];
/**
* Type of the media within this MediaResponse
*/
mediaType: MediaValues.Type;
/**
* Adds a single media file or list of media files to the cart.
*
* @param items Single or Array of MediaObject to add.
* @return Returns current constructed MediaResponse.
*/
addMediaObjects(items: MediaObject | MediaObject[]): MediaResponse;
}
/**
* Class for initializing and constructing MediaObject with chainable interface.
*/
export class MediaObject {
/**
* Constructor for MediaObject.
*
* @param name Name of the MediaObject.
* @param contentUrl URL of the MediaObject.
*/
constructor(name: string, contentUrl: string);
/**
* Name of the MediaObject.
*/
name: string;
/**
* MediaObject URL.
*/
contentUrl: string;
/**
* Description of the MediaObject.
*/
description?: string;
/**
* Large image.
*/
largeImage?: Image;
/**
* Icon image.
*/
icon?: Image;
/**
* Set the description of the item.
*
* @param description Description of the item.
* @return Returns current constructed MediaObject.
*/
setDescription(description: string): MediaObject;
/**
* Sets the image for this item.
*
* @param url Image source URL.
* @param type Type of image (LARGE or ICON).
* @return Returns current constructed MediaObject.
*/
setImage(url: string, type: MediaValues.ImageType): MediaObject;
}
/**
* Check if given text contains SSML.
* @param text Text to check.
+21 -18
View File
@@ -11,6 +11,9 @@ const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
return results;
};
WScript.Echo('Hello, world');
WScript.Quit();
// source -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms630826(v=vs.85).aspx
{
const cd = new ActiveXObject('WIA.CommonDialog');
@@ -51,7 +54,7 @@ const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
{
const dev = cd.ShowSelectDevice();
if (dev) {
collectionToArray(dev.Properties).forEach(p => {
for (const p of collectionToArray(dev.Properties)) {
let s = `${p.Name} (${p.PropertyID}) = `;
if (p.IsVector) {
s += '[vector of data]';
@@ -84,7 +87,7 @@ const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
}
WScript.Echo(s);
});
}
}
}
@@ -112,7 +115,7 @@ const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
{
const img = cd.ShowAcquireImage();
if (img) {
collectionToArray(img.Properties).forEach(p => {
for (const p of collectionToArray(img.Properties)) {
let contents = '';
if (p.IsVector) {
contents = '[vector data not emitted]';
@@ -124,7 +127,7 @@ const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
contents = p.Value;
}
WScript.Echo(`${p.Name} (${p.PropertyID}) = ${contents}`);
});
}
}
}
@@ -133,12 +136,12 @@ const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
const dev = cd.ShowSelectDevice();
if (dev) {
const actionEvent = WIA.WiaEventFlag.ActionEvent;
collectionToArray(dev.Events).forEach(e => {
for (const e of collectionToArray(dev.Events)) {
const msg = (e.Type & actionEvent) === actionEvent ?
`${e.Name} is an Action event` :
`${e.Name} is not an Action event`;
WScript.Echo(msg);
});
}
}
}
@@ -208,14 +211,14 @@ Frame count = ${img.FrameCount}}
// Create an imageprocess object and enumerate filters
{
const ip = new ActiveXObject('WIA.ImageProcess');
collectionToArray(ip.FilterInfos).forEach(fi => {
for (const fi of collectionToArray(ip.FilterInfos)) {
const s = [
fi.Name,
new Array(51).join('='),
fi.Description
].join('\n');
WScript.Echo(s);
});
}
}
// Create an imageprocess object and create one of each available filter
@@ -269,11 +272,11 @@ Frame count = ${img.FrameCount}}
WScript.Echo(s);
};
collectionToArray(ip.FilterInfos).forEach(fi => {
for (const fi of collectionToArray(ip.FilterInfos)) {
ip.Filters.Add(fi.FilterID);
listProperties(ip.Filters(1));
ip.Filters.Remove(1);
});
}
}
// List the supported transfer formats
@@ -308,14 +311,14 @@ Frame count = ${img.FrameCount}}
{
const dev = cd.ShowSelectDevice();
if (dev) {
collectionToArray(dev.Items).forEach(item => {
for (const item of collectionToArray(dev.Items)) {
let s: string = item.Properties("Item Name").Value;
if (item.Properties.Exists("Item Time Stamp")) {
const v: WIA.Vector = item.Properties("Item Time Stamp").Value;
if (v.Count === 8) { s += ` (${v.Date})`; }
}
WScript.Echo(s);
});
}
}
}
@@ -340,16 +343,16 @@ Frame count = ${img.FrameCount}}
}
// List all available devices by name and deviceid
collectionToArray(dm.DeviceInfos).forEach(di => {
for (const di of collectionToArray(dm.DeviceInfos)) {
const name: string = di.Properties("Name").Value;
WScript.Echo(`${name} (${di.DeviceID})`);
});
}
// Display all the properties for the selected device
{
const dev = cd.ShowSelectDevice();
if (dev) {
collectionToArray(dev.Properties).forEach(p => {
for (const p of collectionToArray(dev.Properties)) {
const name = `${p.Name} (${p.PropertyID})`;
let contents: string;
if (p.IsVector) {
@@ -360,7 +363,7 @@ Frame count = ${img.FrameCount}}
contents = p.Value;
}
WScript.Echo(`${name} = ${contents}`);
});
}
}
}
@@ -430,7 +433,7 @@ Frame count = ${img.FrameCount}}
if (args[0] === 'connect') {
const deviceID = args[1].substr(12);
const device = dm.DeviceInfos(deviceID).Connect();
collectionToArray(device.Items).forEach(item => {
for (const item of collectionToArray(device.Items)) {
const img = item.Transfer();
img.SaveFile(`C:\\${item.Properties('Item Name').Value}.${img.FileExtension}`);
@@ -445,7 +448,7 @@ Frame count = ${img.FrameCount}}
WScript.Echo(error);
}
}
});
}
WScript.Quit();
}
break;
+11 -9
View File
@@ -1,10 +1,6 @@
import AuthenticationContext, {
AuthenticationContextOptions,
TokenCallback,
UserCallback
} from "adal-angular";
import AuthenticationContext = require("adal-angular");
const onLogin: TokenCallback = (errorDescription, idToken, error) => {
const onLogin: AuthenticationContext.TokenCallback = (errorDescription, idToken, error) => {
if (error) {
console.error(errorDescription, error);
return;
@@ -14,7 +10,7 @@ const onLogin: TokenCallback = (errorDescription, idToken, error) => {
}
};
const onToken: TokenCallback = (errorDesc, token, error) => {
const onToken: AuthenticationContext.TokenCallback = (errorDesc, token, error) => {
if (error) {
console.error(error);
return;
@@ -22,7 +18,7 @@ const onToken: TokenCallback = (errorDesc, token, error) => {
console.log('Making request with token:', token);
};
const onUser: UserCallback = (error, user) => {
const onUser: AuthenticationContext.UserCallback = (error, user) => {
if (error) {
console.error(error);
return;
@@ -57,7 +53,7 @@ const acquireAnAccessToken = () => {
);
};
const config: AuthenticationContextOptions = {
const config: AuthenticationContext.Options = {
clientId: "7cee0f68-5051-41f6-9e45-80463d21d65d",
redirectUri: "http://localhost:16969/",
instance: "https://login.microsoftonline.com/",
@@ -70,6 +66,7 @@ const config: AuthenticationContextOptions = {
};
const authenticationContext = new AuthenticationContext(config);
window.Logging.level = authenticationContext.CONSTANTS.LOGGING_LEVEL.ERROR;
if (authenticationContext.isCallback(window.location.hash)) {
authenticationContext.handleWindowCallback();
@@ -79,6 +76,11 @@ if (authenticationContext.isCallback(window.location.hash)) {
acquireAnAccessToken();
}
const injectedContext = AuthenticationContext.inject({
clientId: "7cee0f68-5051-41f6-9e45-80463d21d65d",
});
injectedContext.handleWindowCallback();
setTimeout(() => {
authenticationContext.logOut();
}, 60000);
+242 -139
View File
@@ -1,142 +1,28 @@
// Type definitions for adal-angular 1.0
// Project: https://github.com/AzureAD/azure-activedirectory-library-for-js#readme
// Definitions by: Daniel Perez Alvarez <https://github.com/unindented>
// Anthony Ciccarello <https://github.com/aciccarello>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export enum LoggingLevel {
ERROR = 0,
WARNING = 1,
INFO = 2,
VERBOSE = 3
}
// In module contexts the class constructor function is the exported object
export = AuthenticationContext;
export type RequestType = "LOGIN" | "RENEW_TOKEN" | "UNKNOWN";
// This class is defined globally in not in a module context
declare class AuthenticationContext {
instance: string;
config: AuthenticationContext.Options;
callback: AuthenticationContext.TokenCallback;
popUp: boolean;
isAngular: boolean;
export type ResponseType = "id_token token" | "token";
/**
* Enum for request type
*/
REQUEST_TYPE: AuthenticationContext.RequestType;
RESPONSE_TYPE: AuthenticationContext.ResponseType;
CONSTANTS: AuthenticationContext.Constants;
export interface RequestInfo {
/**
* Object comprising of fields such as id_token/error, session_state, state, e.t.c.
*/
parameters: any;
/**
* Request type.
*/
requestType: RequestType;
/**
* Whether state is valid.
*/
stateMatch: boolean;
/**
* Unique guid used to match the response with the request.
*/
stateResponse: string;
/**
* Whether `requestType` contains `id_token`, `access_token` or error.
*/
valid: boolean;
}
export interface UserInfo {
/**
* Username assigned from UPN or email.
*/
userName: string;
/**
* Properties parsed from `id_token`.
*/
profile: any;
}
export type TokenCallback = (
errorDesc: string | null,
token: string,
error: any
) => void;
export type UserCallback = (errorDesc: string | null, user: UserInfo) => void;
export interface AuthenticationContextOptions {
/**
* Client ID assigned to your app by Azure Active Directory.
*/
clientId: string;
/**
* Endpoint at which you expect to receive tokens.Defaults to `window.location.href`.
*/
redirectUri: string;
/**
* Azure Active Directory instance. Defaults to `https://login.microsoftonline.com/`.
*/
instance?: string;
/**
* Your target tenant. Defaults to `common`.
*/
tenant?: string;
/**
* Query parameters to add to the authentication request.
*/
extraQueryParameter?: string;
/**
* Unique identifier used to map the request with the response. Defaults to RFC4122 version 4 guid (128 bits).
*/
correlationId?: string;
/**
* User defined function of handling the navigation to Azure AD authorization endpoint in case of login.
*/
displayCall?: (url: string) => void;
/**
* Set this to true to enable login in a popup winodow instead of a full redirect. Defaults to `false`.
*/
popUp?: boolean;
/**
* Set this to the resource to request on login. Defaults to `clientId`.
*/
loginResource?: string;
/**
* Set this to redirect the user to a custom login page.
*/
localLoginUrl?: string;
/**
* Redirects to start page after login. Defaults to `true`.
*/
navigateToLoginRequestUrl?: boolean;
/**
* Set this to redirect the user to a custom logout page.
*/
logOutUri?: string;
/**
* Redirects the user to postLogoutRedirectUri after logout. Defaults to `redirectUri`.
*/
postLogoutRedirectUri?: string;
/**
* Sets browser storage to either 'localStorage' or sessionStorage'. Defaults to `sessionStorage`.
*/
cacheLocation?: "localStorage" | "sessionStorage";
/**
* Array of keywords or URIs. Adal will attach a token to outgoing requests that have these keywords or URIs.
*/
endpoints?: { [resource: string]: string };
/**
* Array of keywords or URIs. Adal will not attach a token to outgoing requests that have these keywords or URIs.
*/
anonymousEndpoints?: string[];
/**
* If the cached token is about to be expired in the expireOffsetSeconds (in seconds), Adal will renew the token instead of using the cached token. Defaults to 300 seconds.
*/
expireOffsetSeconds?: number;
/**
* The number of milliseconds of inactivity before a token renewal response from AAD should be considered timed out. Defaults to 6 seconds.
*/
loadFrameTimeout?: number;
/**
* Callback to be invoked when a token is acquired.
*/
callback?: TokenCallback;
}
export default class AuthenticationContext {
constructor(options: AuthenticationContextOptions);
constructor(options: AuthenticationContext.Options);
/**
* Initiates the login process by redirecting the user to Azure AD authorization endpoint.
*/
@@ -153,7 +39,7 @@ export default class AuthenticationContext {
/**
* If user object exists, returns it. Else creates a new user object by decoding `id_token` from the cache.
*/
getCachedUser(): UserInfo;
getCachedUser(): AuthenticationContext.UserInfo;
/**
* Adds the passed callback to the array of callbacks for the specified resource.
* @param resource A URI that identifies the resource for which the token is requested.
@@ -163,14 +49,14 @@ export default class AuthenticationContext {
registerCallback(
expectedState: string,
resource: string,
callback: TokenCallback
callback: AuthenticationContext.TokenCallback
): void;
/**
* Acquires token from the cache if it is not expired. Otherwise sends request to AAD to obtain a new token.
* @param resource Resource URI identifying the target resource.
* @param callback The callback provided by the caller. It will be called with token or error.
*/
acquireToken(resource: string, callback: TokenCallback): void;
acquireToken(resource: string, callback: AuthenticationContext.TokenCallback): void;
/**
* Acquires token (interactive flow using a popup window) by sending request to AAD to obtain a new token.
* @param resource Resource URI identifying the target resource.
@@ -182,7 +68,7 @@ export default class AuthenticationContext {
resource: string,
extraQueryParameters: string | null | undefined,
claims: string | null | undefined,
callback: TokenCallback
callback: AuthenticationContext.TokenCallback
): void;
/**
* Acquires token (interactive flow using a redirect) by sending request to AAD to obtain a new token. In this case the callback passed in the authentication request constructor will be called.
@@ -217,7 +103,7 @@ export default class AuthenticationContext {
* Calls the passed in callback with the user object or error message related to the user.
* @param callback The callback provided by the caller. It will be called with user or error.
*/
getUser(callback: UserCallback): void;
getUser(callback: AuthenticationContext.UserCallback): void;
/**
* Checks if the URL fragment contains access token, id token or error description.
* @param hash Hash passed from redirect page.
@@ -230,11 +116,11 @@ export default class AuthenticationContext {
/**
* Creates a request info object from the URL fragment and returns it.
*/
getRequestInfo(hash: string): RequestInfo;
getRequestInfo(hash: string): AuthenticationContext.RequestInfo;
/**
* Saves token or error received in the response from AAD in the cache. In case of `id_token`, it also creates the user object.
*/
saveTokenFromHash(requestInfo: RequestInfo): void;
saveTokenFromHash(requestInfo: AuthenticationContext.RequestInfo): void;
/**
* Gets resource for given endpoint if mapping is provided with config.
* @param endpoint Resource URI identifying the target resource.
@@ -252,7 +138,7 @@ export default class AuthenticationContext {
* @param message Message to log.
* @param error Error to log.
*/
log(level: LoggingLevel, message: string, error: any): void;
log(level: AuthenticationContext.LoggingLevel, message: string, error: any): void;
/**
* Logs messages when logging level is set to 0.
* @param message Message to log.
@@ -274,4 +160,221 @@ export default class AuthenticationContext {
* @param message Message to log.
*/
verbose(message: string): void;
/**
* Logs Pii messages when Logging Level is set to 0 and window.piiLoggingEnabled is set to true.
* @param message Message to log.
* @param error Error to log.
*/
errorPii(message: string, error: any): void;
/**
* Logs Pii messages when Logging Level is set to 1 and window.piiLoggingEnabled is set to true.
* @param message Message to log.
*/
warnPii(message: string): void;
/**
* Logs messages when Logging Level is set to 2 and window.piiLoggingEnabled is set to true.
* @param message Message to log.
*/
infoPii(message: string): void;
/**
* Logs messages when Logging Level is set to 3 and window.piiLoggingEnabled is set to true.
* @param message Message to log.
*/
verbosePii(message: string): void;
}
declare namespace AuthenticationContext {
function inject(config: Options): AuthenticationContext;
type LoggingLevel = 0 | 1 | 2 | 3;
type RequestType = "LOGIN" | "RENEW_TOKEN" | "UNKNOWN";
type ResponseType = "id_token token" | "token";
interface RequestInfo {
/**
* Object comprising of fields such as id_token/error, session_state, state, e.t.c.
*/
parameters: any;
/**
* Request type.
*/
requestType: RequestType;
/**
* Whether state is valid.
*/
stateMatch: boolean;
/**
* Unique guid used to match the response with the request.
*/
stateResponse: string;
/**
* Whether `requestType` contains `id_token`, `access_token` or error.
*/
valid: boolean;
}
interface UserInfo {
/**
* Username assigned from UPN or email.
*/
userName: string;
/**
* Properties parsed from `id_token`.
*/
profile: any;
}
type TokenCallback = (
errorDesc: string | null,
token: string | null,
error: any
) => void;
type UserCallback = (errorDesc: string | null, user: UserInfo | null) => void;
/**
* Configuration options for Authentication Context
*/
interface Options {
/**
* Client ID assigned to your app by Azure Active Directory.
*/
clientId: string;
/**
* Endpoint at which you expect to receive tokens.Defaults to `window.location.href`.
*/
redirectUri?: string;
/**
* Azure Active Directory instance. Defaults to `https://login.microsoftonline.com/`.
*/
instance?: string;
/**
* Your target tenant. Defaults to `common`.
*/
tenant?: string;
/**
* Query parameters to add to the authentication request.
*/
extraQueryParameter?: string;
/**
* Unique identifier used to map the request with the response. Defaults to RFC4122 version 4 guid (128 bits).
*/
correlationId?: string;
/**
* User defined function of handling the navigation to Azure AD authorization endpoint in case of login.
*/
displayCall?: (url: string) => void;
/**
* Set this to true to enable login in a popup winodow instead of a full redirect. Defaults to `false`.
*/
popUp?: boolean;
/**
* Set this to the resource to request on login. Defaults to `clientId`.
*/
loginResource?: string;
/**
* Set this to redirect the user to a custom login page.
*/
localLoginUrl?: string;
/**
* Redirects to start page after login. Defaults to `true`.
*/
navigateToLoginRequestUrl?: boolean;
/**
* Set this to redirect the user to a custom logout page.
*/
logOutUri?: string;
/**
* Redirects the user to postLogoutRedirectUri after logout. Defaults to `redirectUri`.
*/
postLogoutRedirectUri?: string;
/**
* Sets browser storage to either 'localStorage' or sessionStorage'. Defaults to `sessionStorage`.
*/
cacheLocation?: "localStorage" | "sessionStorage";
/**
* Array of keywords or URIs. Adal will attach a token to outgoing requests that have these keywords or URIs.
*/
endpoints?: { [resource: string]: string };
/**
* Array of keywords or URIs. Adal will not attach a token to outgoing requests that have these keywords or URIs.
*/
anonymousEndpoints?: string[];
/**
* If the cached token is about to be expired in the expireOffsetSeconds (in seconds), Adal will renew the token instead of using the cached token. Defaults to 300 seconds.
*/
expireOffsetSeconds?: number;
/**
* The number of milliseconds of inactivity before a token renewal response from AAD should be considered timed out. Defaults to 6 seconds.
*/
loadFrameTimeout?: number;
/**
* Callback to be invoked when a token is acquired.
*/
callback?: TokenCallback;
}
interface LoggingConfig {
level: LoggingLevel;
log: (message: string) => void;
piiLoggingEnabled: boolean;
}
/**
* Enum for storage constants
*/
interface Constants {
ACCESS_TOKEN: 'access_token';
EXPIRES_IN: 'expires_in';
ID_TOKEN: 'id_token';
ERROR_DESCRIPTION: 'error_description';
SESSION_STATE: 'session_state';
STORAGE: {
TOKEN_KEYS: 'adal.token.keys';
ACCESS_TOKEN_KEY: 'adal.access.token.key';
EXPIRATION_KEY: 'adal.expiration.key';
STATE_LOGIN: 'adal.state.login';
STATE_RENEW: 'adal.state.renew';
NONCE_IDTOKEN: 'adal.nonce.idtoken';
SESSION_STATE: 'adal.session.state';
USERNAME: 'adal.username';
IDTOKEN: 'adal.idtoken';
ERROR: 'adal.error';
ERROR_DESCRIPTION: 'adal.error.description';
LOGIN_REQUEST: 'adal.login.request';
LOGIN_ERROR: 'adal.login.error';
RENEW_STATUS: 'adal.token.renew.status';
};
RESOURCE_DELIMETER: '|';
LOADFRAME_TIMEOUT: '6000';
TOKEN_RENEW_STATUS_CANCELED: 'Canceled';
TOKEN_RENEW_STATUS_COMPLETED: 'Completed';
TOKEN_RENEW_STATUS_IN_PROGRESS: 'In Progress';
LOGGING_LEVEL: {
ERROR: 0;
WARN: 1;
INFO: 2;
VERBOSE: 3;
};
LEVEL_STRING_MAP: {
0: 'ERROR:';
1: 'WARNING:';
2: 'INFO:';
3: 'VERBOSE:';
};
POPUP_WIDTH: 483;
POPUP_HEIGHT: 600;
}
}
declare global {
interface Window {
Logging: AuthenticationContext.LoggingConfig;
}
}
+3 -2
View File
@@ -15,10 +15,11 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",
"adal-angular-tests.ts"
]
}
}
+3 -3
View File
@@ -5,8 +5,8 @@ var mongoConnectionString = "mongodb://127.0.0.1/agenda";
var agenda = new Agenda({ db: { address: mongoConnectionString } });
agenda.define('delete old users', (job, done) => {
agenda.define<{ foo: Error }>('delete old users', (job, done) => {
done(job.attrs.data.foo)
});
agenda.on('ready', () => {
@@ -62,7 +62,7 @@ agenda.schedule('tomorrow at noon', ['printAnalyticsReport', 'sendNotifications'
agenda.now('do the hokey pokey');
var job = agenda.create('printAnalyticsReport', { userCount: 100 });
var job = agenda.create<{ userCount: number }>('printAnalyticsReport', { userCount: 100 });
job.save(function(err) {
console.log("Job successfully saved");
});
+31 -26
View File
@@ -1,6 +1,7 @@
// Type definitions for Agenda v1.0.0
// Project: https://github.com/rschmukler/agenda
// Type definitions for Agenda v1.0.3
// Project: https://github.com/agenda/agenda
// Definitions by: Meir Gottlieb <https://github.com/meirgottlieb>
// Jeff Principe <https://github.com/princjef>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -89,14 +90,14 @@ declare class Agenda extends EventEmitter {
* @param name The name of the job.
* @param data Data to associated with the job.
*/
create(name: string, data?: any): Agenda.Job;
create<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(name: string, data?: T): Agenda.Job<T>;
/**
* Find all Jobs matching `query` and pass same back in cb().
* @param query
* @param cb
*/
jobs(query: any, cb: ResultCallback<Agenda.Job[]>): void;
jobs<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(query: any, cb: ResultCallback<Agenda.Job<T>[]>): void;
/**
* Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want
@@ -113,8 +114,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<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(name: string, handler: (job: Agenda.Job<T>, done: (err?: Error) => void) => void): void;
define<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(name: string, options: Agenda.JobOptions, handler: (job: Agenda.Job<T>, done: (err?: Error) => void) => void): void;
/**
* Runs job name at the given interval. Optionally, data and options can be passed in.
@@ -124,8 +125,8 @@ declare class Agenda extends EventEmitter {
* @param options An optional argument that will be passed to job.repeatEvery.
* @param cb An optional callback function which will be called when the job has been persisted in the database.
*/
every(interval: number | string, names: string, data?: any, options?: any, cb?: ResultCallback<Agenda.Job>): Agenda.Job;
every(interval: number | string, names: string[], data?: any, options?: any, cb?: ResultCallback<Agenda.Job[]>): Agenda.Job[];
every<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(interval: number | string, names: string, data?: T, options?: any, cb?: ResultCallback<Agenda.Job<T>>): Agenda.Job<T>;
every<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(interval: number | string, names: string[], data?: T, options?: any, cb?: ResultCallback<Agenda.Job<T>[]>): Agenda.Job<T>[];
/**
* Schedules a job to run name once at a given time.
@@ -134,8 +135,8 @@ declare class Agenda extends EventEmitter {
* @param data An optional argument that will be passed to the processing function under job.attrs.data.
* @param cb An optional callback function which will be called when the job has been persisted in the database.
*/
schedule(when: Date | string, names: string, data?: any, cb?: ResultCallback<Agenda.Job>): Agenda.Job;
schedule(when: Date | string, names: string[], data?: any, cb?: ResultCallback<Agenda.Job[]>): Agenda.Job[];
schedule<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(when: Date | string, names: string, data?: T, cb?: ResultCallback<Agenda.Job<T>>): Agenda.Job<T>;
schedule<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(when: Date | string, names: string[], data?: T, cb?: ResultCallback<Agenda.Job<T>[]>): Agenda.Job<T>[];
/**
* Schedules a job to run name once immediately.
@@ -143,7 +144,7 @@ declare class Agenda extends EventEmitter {
* @param data An optional argument that will be passed to the processing function under job.attrs.data.
* @param cb An optional callback function which will be called when the job has been persisted in the database.
*/
now(name: string, data?: any, cb?: ResultCallback<Agenda.Job>): Agenda.Job;
now<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(name: string, data?: T, cb?: ResultCallback<Agenda.Job<T>>): Agenda.Job<T>;
/**
* Cancels any jobs matching the passed mongodb-native query, and removes them from the database.
@@ -242,10 +243,14 @@ declare namespace Agenda {
}
}
interface JobAttributesData {
[key: string]: any;
}
/**
* The database record associated with a job.
*/
interface JobAttributes {
interface JobAttributes<T extends JobAttributesData = JobAttributesData> {
/**
* The record identity.
*/
@@ -264,7 +269,7 @@ declare namespace Agenda {
/**
* The job details.
*/
data: { [name: string]: any };
data: T;
/**
* The priority of the job.
@@ -330,12 +335,12 @@ declare namespace Agenda {
/**
* A scheduled job.
*/
interface Job {
interface Job<T extends JobAttributesData = JobAttributesData> {
/**
* The database record associated with the job.
*/
attrs: JobAttributes;
attrs: JobAttributes<T>;
/**
* The agenda that created the job.
@@ -348,54 +353,54 @@ declare namespace Agenda {
* @param options An optional argument that can include a timezone field. The timezone should be a string as
* accepted by moment-timezone and is considered when using an interval in the cron string format.
*/
repeatEvery(interval: string | number, options?: { timezone?: string }): Job
repeatEvery(interval: string | number, options?: { timezone?: string }): Job<T>
/**
* Specifies a time when the job should repeat. [Possible values](https://github.com/matthewmueller/date#examples).
* @param time
*/
repeatAt(time: string): Job
repeatAt(time: string): Job<T>
/**
* Disables the job.
*/
disable(): Job;
disable(): Job<T>;
/**
* Enables the job.
*/
enable(): Job;
enable(): Job<T>;
/**
* Ensure that only one instance of this job exists with the specified properties
* @param value The properties associated with the job that must be unqiue.
* @param opts
*/
unique(value: any, opts?: { insertOnly?: boolean }): Job;
unique(value: any, opts?: { insertOnly?: boolean }): Job<T>;
/**
* Specifies the next time at which the job should run.
* @param time The next time at which the job should run.
*/
schedule(time: string | Date): Job;
schedule(time: string | Date): Job<T>;
/**
* Specifies the priority weighting of the job.
* @param value The priority of the job (lowest|low|normal|high|highest|number).
*/
priority(value: string | number): Job;
priority(value: string | number): Job<T>;
/**
* Sets job.attrs.failedAt to now, and sets job.attrs.failReason to reason.
* @param reason A message or Error object that indicates why the job failed.
*/
fail(reason: string | Error): Job;
fail(reason: string | Error): Job<T>;
/**
* Runs the given job and calls callback(err, job) upon completion. Normally you never need to call this manually
* @param cb Called when the job is completed.
*/
run(cb?: ResultCallback<Job>): Job;
run(cb?: ResultCallback<Job<T>>): Job<T>;
/**
* Returns true if the job is running; otherwise, returns false.
@@ -406,7 +411,7 @@ declare namespace Agenda {
* Saves the job into the database.
* @param cb Called when the job is saved.
*/
save(cb?: ResultCallback<Job>): Job;
save(cb?: ResultCallback<Job<T>>): Job<T>;
/**
* Removes the job from the database and cancels the job.
@@ -424,7 +429,7 @@ declare namespace Agenda {
/**
* Calculates next time the job should run
*/
computeNextRunAt(): Job;
computeNextRunAt(): Job<T>;
}
interface JobOptions {
+2 -11
View File
@@ -805,11 +805,7 @@ declare namespace algoliasearch {
* @param err() error callback
* https://www.algolia.com/doc/api-reference/api-methods/search-for-facet-values/
*/
searchForFacetValues({
facetName,
facetQuery,
...qp,
}: {
searchForFacetValues(options: {
facetName: string;
facetQuery: string;
} & AlgoliaQueryParameters): Promise<any>;
@@ -820,12 +816,7 @@ declare namespace algoliasearch {
* @param err() error callback
* https://www.algolia.com/doc/api-reference/api-methods/search-for-facet-values/
*/
searchForFacetValues(
{
facetName,
facetQuery,
...qp,
}: {
searchForFacetValues(options: {
facetName: string;
facetQuery: string;
} & AlgoliaQueryParameters,
+57
View File
@@ -0,0 +1,57 @@
import Message = require('amp-message');
// $ExpectType Message
new Message(new Buffer('aaa'));
// $ExpectType Message
new Message([new Buffer('aaa'), new Buffer('bbb')]);
const message = new Message([new Buffer('aaa'), new Buffer('bbb')]);
// $ExpectType string
message.inspect();
// $ExpectType Buffer
message.toBuffer();
// $ExpectType number
message.push(new Buffer('ccc'));
// $ExpectType Buffer | undefined
message.pop();
// $ExpectType Buffer | undefined
message.shift();
// $ExpectType number
message.unshift(new Buffer('ddd'));
// $ExpectError
new Message();
// $ExpectError
new Message(1);
// $ExpectError
new Message({});
// $ExpectError
new Message('aaa');
// $ExpectError
message.push(1);
// $ExpectError
message.push({});
// $ExpectError
message.push('aaa');
// $ExpectError
message.unshift(1);
// $ExpectError
message.unshift({});
// $ExpectError
message.unshift('aaa');
+25
View File
@@ -0,0 +1,25 @@
// Type definitions for amp-message 0.1
// Project: https://github.com/visionmedia/node-amp-message
// Definitions by: Vilim Stubičan <https://github.com/jewbre>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/// <reference types="node" />
declare class Message {
constructor(args: Buffer | Buffer[]);
inspect(): string;
toBuffer(): Buffer;
push(...items: Buffer[]): number;
pop(): Buffer | undefined;
shift(): Buffer | undefined;
unshift(...items: Buffer[]): number;
}
export = Message;
+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",
"amp-message-tests.ts"
]
}
+44
View File
@@ -0,0 +1,44 @@
import { decode, encode, Stream } from 'amp';
// $ExpectType Buffer[]
decode(new Buffer('something'));
// $ExpectType Buffer
encode([new Buffer('something'), new Buffer('something')]);
// $ExpectError
decode('');
// $ExpectError
decode(1);
// $ExpectError
decode();
// $ExpectError
encode('');
// $ExpectError
encode(1);
// $ExpectError
encode();
// $ExpectType Stream
new Stream({});
// $ExpectType Stream
new Stream({
highWaterMark: 1,
decodeStrings: true,
objectMode: true,
destroy: (error?: Error) => {
return 'handle error';
},
final: (callback: (error?: Error) => void) => {
// do nothing
}
});
// $ExpectError
new Stream({somethingNoneExisting: true});
+19
View File
@@ -0,0 +1,19 @@
// Type definitions for amp 0.3
// Project: https://github.com/visionmedia/node-amp
// Definitions by: Vilim Stubičan <https://github.com/jewbre>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/// <reference types="node" />
import * as stream from 'stream';
export function decode(buf: Buffer): Buffer[];
export function encode(args: Buffer[]): Buffer;
export class Stream extends stream.Writable {
constructor(opts: stream.WritableOptions);
_write(chunk: any, encoding: string, fn: () => void): void;
}
+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",
"amp-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
@@ -8,7 +8,8 @@ myApp.config((
$mdAriaProvider: ng.material.IAriaProvider,
$mdThemingProvider: ng.material.IThemingProvider,
$mdIconProvider: ng.material.IIconProvider,
$mdProgressCircularProvider: ng.material.IProgressCircularProvider) => {
$mdProgressCircularProvider: ng.material.IProgressCircularProvider,
$mdDialogProvider: ng.material.IDialogProvider) => {
$mdThemingProvider.alwaysWatchTheme(true);
const neonRedMap: ng.material.IPalette = $mdThemingProvider.extendPalette('red', {
500: 'ff0000'
@@ -56,6 +57,23 @@ myApp.config((
// Globally disables all ARIA warnings.
$mdAriaProvider.disableWarnings();
// Add custom dialog preset
$mdDialogProvider.addPreset('testPreset', {
methods: ['entityName'],
options: () => {
return {
template:
'<md-dialog>' +
'This is a custom preset' +
'</md-dialog>',
controllerAs: 'dialog',
bindToController: true,
clickOutsideToClose: true,
escapeToClose: true
};
}
});
});
myApp.controller('BottomSheetController', ($scope: TestScope, $mdBottomSheet: ng.material.IBottomSheetService, $q: ng.IQService) => {
@@ -192,6 +210,11 @@ myApp.controller('DialogController', ($scope: TestScope, $mdDialog: ng.material.
onComplete: (scope, element) => { },
onRemoving: (element, removePromise) => { },
});
// Show custom dialog preset
$mdDialog.show(
$mdDialog['testPreset']().entityName('Product #6')
);
});
class IconDirective implements ng.IDirective {
+10 -1
View File
@@ -125,6 +125,11 @@ declare module 'angular' {
}
interface IDialogService {
// indexer used to call preset dialog created with $mdDialogProvider
// see: https://material.angularjs.org/latest/api/service/$mdDialog#custom-presets
// tslint:disable-next-line:ban-types
[presetName: string]: Function;
show(dialog: IDialogOptions | IAlertDialog | IConfirmDialog | IPromptDialog): IPromise<any>;
confirm(): IConfirmDialog;
alert(): IAlertDialog;
@@ -133,6 +138,10 @@ declare module 'angular' {
cancel(response?: any): void;
}
interface IDialogProvider {
addPreset(presetName: string, presetOptions: { methods?: ReadonlyArray<string>, options: () => IDialogOptions }): IDialogProvider;
}
type IIcon = (id: string) => IPromise<Element>; // id is a unique ID or URL
interface IIconProvider {
@@ -223,7 +232,7 @@ declare module 'angular' {
contrastDefaultColor?: string;
contrastDarkColors?: string | string[];
contrastLightColors?: string | string[];
contrastStrongLightColors?: string|string[];
contrastStrongLightColors?: string | string[];
}
interface IThemeHues {
+2 -2
View File
@@ -1,5 +1,5 @@
import * as React from "react";
import { StyleSheet, css, StyleSheetServer, StyleSheetTestUtils } from "aphrodite";
import { StyleSheet, css, StyleSheetServer, StyleSheetTestUtils, FontFamily } from "aphrodite";
const styles = StyleSheet.create({
red: {
@@ -20,7 +20,7 @@ const styles = StyleSheet.create({
}
});
const coolFont = {
const coolFont: FontFamily = {
fontFamily: "CoolFont",
fontStyle: "normal",
fontWeight: "normal",
+25 -2
View File
@@ -4,13 +4,36 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
import * as React from "react";
import * as CSS from "csstype";
type BaseCSSProperties = CSS.Properties<number | string>;
type FontFamily =
| BaseCSSProperties['fontFamily']
| CSS.FontFace;
// Replace with Exclude once on 2.8+
type Diff<T extends string, U extends string> = (
& { [P in T]: P }
& { [P in U]: never }
& { [x: string]: never }
)[T];
type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>;
type CSSProperties = Omit<BaseCSSProperties, 'fontFamily'> & {
fontFamily?: FontFamily | FontFamily[];
};
// For pseudo selectors and media queries
interface OpenCSSProperties extends CSSProperties {
[k: string]: CSSProperties[keyof CSSProperties] | CSSProperties;
}
/**
* Aphrodite style declaration
*/
export interface StyleDeclaration {
[key: string]: React.CSSProperties;
[key: string]: OpenCSSProperties;
}
interface StyleSheetStatic {
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"csstype": "^2.2.0"
}
}
+1 -1
View File
@@ -64,6 +64,6 @@ archiver.setModule(() => {});
archiver.pointer();
archiver.use(() => {});
archiver.finalize().then();
archiver.finalize();
archiver.symlink('./path', './target');
+1 -1
View File
@@ -35,7 +35,7 @@ declare namespace archiver {
directory(dirpath: string, destpath: false | string, data?: EntryData | EntryDataFunction): this;
file(filename: string, data: EntryData): this;
glob(pattern: string, options?: glob.IOptions, data?: EntryData): this;
finalize(): Promise<void>;
finalize(): void;
setFormat(format: string): this;
setModule(module: Function): this;
+1 -1
View File
@@ -1,4 +1,4 @@
import arrify = require("arrify");
import * as arrify from 'arrify';
arrify(null);
arrify<number>(null);
+1
View File
@@ -14,4 +14,5 @@
* arrify([2, 3]) // returns [2, 3]
*/
declare function arrify<T>(val: undefined | null | T | T[]): T[];
declare namespace arrify {}
export = arrify;
+2 -1
View File
@@ -1,4 +1,5 @@
import { Options, RetryFunction, retry } from 'async-retry';
import { Options, RetryFunction } from 'async-retry';
import retry = require("async-retry");
const o: Options = {
retries: 1,
+18 -10
View File
@@ -1,17 +1,25 @@
// Type definitions for async-retry 1.1
// Type definitions for async-retry 1.2
// Project: https://github.com/zeit/async-retry#readme
// Definitions by: Albert Wu <https://github.com/albertywu>
// Pablo Rodríguez <https://github.com/MeLlamoPablo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export function retry<A>(fn: RetryFunction<A>, opts: Options): Promise<A>;
declare function AsyncRetry<A>(
fn: AsyncRetry.RetryFunction<A>,
opts: AsyncRetry.Options
): Promise<A>;
export interface Options {
retries?: number;
factor?: number;
minTimeout?: number;
maxTimeout?: number;
randomize?: boolean;
onRetry?: (e: Error) => any;
declare namespace AsyncRetry {
interface Options {
retries?: number;
factor?: number;
minTimeout?: number;
maxTimeout?: number;
randomize?: boolean;
onRetry?: (e: Error) => any;
}
type RetryFunction<A> = (bail: (e: Error) => A, attempt: number) => A|Promise<A>;
}
export type RetryFunction<A> = (bail: (e: Error) => A, attempt: number) => A|Promise<A>;
export = AsyncRetry;
+2 -2
View File
@@ -168,8 +168,8 @@ export function forever<E>(next: (next : ErrorCallback<E>) => void, errBack: Err
export function waterfall<T, E>(tasks: Function[], callback?: AsyncResultCallback<T, E | Error>): void;
export function compose(...fns: Function[]): Function;
export function seq(...fns: Function[]): Function;
export function applyEach(fns: Function[], argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
export function applyEachSeries(fns: Function[], argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
export function applyEach(fns: Function[], ...argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
export function applyEachSeries(fns: Function[], ...argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
export function queue<T, E>(worker: AsyncWorker<T, E>, concurrency?: number): AsyncQueue<T>;
export function queue<T, R, E>(worker: AsyncResultIterator<T, R, E>, concurrency?: number): AsyncQueue<T>;
export function priorityQueue<T, E>(worker: AsyncWorker<T, E>, concurrency: number): AsyncPriorityQueue<T>;
+1 -1
View File
@@ -3310,7 +3310,7 @@ const pathWatcherPromise = Atom.watchPath("/var/test", {}, (events) => {
for (const event of events) {
str = event.path;
str = event.action;
if (event.oldPath) str = event.oldPath;
if (event.action === "renamed") str = event.oldPath;
}
});
+29 -4
View File
@@ -30,11 +30,20 @@ export interface SuggestionInsertedEvent {
suggestion: TextSuggestion|SnippetSuggestion;
}
/**
* COMPATIBILITY STUB. WILL BE REMOVED
*/
// tslint:disable-next-line:no-empty-interface
export interface Suggestion<
T extends { text: string }|{ snippet: string }
> extends SuggestionBase {}
// TODO: Remove on next minor version
/**
* An autocompletion suggestion for the user.
* Primary data type for the Atom Autocomplete+ service.
*/
export interface Suggestion<T extends { text: string }|{ snippet: string }> {
export interface SuggestionBase {
/**
* A string that will show in the UI for this suggestion.
* When not set, snippet || text is displayed.
@@ -91,14 +100,20 @@ export interface Suggestion<T extends { text: string }|{ snippet: string }> {
* When specified, a More.. link will be displayed in the description area.
*/
descriptionMoreURL?: string;
/**
* (experimental) Description with Markdown formatting.
* Takes precedence over plaintext description.
*/
descriptionMarkdown?: string;
}
export interface TextSuggestion extends Suggestion<TextSuggestion> {
export interface TextSuggestion extends SuggestionBase {
/** The text which will be inserted into the editor, in place of the prefix. */
text: string;
}
export interface SnippetSuggestion extends Suggestion<SnippetSuggestion> {
export interface SnippetSuggestion extends SuggestionBase {
/**
* A snippet string. This will allow users to tab through function arguments
* or other options.
@@ -106,7 +121,8 @@ export interface SnippetSuggestion extends Suggestion<SnippetSuggestion> {
snippet: string;
}
export type Suggestions = Array<TextSuggestion|SnippetSuggestion>;
export type AnySuggestion = TextSuggestion|SnippetSuggestion;
export type Suggestions = AnySuggestion[];
/** The interface that all Autocomplete+ providers must implement. */
export interface AutocompleteProvider {
@@ -154,4 +170,13 @@ export interface AutocompleteProvider {
/** Will be called if your provider is being destroyed by autocomplete+ */
dispose?(): void;
/**
* (experimental) Is called when a suggestion is selected by the user for
* the purpose of loading more information about the suggestion. Return a
* Promise of the new suggestion to replace it with or return null if
* no change is needed.
*/
getSuggestionDetailsOnSelect?:
(suggestion: AnySuggestion) => Promise<AnySuggestion | null> | AnySuggestion | null;
}
+13 -4
View File
@@ -5647,19 +5647,28 @@ export interface FileSavedEvent {
path: string;
}
export type FilesystemChangeEvent = Array<{
export interface FilesystemChangeBasic<
Action extends "created"|"modified"|"deleted"|"renamed"
= "created"|"modified"|"deleted"
> {
/** A string describing the filesystem action that occurred. */
action: "created"|"modified"|"deleted"|"renamed";
action: Action;
/** The absolute path to the filesystem entry that was acted upon. */
path: string;
}
export interface FilesystemChangeRename extends FilesystemChangeBasic<"renamed"> {
/**
* For rename events, a string containing the filesystem entry's former
* absolute path.
*/
oldPath?: string;
}>;
oldPath: string;
}
export type FilesystemChange = FilesystemChangeBasic|FilesystemChangeRename;
export type FilesystemChangeEvent = FilesystemChange[];
export interface FullKeybindingMatchEvent {
/** The string of keystrokes that matched the binding. */
+3 -1
View File
@@ -124,7 +124,9 @@ const otherOptions : Auth0LockConstructorOptions = {
configurationBaseUrl: "https://cdn.auth0.com",
languageBaseUrl: "http://www.example.com",
hashCleanup: false,
leeway: 30
leeway: 30,
_enableImpersonation: true,
_enableIdPInitiatedLogin: false
};
new Auth0Lock(CLIENT_ID, DOMAIN, otherOptions);
+4 -2
View File
@@ -1,4 +1,4 @@
// Type definitions for auth0-lock 10.16
// Type definitions for auth0-lock 11.4
// Project: http://auth0.com
// Definitions by: Brian Caruso <https://github.com/carusology>
// Dan Caddigan <https://github.com/goldcaddy77>
@@ -118,7 +118,7 @@ interface Auth0LockConstructorOptions {
auth?: Auth0LockAuthOptions;
autoclose?: boolean;
autofocus?: boolean;
avatar?: Auth0LockAvatarOptions;
avatar?: Auth0LockAvatarOptions | null;
clientBaseUrl?: string;
closable?: boolean;
configurationBaseUrl?: string;
@@ -143,6 +143,8 @@ interface Auth0LockConstructorOptions {
socialButtonStyle?: "big" | "small";
theme?: Auth0LockThemeOptions;
usernameStyle?: string;
_enableImpersonation?: boolean;
_enableIdPInitiatedLogin?: boolean;
}
interface Auth0LockFlashMessageOptions {
+3 -3
View File
@@ -25,7 +25,7 @@ declare namespace autobahn {
leave(reason: string, message: string): void;
call<TResult>(procedure: string, args?: any[], kwargs?: any, options?: ICallOptions): When.Promise<TResult>;
call<TResult>(procedure: string, args?: any[] | any, kwargs?: any, options?: ICallOptions): When.Promise<TResult>;
publish(topic: string, args?: any[], kwargs?: any, options?: IPublishOptions): When.Promise<IPublication>;
@@ -96,7 +96,7 @@ declare namespace autobahn {
kwargs: any;
}
type SubscribeHandler = (args?: any[], kwargs?: any, details?: IEvent) => void;
type SubscribeHandler = (args?: any[] | any, kwargs?: any, details?: IEvent) => void;
interface ISubscription {
topic: string;
@@ -206,7 +206,7 @@ declare namespace autobahn {
type DeferFactory = () => When.Promise<any>;
type OnChallengeHandler = (session: Session, method: string, extra: any) => string;
type OnChallengeHandler = (session: Session, method: string, extra: any) => string | When.Promise<string>;
interface IConnectionOptions {
use_es6_promises?: boolean;
+69 -3
View File
@@ -260,9 +260,27 @@ statement = {
};
statement = {
Sid: str,
Action: [str, str],
Effect: str,
Resource: [str, str]
Resource: [str, str],
Condition: {
condition1: { key: "value" },
condition2: [{
key1: "value",
key2: "value"
}, {
key3: "value"
}]
},
Principal: [str, str],
NotPrincipal: [str, str]
};
statement = {
Effect: str,
NotAction: str,
NotResource: str
};
policyDocument = {
@@ -270,6 +288,11 @@ policyDocument = {
Statement: [statement]
};
policyDocument = {
Version: str,
Statement: [statement, statement]
};
authResponse = {
principalId: str,
policyDocument,
@@ -572,6 +595,28 @@ const CloudFrontResponseEvent: AWSLambda.CloudFrontResponseEvent = {
]
};
/* Kinesis Data Stream Events */
declare let kinesisStreamEvent: AWSLambda.KinesisStreamEvent;
declare let kinesisStreamRecord: AWSLambda.KinesisStreamRecord;
declare let kinesisStreamRecordPayload: AWSLambda.KinesisStreamRecordPayload;
kinesisStreamRecord = kinesisStreamEvent.Records[0];
str = kinesisStreamRecord.awsRegion;
str = kinesisStreamRecord.eventID;
str = kinesisStreamRecord.eventName;
str = kinesisStreamRecord.eventSource;
str = kinesisStreamRecord.eventSourceARN;
str = kinesisStreamRecord.eventVersion;
str = kinesisStreamRecord.invokeIdentityArn;
kinesisStreamRecordPayload = kinesisStreamRecord.kinesis;
num = kinesisStreamRecordPayload.approximateArrivalTimestamp;
str = kinesisStreamRecordPayload.data;
str = kinesisStreamRecordPayload.kinesisSchemaVersion;
str = kinesisStreamRecordPayload.partitionKey;
str = kinesisStreamRecordPayload.sequenceNumber;
/* Compatibility functions */
context.done();
context.done(error);
@@ -585,8 +630,27 @@ context.fail(str);
/* Handler */
let handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => { };
// async methods return Promise, test assignability
let asyncHandler: AWSLambda.Handler = async (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => { };
/* In node8.10 runtime, handlers may return a promise for the result value, so existing async
* handlers that return Promise<void> before calling the callback will now have a `null` result.
* Be safe and make that badly typed with a major verson bump to 8.10 so users expect the breaking change,
* since the upgrade effort should be pretty low in most cases, and it points them at a nicer solution.
*/
// $ExpectError
let legacyAsyncHandler: AWSLambda.APIGatewayProxyHandler = async (
event: AWSLambda.APIGatewayProxyEvent,
context: AWSLambda.Context,
cb: AWSLambda.Callback<AWSLambda.APIGatewayProxyResult>,
) => {
cb(null, { statusCode: 200, body: 'No longer valid' });
};
let node8AsyncHandler: AWSLambda.APIGatewayProxyHandler = async (
event: AWSLambda.APIGatewayProxyEvent,
context: AWSLambda.Context,
cb: AWSLambda.Callback<AWSLambda.APIGatewayProxyResult>,
) => {
return { statusCode: 200, body: 'Is now valid!' };
};
let inferredHandler: AWSLambda.S3Handler = (event, context, cb) => {
// $ExpectType S3Event
@@ -661,3 +725,5 @@ let customHandler: AWSLambda.Handler<CustomEvent, CustomResult> = (event, contex
// $ExpectError
cb(null, { resultString: bool });
};
let kinesisStreamHandler: AWSLambda.KinesisStreamHandler = (event: AWSLambda.KinesisStreamEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => { };
+67 -9
View File
@@ -1,4 +1,4 @@
// Type definitions for AWS Lambda
// Type definitions for AWS Lambda 8.10
// Project: http://docs.aws.amazon.com/lambda
// Definitions by: James Darbyshire <https://github.com/darbio/aws-lambda-typescript>
// Michael Skarum <https://github.com/skarum>
@@ -16,6 +16,8 @@
// Danilo Raisi <https://github.com/daniloraisi>
// Simon Buchan <https://github.com/simonbuchan>
// David Hayden <https://github.com/Haydabase>
// Chris Redekop <https://github.com/repl-chris>
// Aneil Mallavarapu <https://github.com/aneilbaboo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -437,28 +439,52 @@ export interface CustomAuthorizerResult {
principalId: string;
policyDocument: PolicyDocument;
context?: AuthResponseContext;
usageIdentifierKey?: string;
}
export type AuthResponse = CustomAuthorizerResult;
/**
* API Gateway CustomAuthorizer AuthResponse.PolicyDocument.
* http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output
* https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-output.html
* https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition
*/
export interface PolicyDocument {
Version: string;
Statement: [Statement];
Id?: string;
Statement: Statement[];
}
/**
* API Gateway CustomAuthorizer AuthResponse.PolicyDocument.Condition.
* https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-policy-language-overview.html
* https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html
*/
export interface ConditionBlock {
[condition: string]: Condition | Condition[];
}
export interface Condition {
[key: string]: string | string[];
}
/**
* API Gateway CustomAuthorizer AuthResponse.PolicyDocument.Statement.
* http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output
* https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-policy-language-overview.html
* https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html
*/
export interface Statement {
Action: string | string[];
export type Statement = BaseStatement & StatementAction & StatementResource;
export interface BaseStatement {
Effect: string;
Resource: string | string[];
Sid?: string;
Condition?: ConditionBlock;
Principal?: string | string[];
NotPrincipal?: string | string[];
}
export type StatementAction = { Action: string | string[] } | { NotAction: string | string[] };
export type StatementResource = { Resource: string | string[] } | { NotResource: string | string[] };
/**
* API Gateway CustomAuthorizer AuthResponse.PolicyDocument.Statement.
* http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output
@@ -529,6 +555,31 @@ export interface CloudFrontRequestEvent {
export type CloudFrontResponseResult = undefined | null | CloudFrontResultResponse;
// Kinesis Streams
// https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-kinesis-streams
export interface KinesisStreamRecordPayload {
approximateArrivalTimestamp: number;
data: string;
kinesisSchemaVersion: string;
partitionKey: string;
sequenceNumber: string;
}
export interface KinesisStreamRecord {
awsRegion: string;
eventID: string;
eventName: string;
eventSource: string;
eventSourceARN: string;
eventVersion: string;
invokeIdentityArn: string;
kinesis: KinesisStreamRecordPayload;
}
export interface KinesisStreamEvent {
Records: KinesisStreamRecord[];
}
/**
* AWS Lambda handler function.
* http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
@@ -536,8 +587,13 @@ export type CloudFrontResponseResult = undefined | null | CloudFrontResultRespon
* @param event – event data.
* @param context – runtime information of the Lambda function that is executing.
* @param callback – optional callback to return information to the caller, otherwise return value is null.
* @return In the node8.10 runtime, a promise for the lambda result.
*/
export type Handler<TEvent = any, TResult = any> = (event: TEvent, context: Context, callback: Callback<TResult>) => void;
export type Handler<TEvent = any, TResult = any> = (
event: TEvent,
context: Context,
callback: Callback<TResult>,
) => void | Promise<TResult>;
/**
* Optional callback parameter.
@@ -595,7 +651,9 @@ export type CloudFrontRequestCallback = Callback<CloudFrontRequestResult>;
export type CloudFrontResponseHandler = Handler<CloudFrontResponseEvent, CloudFrontResponseResult>;
export type CloudFrontResponseCallback = Callback<CloudFrontResponseResult>;
// TODO: Kinesis (should be very close to DynamoDB stream?)
export type KinesisStreamHandler = Handler<KinesisStreamEvent, void>;
// TODO: Kinesis Firehose
export type CustomAuthorizerHandler = Handler<CustomAuthorizerEvent, CustomAuthorizerResult>;
export type CustomAuthorizerCallback = Callback<CustomAuthorizerResult>;
+173
View File
@@ -0,0 +1,173 @@
import * as axon from 'axon';
import { Socket as NetSocket } from 'net';
const PubEmitterSocket = axon.PubEmitterSocket;
const PubSocket = axon.PubSocket;
const RepSocket = axon.RepSocket;
const ReqSocket = axon.ReqSocket;
const Socket = axon.Socket;
const SubSocket = axon.SubSocket;
const pubSocket = new PubSocket();
const pubEmitterSocket = new PubEmitterSocket();
const repSocket = new RepSocket();
const reqSocket = new ReqSocket();
const netSocket = new NetSocket();
const socket = new Socket();
const subSocket = new SubSocket();
// $ExpectType PubSocket
pubSocket.send('anything');
// $ExpectType PubSocket
pubSocket.send('anything', {w: 100, h: 200});
// $ExpectType PubSocket
pubEmitterSocket.send('anything');
// $ExpectType PubSocket
pubEmitterSocket.send('anything', {w: 100, h: 200});
// $ExpectType Socket
pubEmitterSocket.bind(3000);
// $ExpectError
pubEmitterSocket.bind({a, b, c});
// $ExpectError
pubEmitterSocket.bind();
// $ExpectType Socket
pubEmitterSocket.connect(3000);
// $ExpectError
pubEmitterSocket.connect({a, b, c});
// $ExpectError
pubEmitterSocket.connect();
// $ExpectType (args: Buffer | Buffer[]) => void
repSocket.onmessage(netSocket);
// $ExpectError
repSocket.onmessage();
// $ExpectError
repSocket.onmessage('');
// $ExpectError
repSocket.onmessage(1);
// $ExpectError
repSocket.onmessage({});
// $ExpectType string
reqSocket.id();
// $ExpectType (args: Buffer | Buffer[]) => void
reqSocket.onmessage();
// $ExpectType void
reqSocket.send('anything');
// $ExpectType void
reqSocket.send('anything', {w: 100, h: 200});
// $ExpectType Socket
socket.set('name', 'aaa');
// $ExpectError
socket.set(1, 'aaa');
// $ExpectError
socket.set({}, 'aaa');
// $ExpectError
socket.set('name');
// $ExpectType any
socket.get('name');
// $ExpectError
socket.get(1);
// $ExpectError
socket.get({});
// $ExpectType Socket
socket.enable('name');
// $ExpectError
socket.enable(1);
// $ExpectError
socket.enable({});
// $ExpectType Socket
socket.disable('name');
// $ExpectError
socket.disable(1);
// $ExpectError
socket.disable({});
// $ExpectType boolean
socket.enabled('name');
// $ExpectError
socket.enabled(1);
// $ExpectError
socket.enabled({});
// $ExpectType boolean
socket.disabled('name');
// $ExpectError
socket.disabled(1);
// $ExpectError
socket.disabled({});
// $ExpectType boolean
subSocket.hasSubscriptions();
// $ExpectType boolean
subSocket.matches('name');
// $ExpectError
subSocket.matches(1);
// $ExpectError
subSocket.matches({});
// $ExpectType RegExp
subSocket.subscribe(/some regex/);
// $ExpectType RegExp
subSocket.subscribe('some string');
// $ExpectError
subSocket.subscribe(1);
// $ExpectError
subSocket.subscribe({});
// $ExpectError
subSocket.subscribe();
// $ExpectType void
subSocket.unsubscribe(/some regex/);
// $ExpectType void
subSocket.unsubscribe('some string');
// $ExpectError
subSocket.unsubscribe(1);
// $ExpectError
subSocket.unsubscribe({});
// $ExpectError
subSocket.unsubscribe();
+134
View File
@@ -0,0 +1,134 @@
// Type definitions for axon 2.0
// Project: https://github.com/visionmedia/axon#readme
// Definitions by: Vilim Stubičan <https://github.com/jewbre>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/// <reference types="node" />
import { EventEmitter } from "events";
import { Socket as NetSocket } from "net";
export class Socket extends EventEmitter {
set(name: string, val: any): Socket;
get(name: string): any;
enable(name: string): Socket;
disable(name: string): Socket;
enabled(name: string): boolean;
disabled(name: string): boolean;
use(plugin: (socket: Socket) => any): Socket;
pack(args: Buffer | Buffer[]): Buffer;
closeSockets(): void;
close(): void;
closeServer(fn: () => any): void;
address(): { port: number; family: string; address: string; string: string } | undefined;
removeSocket(sock: Socket): void;
addSocket(sock: Socket): void;
handleErrors(sock: Socket): void;
onmessage(sock: NetSocket): (args: Buffer | Buffer[]) => void;
connect(port: ConnectionPort, host?: string | (() => void), fn?: () => void): Socket;
onconnect(sock: Socket): void;
bind(port: ConnectionPort, host?: string | (() => void), fn?: () => void): Socket;
}
export class SubSocket extends Socket {
hasSubscriptions(): boolean;
matches(topic: string): boolean;
onmessage(sock: NetSocket): (args: Buffer | Buffer[]) => void;
subscribe(re: RegExp | string): RegExp;
unsubscribe(re: RegExp | string): void;
clearSubscriptions(): void;
/**
* @throws {Error}
*/
send(): void;
}
export class SubEmitterSocket {
onmessage(): (args: Buffer | Buffer[]) => void;
on(event: string, fn: (...args: any[]) => void): SubEmitterSocket;
off(event: string): SubEmitterSocket;
bind(port: ConnectionPort, host?: string | (() => void), fn?: () => void): Socket;
connect(port: ConnectionPort, host?: string | (() => void), fn?: () => void): Socket;
close(): void;
}
export class PubSocket extends Socket {
send(...args: any[]): PubSocket;
}
export class PubEmitterSocket {
sock: PubSocket;
send(...args: any[]): PubSocket;
bind(port: ConnectionPort, host?: string | (() => void), fn?: () => void): Socket;
connect(port: ConnectionPort, host?: string | (() => void), fn?: () => void): Socket;
close(): void;
}
export class PushSocket extends Socket {
send(...args: any[]): void;
enqueue(msg: any): void;
}
export class ReqSocket extends Socket {
id(): string;
onmessage(): (args: Buffer | Buffer[]) => void;
send(...args: any[]): void;
}
export class RepSocket extends Socket {
onmessage(sock: NetSocket): (args: Buffer | Buffer[]) => void;
}
export class PullSocket extends Socket {
/**
* @throws {Error}
*/
send(): void;
}
export type ConnectionPort =
number
| string
| { protocol?: string, hostname?: string, pathname: string, port: string | number };
export function socket(type: string, options?: any): Socket;
export const types: {
[propName: string]: { new(): PubEmitterSocket | SubEmitterSocket | PushSocket | PullSocket | PubSocket | SubSocket | ReqSocket | RepSocket | Socket };
};
+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",
"axon-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+2 -2
View File
@@ -14,14 +14,14 @@ function ResponseCallback(err: Error | null, response: Azure.ServiceBus.Response
const ServiceBus = AzureSB.createServiceBusService('connectionstring');
// Queues
ServiceBus.listQueues('', createResultCallback<Models.Queue[]>());
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.listTopics(createResultCallback<Models.Topic[]>());
ServiceBus.createTopic('test', createResultCallback<Models.Topic>());
ServiceBus.createTopicIfNotExists('test', createResultCallback<boolean>());
ServiceBus.getTopic('test', createResultCallback<Models.Topic>());
+10 -14
View File
@@ -214,15 +214,15 @@ export namespace Azure.ServiceBus {
// [x: string]: string | Dictionary<string | object>;
// }
export const ActiveMessageCount = 'd2p1:ActiveMessageCount';
export const DeadLetterMessageCount = 'd2p1:DeadLetterMessageCount';
export const ScheduledMessageCount = 'd2p1:ScheduledMessageCount';
export const TransferMessageCount = 'd2p1:TransferMessageCount';
export const TransferDeadLetterMessageCount = 'd2p1:TransferDeadLetterMessageCount';
export interface Topic extends ExtendedBase {
AccessedAt: DateString;
CountDetails: {
'd2p1:ActiveMessageCount': string;
'd2p1:DeadLetterMessageCount': string;
'd2p1:ScheduledMessageCount': string;
'd2p1:TransferMessageCount': string;
'd2p1:TransferDeadLetterMessageCount': string;
};
CountDetails: { [key: string]: string };
EnableSubscriptionPartitioning: string;
FilteringMessagesBeforePublishing: string;
IsExpress: string;
@@ -242,13 +242,7 @@ export namespace Azure.ServiceBus {
}
export interface Subscription extends ExtendedBase {
CountDetails: {
'd3p1:ActiveMessageCount': string;
'd3p1:DeadLetterMessageCount': string;
'd3p1:ScheduledMessageCount': string;
'd3p1:TransferMessageCount': string;
'd3p1:TransferDeadLetterMessageCount': string;
};
CountDetails: { [key: string]: string };
DeadLetteringOnFilterEvaluationExceptions: string;
DeadLetteringOnMessageExpiration: string;
LockDuration: string;
@@ -315,6 +309,8 @@ export namespace Azure.ServiceBus {
export type CreateSubscriptionOptions = Partial<ICreateSubscriptionOptions>;
export type ListSubscriptionsOptions = Partial<PaginationOptions>;
export type ListRulesOptions = Partial<PaginationOptions>;
export type ListTopicsOptions = Partial<PaginationOptions>;
export type ListQueuesOptions = Partial<PaginationOptions>;
export type CreateRuleOptions = Partial<ICreateRuleOptions>;
export type CreateNotificationHubOptions = Partial<ICreateNotificationHubOptions>;
export type ListNotificationHubsOptions = Partial<PaginationOptions>;
+6 -2
View File
@@ -11,6 +11,8 @@ import CreateTopicOptions = Azure.ServiceBus.CreateTopicOptions;
import ListNotificationHubsOptions = Azure.ServiceBus.ListNotificationHubsOptions;
import ListRulesOptions = Azure.ServiceBus.ListRulesOptions;
import ListSubscriptionsOptions = Azure.ServiceBus.ListSubscriptionsOptions;
import ListTopicsOptions = Azure.ServiceBus.ListTopicsOptions;
import ListQueuesOptions = Azure.ServiceBus.ListQueuesOptions;
import MessageOrName = Azure.ServiceBus.MessageOrName;
import Queue = Azure.ServiceBus.Results.Models.Queue;
import ReceiveQueueMessageOptions = Azure.ServiceBus.ReceiveQueueMessageOptions;
@@ -88,7 +90,8 @@ declare class ServiceBusService extends ServiceBusServiceBase {
public getQueue(queuePath: string,
callback: TypedResultAndResponseCallback<Queue>): void;
public listQueues(queuePath: string,
public listQueues(callback: TypedResultAndResponseCallback<Queue[]>): void;
public listQueues(options: ListQueuesOptions,
callback: TypedResultAndResponseCallback<Queue[]>): void;
/*
@@ -115,7 +118,8 @@ declare class ServiceBusService extends ServiceBusServiceBase {
public getTopic(topicPath: string,
callback: TypedResultAndResponseCallback<Topic>): void;
public listTopics(topicPath: string,
public listTopics(callback: TypedResultAndResponseCallback<Topic[]>): void;
public listTopics(options: ListTopicsOptions,
callback: TypedResultAndResponseCallback<Topic[]>): void;
/*
+3 -4
View File
@@ -1,14 +1,13 @@
/// <reference types="node" />
import EventEmitter = NodeJS.EventEmitter;
import ServiceClient = require('azure-sb/lib/serviceclient');
declare class ServiceBusServiceClient extends EventEmitter {
declare class ServiceBusServiceClient extends ServiceClient {
constructor(accessKey?: string,
issuer?: string,
sharedAccessKeyName?: string,
sharedAccessKeyValue?: string,
host?: string,
acsHost?: string,
authenticationProvider?: object);
authenticationProvider?: object);
}
export = ServiceBusServiceClient;
+8
View File
@@ -0,0 +1,8 @@
/// <reference types="node" />
import EventEmitter = NodeJS.EventEmitter;
declare class ServiceClient extends EventEmitter {
public host: string;
public port: number;
public protocol: string;
}
export = ServiceClient;
+2 -1
View File
@@ -30,6 +30,7 @@
"lib/models/subscriptionresult.d.ts",
"lib/models/notificationhubresult.d.ts",
"lib/models/resourceresult.d.ts",
"lib/serviceclient.d.ts",
"lib/servicebusserviceclient.d.ts",
"lib/gcmservice.d.ts",
"lib/wnsservice.d.ts",
@@ -38,4 +39,4 @@
"azure-sb-tests.ts",
"index.d.ts"
]
}
}
+8 -5
View File
@@ -1,6 +1,9 @@
// Type definitions for Marionette 3.3
// Project: https://github.com/marionettejs/
// Definitions by: Zeeshan Hamid <https://github.com/zhamid>, Natan Vivo <https://github.com/nvivo>, Sven Tschui <https://github.com/sventschui>
// Definitions by: Zeeshan Hamid <https://github.com/zhamid>,
// Natan Vivo <https://github.com/nvivo>,
// Sven Tschui <https://github.com/sventschui>,
// Volker Nauruhn <https://github.com/razorness>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -1394,27 +1397,27 @@ export class CollectionView<TModel extends Backbone.Model, TView extends View<TM
* instance is about to be added to the collection view. It provides
* access to the view instance for the child that was added.
*/
onBeforeAddChild(childView: TView): void;
onBeforeAddChild(collectionView: CollectionView<TModel, TView, TCollection>, childView: TView): void;
/**
* This callback function allows you to know when a child / child view
* instance has been added to the collection view. It provides access to
* the view instance for the child that was added.
*/
onAddChild(childView: TView): void;
onAddChild(collectionView: CollectionView<TModel, TView, TCollection>, childView: TView): void;
/**
* This callback function allows you to know when a childView instance is
* about to be removed from the collectionView. It provides access to the
* view instance for the child that was removed.
*/
onBeforeRemoveChild(childView: TView): void;
onBeforeRemoveChild(collectionView: CollectionView<TModel, TView, TCollection>, childView: TView): void;
/**
* This callback function allows you to know when a child / childView
* instance has been deleted or removed from the collection.
*/
onRemoveChild(childView: TView): void;
onRemoveChild(collectionView: CollectionView<TModel, TView, TCollection>, childView: TView): void;
/**
* Automatically destroys this Collection's children and cleans up
+9
View File
@@ -0,0 +1,9 @@
import * as base64url from 'base64-url';
base64url.encode('Node.js is awesome.'); // $ExpectType string
base64url.decode('Tm9kZS5qcyBpcyBhd2Vzb21lLg'); // $ExpectType string
base64url.escape('This+is/goingto+escape=='); // $ExpectType string
base64url.unescape('This-is_goingto-escape'); // $ExpectType string
base64url.encode('string to encode', 'ascii'); // $ExpectType string
base64url.decode('string to decode', 'ascii'); // $ExpectType string
+9
View File
@@ -0,0 +1,9 @@
// Type definitions for base64-url 2.2
// Project: https://github.com/joaquimserafim/base64-url
// Definitions by: Uri Shaked <https://github.com/urish>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export function decode(value: string, encoding?: string): string;
export function encode(value: string, encoding?: string): string;
export function escape(value: string): string;
export function unescape(value: string): 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",
"base64-url-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+106
View File
@@ -0,0 +1,106 @@
import { RequestQuery, Server } from 'hapi';
import * as bell from 'bell';
async function run() {
const server = new Server({ port: 8000 });
await server.register(bell);
server.auth.strategy('arcgisonline', 'bell', {
provider: 'twitter',
password: 'some cookie password',
location: 'http://example.com/oauth',
clientId: '',
clientSecret: '',
scope(request) {
const scopes = ['public_profile', 'email'];
if ((<RequestQuery> request.query).wantsSharePermission) {
scopes.push('publish_actions');
}
return scopes;
}
});
const providers: bell.BellOptions[] = [{
provider: 'discord',
password: 'cookie_encryption_password_secure',
isSecure: false,
clientId: '',
clientSecret: '',
location: () => '',
},
{
provider: 'facebook',
password: 'cookie_encryption_password_secure',
isSecure: false,
clientId: '',
clientSecret: '',
location: server.info.uri
},
{
provider: 'google',
password: 'cookie_encryption_password_secure',
isSecure: false,
clientId: '',
clientSecret: '',
location: server.info.uri
},
{
provider: 'linkedin',
password: 'cookie_encryption_password_secure',
isSecure: false,
clientId: '',
clientSecret: '',
providerParams: {
redirect_uri: server.info.uri + '/bell/door'
}
},
{
provider: 'meetup',
password: 'cookie_encryption_password_secure',
isSecure: false,
clientId: '',
clientSecret: '',
scope: ['basic', 'ageless', 'group_edit', 'reporting'],
},
{
provider: 'nest',
password: 'cookie_encryption_password_secure',
isSecure: false,
clientId: '',
clientSecret: ''
},
{
provider: 'office365',
clientId: '',
clientSecret: '',
password: 'cookie_encryption_password_secure',
providerParams: {
response_type: 'code'
},
scope: ['openid', 'offline_access', 'profile']
},
{
provider: 'okta',
config: { uri: 'https://your-organization.okta.com' },
password: 'cookie_encryption_password_secure',
isSecure: false,
location: 'http://127.0.0.1:8000',
clientId: '',
clientSecret: ''
},
{
provider: 'slack',
password: 'cookie_encryption_password_secure',
isSecure: false,
clientId: '',
clientSecret: ''
},
{
provider: 'twitch',
password: 'cookie_encryption_password_secure',
isSecure: false,
clientId: '',
clientSecret: '',
scope: ['user_read', 'channel_read']
}];
}
+269
View File
@@ -0,0 +1,269 @@
// Type definitions for bell 9.1
// Project: https://github.com/hapijs/bell
// Definitions by: Simon Schick <https://github.com/SimonSchick>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.7
import { Server, Request, Plugin, AuthCredentials } from 'hapi';
declare module 'hapi' {
interface ServerAuth {
strategy(name: string, scheme: 'bell', options: BellOptions): void;
strategy(
name: string,
scheme: 'bell',
mode: boolean | 'required' | 'optional' | 'try',
options: BellOptions,
): void;
}
}
export interface StringLikeMap {
[key: string]: string | number;
}
export type Provider =
'arcgisonline' |
'auth0' |
'azuread' |
'bitbucket' |
'digitalocean' |
'discord' |
'dropbox' |
'dropboxV2' |
'facebook' |
'fitbit' |
'foursquare' |
'github' |
'gitlab' |
'google' |
'googleplus' |
'instagram' |
'linkedin' |
'live' |
'medium' |
'meetup' |
'mixer' |
'nest' |
'office365' |
'okta' |
'phabricator' |
'pingfed' |
'pinterest' |
'reddit' |
'salesforce' |
'slack' |
'spotify' |
'stripe' |
'trakt' |
'tumblr' |
'twitch' |
'twitter' |
'vk' |
'wordpress' |
'yahoo';
export type RequestPassThrough = (
request: Request,
next: (err: Error | null, credentials: AuthCredentials) => void,
) => void;
export interface OptionalOptions {
/**
* the name of the cookie used to manage the temporary state.
* Defaults to 'bell-provider' where 'provider' is the provider name (or 'custom' for custom providers).
* For example, the Twitter cookie name defaults to 'bell-twitter'.
*/
cookie?: string;
/**
* sets the cookie secure flag.
* Defaults to true.
*/
isSecure?: boolean;
/**
* sets the cookie HTTP only flag.
* Defaults to true.
*/
isHttpOnly?: boolean;
/**
* cookie time-to-live in milliseconds.
* Defaults to null (session time-life - cookies are deleted when the browser is closed).
*/
ttl?: number;
/**
* the domain scope.
* Defaults to null (no domain).
*/
domain?: string;
/**
* provider-specific query parameters for the authentication endpoint.
* It may be passed either as an object to merge into the query string,
* or a function which takes the client's request and returns an object.
* Each provider supports its own set of parameters which customize the user's login experience.
* For example:
* * Facebook supports `display` ('page', 'popup', or 'touch'), `auth_type`, `auth_nonce`.
* * Google supports `access_type`, `approval_prompt`, `prompt`, `login_hint`, `user_id`, `hd`.
* * Twitter supports `force_login`, `screen_name`.
* * Linkedin supports `fields`.
*/
providerParams?: StringLikeMap | ((request: Request) => StringLikeMap);
/**
* allows passing query parameters from a bell protected endpoint to the auth request.
* It will merge the query params you pass along with the providerParams and any other predefined ones.
* Be aware that this will override predefined query parameters!
* Default to false.
*/
allowRuntimeProviderParams?: StringLikeMap | boolean;
/**
* Each built-in vendor comes with the required scope for basic profile information.
* Use scope to specify a different scope as required by your application.
* It may be passed either as an object to merge into the query string,
* or a function which takes the client's request and returns an object.
* Consult the provider for their specific supported scopes.
*/
scope?: string[] | ((request: Request) => string[]);
/**
* skips obtaining a user profile from the provider.
* Useful if you need specific scopes,
* but not the user profile.
* Defaults to false.
*/
skipProfile?: boolean;
/**
* a configuration object used to customize the provider settings.
* The built-in 'twitter' provider accepts the `extendedProfile` & `getMethod` options.
* option which allows disabling the extra profile request when the provider
* returns the user information in the callback (defaults to true).
* The built-in 'github' and 'phabricator' providers accept the uri
* option which allows pointing to a private enterprise installation (e.g. 'https://vpn.example.com').
* See Providers documentation for more information.
*/
config?: { extendedProfile?: boolean; getMethod?: string } | { uri?: string };
/**
* an object of key-value pairs that specify additional
* URL query parameters to send with the profile request to the provider.
* The built-in facebook provider,
* for example, could have fields specified to determine the fields returned from the user's graph,
* which would then be available to you in the auth.credentials.profile.raw object.
*/
profileParams?: StringLikeMap;
/**
* allows passing additional OAuth state from initial request.
* This must be a function returning a string,
* which will be appended to the bell internal state parameter for OAuth code flow.
*/
runtimeStateCallback?(req: Request): string;
// THESE ARE IN THE *REQUIRED* section but are actually not...
/**
* A boolean indicating whether or not you want the redirect_uri to be forced to https.
* Useful if your hapi application runs as http, but is accessed through https.
*/
forceHttps?: boolean;
/**
* Set the base redirect_uri manually if it cannot be inferred properly from server settings.
* Useful to override port, protocol, and host if proxied or forwarded.
*/
location?: string | ((req: Request) => string);
}
export interface RequiredProviderOptions {
/**
* the cookie encryption password.
* Used to encrypt the temporary state cookie used by the module in
* between the authorization protocol steps.
*/
password: string;
/**
* the OAuth client identifier (consumer key).
*/
clientId: string;
/**
* the OAuth client secret (consumer secret)
*/
clientSecret: string;
}
export interface KnownProviderOptions extends RequiredProviderOptions, OptionalOptions {
provider: Provider;
}
/**
* @param uri the requested resource URI (bell will add the token or authentication header as needed).
* @param params any URI query parameters (cannot include them in the URI due to signature requirements).
*/
export type AuthedRequest = (uri: string, params: { [key: string]: string } | null) => Promise<any>;
export interface CustomProtocol {
/**
* the authorization protocol used.
*/
protocol: 'oauth' | 'oauth2';
/**
* the OAuth signature method (OAuth 1.0a only). Must be one of:
* * 'HMAC-SHA1' - default
* * 'RSA-SHA1' - in that case, the clientSecret is your RSA private key
*/
signatureMethod?: 'HMAC-SHA1' | 'RSA-SHA1';
/**
* the temporary credentials (request token) endpoint (OAuth 1.0a only).
*/
temporary?: string;
/**
* boolean that determines if OAuth client id and client secret will be sent
* as parameters as opposed to an Authorization header (OAuth 2.0 only).
* Defaults to false.
*/
useParamsAuth?: boolean;
/**
* the authorization endpoint URI.
*/
auth: string;
/**
* the access token endpoint URI.
*/
token: string;
/**
* the OAuth version.
*/
version?: string;
/**
* an array of scope strings (OAuth 2.0 only).
*/
scope?: string[] | ((query: StringLikeMap) => string[]);
/**
* the scope separator character (OAuth 2.0 only). Only required when a provider has a broken OAuth 2.0 implementation. Defaults to space (Facebook and GitHub default to comma).
*/
scopeSeparator?: string;
/**
* a headers object with additional headers required by the provider
* (e.g. GitHub required the 'User-Agent' header which is set by default).
*/
headers?: {
[key: string]: string;
};
/**
* a function used to obtain user profile information and normalize it.
* @param credentials the credentials object.
* Change the object directly within the function (profile information is typically stored under credentials.profile).
* @param params the parsed information received from the provider (e.g. token, secret, and other custom fields).
* @param get an OAuth helper function to make authenticated requests using the credentials received.
*/
profile(credentials: any, params: { [key: string]: string }, get: AuthedRequest): Promise<void>;
}
export interface CustomProviderOptions extends RequiredProviderOptions, OptionalOptions {
provider: CustomProtocol;
}
export type BellOptions = CustomProviderOptions | KnownProviderOptions;
export const plugin: Plugin<CustomProviderOptions | KnownProviderOptions>;
/**
* Enables simulation mode.
*/
export function simulate(credentialsFunc: RequestPassThrough): void;
/**
* [See docs](https://github.com/hapijs/bell/blob/master/API.md#simulated-authentication)
* Disables simulation mode
*/
export function simulate(state: false): void;
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"strictFunctionTypes": true,
"strictNullChecks": true,
"noImplicitAny": true,
"noImplicitThis": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"bell-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"unified-signatures": false // Disabling as it prevents me from using overloaded doctags
}
}
+18
View File
@@ -102,6 +102,12 @@ export interface BigConstructor {
export interface Big {
/** Returns a Big number whose value is the absolute value, i.e. the magnitude, of this Big number. */
abs(): Big;
/**
* Returns a Big number whose value is the value of this Big number plus n - alias for .plus().
*
* @throws `NaN` if n is invalid.
*/
add(n: BigSource): Big;
/**
* Compare the values.
*
@@ -162,6 +168,12 @@ export interface Big {
* @throws `NaN` if n is negative or otherwise invalid.
*/
mod(n: BigSource): Big;
/**
* Returns a Big number whose value is the value of this Big number times n - alias for .times().
*
* @throws `NaN` if n is invalid.
*/
mul(n: BigSource): Big;
/**
* Returns a Big number whose value is the value of this Big number plus n.
*
@@ -196,6 +208,12 @@ export interface Big {
* @throws `NaN` if this Big number is negative.
*/
sqrt(): Big;
/**
* Returns a Big number whose value is the value of this Big number minus n - alias for .minus().
*
* @throws `NaN` if n is invalid.
*/
sub(n: BigSource): Big;
/**
* Returns a Big number whose value is the value of this Big number times n.
*
+3
View File
@@ -86,6 +86,7 @@ function minusTests() {
0.3 - 0.1; // 0.19999999999999998
const x = new Big(0.3);
x.minus(0.1); // '0.2'
x.sub(0.1); // '0.2'
}
function modTests() {
@@ -99,6 +100,7 @@ function plusTests() {
const x = new Big(0.1);
const y = x.plus(0.2); // '0.3'
Big(0.7).plus(x).plus(y); // '1'
Big(0.7).add(x).add(y); // '1'
}
function powTests() {
@@ -138,6 +140,7 @@ function timesTests() {
const x = new Big(0.6);
const y = x.times(3); // '1.8'
Big('7e+500').times(y); // '1.26e+501'
Big('7e+500').mul(y); // '1.26e+501'
}
function toExponentialTests() {
+3
View File
@@ -88,6 +88,7 @@ function minusTests() {
0.3 - 0.1; // 0.19999999999999998
const x = new Big(0.3);
x.minus(0.1); // '0.2'
x.sub(0.1); // '0.2'
}
function modTests() {
@@ -101,6 +102,7 @@ function plusTests() {
const x = new Big(0.1);
const y = x.plus(0.2); // '0.3'
Big(0.7).plus(x).plus(y); // '1'
Big(0.7).add(x).add(y); // '1'
}
function powTests() {
@@ -140,6 +142,7 @@ function timesTests() {
const x = new Big(0.6);
const y = x.times(3); // '1.8'
Big('7e+500').times(y); // '1.26e+501'
Big('7e+500').mul(y); // '1.26e+501'
}
function toExponentialTests() {
+7
View File
@@ -7,3 +7,10 @@ const b3 = b1.multiply(b2);
console.log(b3.toHex());
// => ae499bfe762edfb416d0ce71447af67ff33d1760cbebd70874be1d7a5564b0439a59808cb1856a91974f7023f72132
const b4 = BigInteger.valueOf(42);
const b5 = BigInteger.valueOf(10);
const b6 = b4.multiply(b5);
console.log(b6);
// => BigInteger { '0': 420, '1': 0, t: 1, s: 0 }
+1 -1
View File
@@ -87,7 +87,7 @@ declare class bigi {
static fromDERInteger(byteArray?: any): number;
static fromHex(hex: string): bigi;
static isBigInteger(obj: any, check_ver: any): obj is bigi;
static valueOf(i: any): number;
static valueOf(i: any): bigi;
}
declare namespace bigi {
interface Constants {
+4
View File
@@ -71,6 +71,10 @@ export class ECPair {
d: BigInteger;
readonly compressed: boolean;
readonly network: Network;
getAddress(): string;
getNetwork(): Network;
+1 -1
View File
@@ -11,7 +11,7 @@ import stream = require('stream');
declare class BufferList extends stream.Duplex {
constructor(callback?: (err: Error, buffer: Buffer) => void);
append(buffer: Buffer): void;
append(buffer: Buffer | Buffer[] | BufferList | BufferList[] | string): void;
get(index: number): number;
slice(start?: number, end?: number): Buffer;
copy(dest: Buffer, destStart?: number, srcStart?: number, srcEnd?: number): void;
+14 -1
View File
@@ -10,7 +10,20 @@ type DatepickerEvents = "show"|"hide"|"clearDate"|"changeDate"|"changeMonth"|"ch
type DatepickerViewModes = 0|"days"|1|"months"|2|"years"|3|"decades"|4|"centuries"|"millenium";
type DatepickerOrientations = "auto"|"left top"|"left bottom"|"right top"|"right bottom";
type DatepickerOrientations =
"auto"
| "left top"
| "left bottom"
| "right top"
| "right bottom"
| "top auto"
| "bottom auto"
| "auto left"
| "top left"
| "bottom left"
| "auto right"
| "top right"
| "bottom right"
/**
* All options that take a “Date” can handle a Date object; a String
+11
View File
@@ -43,10 +43,15 @@ $("#carousel").on("slide.bs.carousel", function(ev) {
$("#carousel").carousel({
interval: 5000,
keyboard: true,
slide: false,
pause: "hover",
wrap: true,
});
$("#carousel").carousel({
slide: "prev",
});
$("#carousel").carousel({
pause: false,
});
@@ -96,6 +101,8 @@ $("#dropdown").dropdown({
offset: 10,
flip: false,
boundary: "window",
reference: "toggle",
display: "dynamic",
});
$("#dropdown").dropdown({
@@ -114,6 +121,10 @@ $("#dropdown").dropdown({
boundary: document.body,
});
$("#dropdown").dropdown({
reference: document.body,
});
// --------------------------------------------------------------------------------------
// Modal
// --------------------------------------------------------------------------------------
+27 -2
View File
@@ -1,4 +1,4 @@
// Type definitions for Bootstrap 4.0
// Type definitions for Bootstrap 4.1
// Project: https://github.com/twbs/bootstrap/
// Definitions by: denisname <https://github.com/denisname>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -55,6 +55,14 @@ export interface CarouselOption {
*/
keyboard?: boolean;
/**
* Use to easily control the position of the carousel. It accepts the keywords prev or next, which alters the slide position
* relative to its current position. Alternatively, use `data-slide-to` to pass a raw slide index to the carousel.
*
* @default false
*/
slide?: "next" | "prev" | false;
/**
* If set to "hover", pauses the cycling of the carousel on mouseenter and resumes the cycling of the carousel on mouseleave.
* If set to false, hovering over the carousel won't pause it.
@@ -116,6 +124,21 @@ export interface DropdownOption {
* @default "scrollParent"
*/
boundary?: Popper.Boundary | HTMLElement;
/**
* Reference element of the dropdown menu. Accepts the values of 'toggle', 'parent', or an HTMLElement reference.
* For more information refer to Popper.js's referenceObject docs.
*
* @default "toggle"
*/
reference?: "toggle" | "parent" | HTMLElement;
/**
* By default, we use Popper.js for dynamic positioning. Disable this with 'static'.
*
* @default "dynamic"
*/
display?: "dynamic" | "static";
}
export interface ModalOption {
@@ -154,6 +177,8 @@ export interface PopoverOption extends TooltipOption {
* Default content value if data-content attribute isn't present.
* If a function is given, it will be called with its this reference
* set to the element that the popover is attached to.
*
* @default ""
*/
content?: string | Element | ((this: Element) => string | Element);
}
@@ -226,7 +251,7 @@ export interface TooltipOption {
* the tooltip or popover DOM node as its first argument and the triggering element DOM node as its second.
* The this context is set to the tooltip or popover instance.
*
* @default "top"
* @default tooltip: "top", popover: "right"
*/
placement?: Placement | ((this: TooltipInstance<this>, node: HTMLElement, trigger: Element) => Placement);
+260 -16
View File
@@ -8,11 +8,98 @@ import browserSync = require("browser-sync");
})();
browserSync({
server: {
baseDir: "./"
ui: true
});
browserSync({
ui: {
port: 9000,
weinre: {
port: 9001
}
}
});
browserSync({
files: "app/css/style.css"
});
browserSync({
files: [
"app/css/style.css",
"app/js/*.js"
]
});
browserSync({
files: [
"app/css/style.css",
"!app/js/*.js"
]
});
browserSync({
files: [
"wp-content/themes/**/*.css",
{
match: ["wp-content/themes/**/*.css"],
fn: function (event, file) {
/** Custom event handler **/
}
}
]
});
browserSync({
watchEvents: [
"change",
"add",
"unlink",
"addDir",
"unlinkDir"
]
});
browserSync({
watch: true
});
browserSync({
ignore: [
"app/js/*.js"
]
});
browserSync({
single: true
});
browserSync({
watchOptions: {
ignoreInitial: true,
ignored: '*.txt'
},
files: ['./app']
});
browserSync({
files: [
{
match: ["wp-content/themes/**/*.php"],
fn: function (event, file) {
/** Custom event handler **/
},
options: {
ignored: '*.txt'
}
}
]
});
browserSync({
server: "app"
});
// multiple base directory
browserSync({
server: {
@@ -20,6 +107,39 @@ browserSync({
}
});
browserSync({
server: true
});
browserSync({
server: {
baseDir: "./"
}
});
browserSync({
server: {
baseDir: "./",
index: "index.htm"
}
});
browserSync({
server: {
baseDir: "./",
directory: true
}
});
browserSync({
server: {
baseDir: "app",
serveStaticOptions: {
extensions: ["html"]
}
}
});
browserSync({
proxy: "yourlocal.dev"
});
@@ -27,8 +147,8 @@ browserSync({
browserSync({
proxy: {
target: "http://yourlocal.dev",
proxyReq: function(proxyReq) {
console.log(proxyReq);
proxyReq: function (proxyReq) {
console.log(proxyReq);
}
}
});
@@ -37,7 +157,7 @@ browserSync({
proxy: {
target: "http://yourlocal.dev",
proxyReq: [
function(proxyReq) {
function (proxyReq) {
console.log(proxyReq);
}
]
@@ -47,7 +167,7 @@ browserSync({
browserSync({
proxy: {
target: "http://yourlocal.dev",
proxyRes: function(proxyRes, req, res) {
proxyRes: function (proxyRes, req, res) {
console.log(proxyRes);
}
}
@@ -57,13 +177,137 @@ browserSync({
proxy: {
target: "http://yourlocal.dev",
proxyRes: [
function(proxyRes, req, res) {
function (proxyRes, req, res) {
console.log(proxyRes);
}
]
}
});
browserSync({
proxy: "https://yourlocal.dev",
https: {
key: "./path/to/the/key/file.key",
cert: "./path/to/the/cert/file.cer"
}
});
browserSync({
port: 3000
});
browserSync({
proxy: "http://yourlocal.dev",
serveStatic: ['.', './app/css']
});
browserSync({
proxy: "http://yourlocal.dev",
serveStatic: [{
route: '/assets',
dir: 'tmp'
}]
});
browserSync({
proxy: "http://yourlocal.dev",
serveStatic: [{
route: ['/assets', '/content'],
dir: 'tmp'
}]
});
browserSync({
proxy: "http://yourlocal.dev",
serveStatic: [{
route: '/assets',
dir: ['./tmp', './app']
}]
});
browserSync({
serveStatic: ['.', './app', './temp'],
serveStaticOptions: {
extensions: ['html'] // pretty urls
}
});
browserSync({
https: true
});
browserSync({
server: "./app",
https: true
});
browserSync({
server: "./app",
https: {
key: "./path/to/the/key/file.key",
cert: "./path/to/the/cert/file.cer"
}
});
browserSync({
httpModule: "http2"
});
browserSync({
ghostMode: {
clicks: true,
scroll: true,
forms: {
inputs: true,
submit: true,
toggles: true
}
},
proxy: "https://yourlocal.dev"
});
/**
* Not testing a bunch because they are either only string or boolean types.
* ....Also just got lazy and tired of writing the simple ones.
*/
browserSync({
snippetOptions: {
// Ignore all HTML files within the templates folder
blacklist: [
"templates/*.html"
],
// Provide a custom Regex for inserting the snippet.
rule: {
match: /<\/body>/i,
fn: function (snippet, match) {
return snippet + match;
}
}
}
});
browserSync({
rewriteRules: [
{
match: /Browsersync/g,
fn: function (req, res, match) {
return 'kittenz';
}
}
]
});
browserSync({
rewriteRules: [
{
match: /(cats|kitten[sz]) are mediocre/g,
replace: "$1 are excellent"
}
]
});
var config = {
server: {
baseDir: "./"
@@ -84,13 +328,13 @@ browserSync(config, function (err, bs) {
browserSync.reload();
// single file
browserSync.reload( "styles.css" );
browserSync.reload("styles.css");
// multiple files
browserSync.reload( ["styles.css", "ie.css"] );
browserSync.reload(["styles.css", "ie.css"]);
// streams support
browserSync.reload( { stream: true } );
browserSync.reload({ stream: true });
browserSync.notify("Compiling, please wait!");
@@ -143,19 +387,19 @@ browser.exit();
browser.stream();
// -- "once" option.
browser.stream({once: true});
browser.stream({ once: true });
// -- "match" option (string).
browser.stream({match: "**/*.js"});
browser.stream({ match: "**/*.js" });
// -- "match" option (RegExp).
browser.stream({match: /\.js$/});
browser.stream({ match: /\.js$/ });
// -- "match" option (function).
browser.stream({match: (testString) => true});
browser.stream({ match: (testString) => true });
// -- "match" option (array).
browser.stream({match: ["**/*.js", /\.js$/, (testString) => true]});
browser.stream({ match: ["**/*.js", /\.js$/, (testString) => true] });
// -- Both options.
browser.stream({once: true, match: ["**/*.js", /\.js$/, (testString) => true]});
browser.stream({ once: true, match: ["**/*.js", /\.js$/, (testString) => true] });
+119 -28
View File
@@ -1,16 +1,21 @@
// Type definitions for browser-sync
// Project: http://www.browsersync.io/
// Definitions by: Asana <https://asana.com>, Joe Skeen <https://github.com/joeskeen>
// Definitions by: Asana <https://asana.com>,
// Joe Skeen <https://github.com/joeskeen>
// Thomas "Thasmo" Deinhamer <https://thasmo.com/>
// Kiyotoshi Ichikawa <https://github.com/aznnomness>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/// <reference types="chokidar"/>
/// <reference types="node" />
/// <reference types="serve-static" />
import * as chokidar from "chokidar";
import * as fs from "fs";
import * as http from "http";
import * as mm from "micromatch";
import { ServeStaticOptions } from "serve-static";
declare namespace browserSync {
interface Options {
@@ -20,7 +25,7 @@ declare namespace browserSync {
*
* port - Default: 3001
* weinre.port - Default: 8080
* Note: requires at least version 2.0.0
* Note: Requires at least version 2.0.0.
*/
ui?: UIOptions | boolean;
/**
@@ -29,20 +34,40 @@ declare namespace browserSync {
* patterns.
* Default: false
*/
files?: string | (string | FileCallback)[];
files?: string | (string | FileCallback | object)[];
/**
* Specify which file events to respond to.
* Available events: `add`, `change`, `unlink`, `addDir`, `unlinkDir`
*/
watchEvents?: string[];
/**
* Watch files automatically.
*/
watch?: boolean;
/**
* Patterns for any watchers to ignore.
* Anything provided here will end up inside 'watchOptions.ignored'.
*/
ignore?: string[];
/**
* Serve an index.html file for all non-asset routes.
* Useful when using client-routers.
*/
single?: boolean;
/**
* File watching options that get passed along to Chokidar. Check their docs for available options
* Default: undefined
* Note: requires at least version 2.6.0
* Note: Requires at least version 2.6.0.
*/
watchOptions?: chokidar.WatchOptions;
/**
* Use the built-in static server for basic HTML/JS/CSS websites.
* Default: false
*/
server?: ServerOptions;
server?: string | boolean | string[] | ServerOptions;
/**
* Proxy an EXISTING vhost. Browsersync will wrap your vhost with a proxy URL to view your site.
* Passing only a URL as a string equates to passing only target property of ProxyOptions type.
* target - Default: undefined
* ws - Default: undefined
* middleware - Default: undefined
@@ -50,25 +75,40 @@ declare namespace browserSync {
* proxyRes - Default: undefined
* proxyReq - Default: undefined
*/
proxy?: string | boolean | ProxyOptions;
proxy?: string | ProxyOptions;
/**
* Use a specific port (instead of the one auto-detected by Browsersync)
* Default: 3000
*/
port?: number;
/**
* Functions or actual plugins used as middleware.
*/
middleware?: MiddlewareHandler | PerRouteMiddleware | (MiddlewareHandler | PerRouteMiddleware)[];
/**
* Add additional directories from which static files should be served.
* Should only be used in proxy or snippet mode.
* Default: []
* Note: requires at least version 2.8.0
* Note: Requires at least version 2.8.0.
*/
serveStatic?: string[];
serveStatic?: (string | { route?: string | string[], dir?: string | string[]})[];
/**
* Options that are passed to the serve-static middleware when you use the
* string[] syntax: eg: `serveStatic: ['./app']`.
* Please see [serve-static](https://github.com/expressjs/serve-static) for details.
*/
serveStaticOptions?: ServeStaticOptions;
/**
* Enable https for localhost development.
* Note - this is not needed for proxy option as it will be inferred from your target url.
* Note: requires at least version 1.3.0
* Note: This may not be needed for proxy option as it will try to infer from your target url.
* Note: If privacy error is encountered please see HttpsOptions below, setting those will resolve.
* Note: Requires at least version 1.3.0.
*/
https?: boolean;
https?: boolean | HttpsOptions;
/**
* Override http module to allow using 3rd party server modules (such as http2).
*/
httpModule?: string;
/**
* Clicks, Scrolls & Form inputs on any device will be mirrored to all others.
* clicks - Default: true
@@ -84,7 +124,7 @@ declare namespace browserSync {
/**
* Change the console logging prefix. Useful if you're creating your own project based on Browsersync
* Default: BS
* Note: requires at least version 1.5.1
* Note: Requires at least version 1.5.1.
*/
logPrefix?: string;
/**
@@ -100,19 +140,19 @@ declare namespace browserSync {
/**
* Log the snippet to the console when you're in snippet mode (no proxy/server)
* Default: true
* Note: requires at least version 1.5.2
* Note: Requires at least version 1.5.2.
*/
logSnippet?: boolean;
/**
* You can control how the snippet is injected onto each page via a custom regex + function.
* You can also provide patterns for certain urls that should be ignored from the snippet injection.
* Note: requires at least version 2.0.0
* Note: Requires at least version 2.0.0.
*/
snippetOptions?: SnippetOptions;
/**
* Add additional HTML rewriting rules.
* Default: false
* Note: requires at least version 2.4.0
* Note: Requires at least version 2.4.0.
*/
rewriteRules?: boolean | RewriteRules[];
/**
@@ -139,7 +179,7 @@ declare namespace browserSync {
/**
* Add HTTP access control (CORS) headers to assets served by Browsersync.
* Default: false
* Note: requires at least version 2.16.0
* Note: Requires at least version 2.16.0.
*/
cors?: boolean;
/**
@@ -177,12 +217,12 @@ declare namespace browserSync {
/**
* Sync the scroll position of any element on the page. Add any amount of CSS selectors
* Default: []
* Note: requires at least version 2.9.0
* Note: Requires at least version 2.9.0.
*/
scrollElements?: string[];
/**
* Default: []
* Note: requires at least version 2.9.0
* Note: Requires at least version 2.9.0.
* Sync the scroll position of any element on the page - where any scrolled element will cause
* all others to match scroll position. This is helpful when a breakpoint alters which element
* is actually scrolling
@@ -197,13 +237,18 @@ declare namespace browserSync {
/**
* Restrict the frequency in which browser:reload events can be emitted to connected clients
* Default: 0
* Note: requires at least version 2.6.0
* Note: Requires at least version 2.6.0.
*/
reloadDebounce?: number;
/**
* Emit only the first event during sequential time windows of a specified duration.
* Note: Requires at least version 2.13.0.
*/
reloadThrottle?: number;
/**
* User provided plugins
* Default: []
* Note: requires at least version 2.6.0
* Note: Requires at least version 2.6.0.
*/
plugins?: any[];
/**
@@ -224,6 +269,10 @@ declare namespace browserSync {
* Override host detection if you know the correct IP to use
*/
host?: string;
/**
* Support environments where dynamic hostnames are not required (ie: electron).
*/
localOnly?: boolean;
/**
* Send file-change events to the browser
* Default: true
@@ -234,10 +283,16 @@ declare namespace browserSync {
* Default: true
*/
timestamps?: boolean;
/**
* ¯\_(ツ)_/¯
* Best guess, when ghostMode (or SocketIO?) is setup the events
* listed here will be emitted and able to hook into.
*/
clientEvents?: string[];
/**
* Alter the script path for complete control over where the Browsersync Javascript is served
* from. Whatever you return from this function will be used as the script path.
* Note: requires at least version 1.5.0
* Note: Requires at least version 1.5.0.
*/
scriptPath?: (path: string) => string;
/**
@@ -248,10 +303,21 @@ declare namespace browserSync {
* domain - Default: undefined
* port - Default: undefined
* clients.heartbeatTimeout - Default: 5000
* Note: requires at least version 1.6.2
* Note: Requires at least version 1.6.2.
*/
socket?: SocketOptions;
middleware?: MiddlewareHandler | PerRouteMiddleware | (MiddlewareHandler | PerRouteMiddleware)[];
/**
* ¯\_(ツ)_/¯
*/
tagNames?: TagNamesOptions;
/**
* ¯\_(ツ)_/¯
*/
injectFileTypes?: string[];
/**
* ¯\_(ツ)_/¯
*/
excludeFileTypes?: string[];
}
interface Hash<T> {
@@ -287,6 +353,7 @@ declare namespace browserSync {
routes?: Hash<string>;
/** configure custom middleware */
middleware?: (MiddlewareHandler | PerRouteMiddleware)[];
serveStaticOptions?: ServeStaticOptions
}
interface ProxyOptions {
@@ -298,6 +365,11 @@ declare namespace browserSync {
proxyReq?: ((res: http.ServerRequest) => any)[] | ((res: http.ServerRequest) => any);
}
interface HttpsOptions {
key?: string;
cert?: string;
}
interface MiddlewareHandler {
(req: http.IncomingMessage, res: http.ServerResponse, next: Function): any;
}
@@ -310,11 +382,17 @@ declare namespace browserSync {
interface GhostOptions {
clicks?: boolean;
scroll?: boolean;
forms?: boolean;
forms?: boolean | {
submit?: boolean;
inputs?: boolean;
toggles?: boolean;
};
}
interface SnippetOptions {
ignorePaths?: string;
async?: boolean,
whitelist?: string[],
blacklist?: string[],
rule?: { match?: RegExp; fn?: (snippet: string, match: string) => any };
}
@@ -327,9 +405,22 @@ declare namespace browserSync {
clients?: { heartbeatTimeout?: number; };
}
interface TagNamesOptions {
less?: string;
scss?: string;
css?: string;
jpg?: string;
jpeg?: string;
png?: string;
svg?: string;
gif?: string;
js?: string;
}
interface RewriteRules {
match: RegExp;
fn: (match: string) => string;
replace?: string;
fn?: (req: http.IncomingMessage, res: http.ServerResponse, match: string) => string;
}
interface StreamOptions {
@@ -342,7 +433,7 @@ declare namespace browserSync {
* Start the Browsersync service. This will launch a server, proxy or start the snippet mode
* depending on your use-case.
*/
(config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance;
(config?: Options, callback?: (err: Error, bs: object) => any): BrowserSyncInstance;
/**
* Create a Browsersync instance
* @param name an identifier that can used for retrieval later
@@ -367,7 +458,7 @@ declare namespace browserSync {
* Start the Browsersync service. This will launch a server, proxy or start the snippet mode
* depending on your use-case.
*/
init(config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance;
init(config?: Options, callback?: (err: Error, bs: object) => any): BrowserSyncInstance;
/**
* Reload the browser
* The reload method will inform all browsers about changed files and will either cause the browser
+8 -1
View File
@@ -6,7 +6,7 @@ bson.ObjectID.cacheHexString = true
let BSON = new bson.BSON();
let Long = bson.Long;
let doc = {long: Long.fromNumber(100)}
let doc = { long: Long.fromNumber(100) }
// Serialize a document
let data = BSON.serialize(doc, false, true, false);
@@ -19,3 +19,10 @@ console.log("doc_2:", doc_2);
BSON = new bson.BSON();
data = BSON.serialize(doc);
doc_2 = BSON.deserialize(data);
// Calculate Object Size
BSON = new bson.BSON();
console.log("Calculated Object size - no options object:", BSON.calculateObjectSize(doc));
console.log("Calculated Object size - empty options object:", BSON.calculateObjectSize(doc, {}));
console.log("Calculated Object size - custom options object:", BSON.calculateObjectSize(doc, { ignoreUndefined: false, serializeFunctions: true }));
+16
View File
@@ -16,6 +16,14 @@ export interface DeserializeOptions {
/** {Boolean, default:false}, deserialize Binary data directly into node.js Buffer object. */
promoteBuffers?: boolean;
}
export interface CalculateObjectSizeOptions {
/** {Boolean, default:false}, serialize the javascript functions */
serializeFunctions?: boolean;
/** {Boolean, default:true}, ignore undefined fields. */
ignoreUndefined?: boolean;
}
export class BSON {
/**
* @param {Object} object the Javascript object to serialize.
@@ -26,6 +34,14 @@ export class BSON {
*/
serialize(object: any, checkKeys?: boolean, asBuffer?: boolean, serializeFunctions?: boolean): Buffer;
deserialize(buffer: Buffer, options?: DeserializeOptions, isArray?: boolean): any;
/**
* Calculate the bson size for a passed in Javascript object.
*
* @param {Object} object the Javascript object to calculate the BSON byte size for.
* @param {CalculateObjectSizeOptions} Options
* @return {Number} returns the number of bytes the BSON object will take up.
*/
calculateObjectSize(object: any, options?: CalculateObjectSizeOptions): number;
}
export class Binary {
+1 -1
View File
@@ -42,7 +42,7 @@ declare namespace Bull {
* When specified, the `Queue` will use this function to create new `ioredis` client connections.
* This is useful if you want to re-use connections.
*/
createClient?(type: 'client' | 'subscriber', redisOpts?: Redis.RedisOptions): Redis.Redis;
createClient?(type: 'client' | 'subscriber' | 'bclient', redisOpts?: Redis.RedisOptions): Redis.Redis;
/**
* Prefix to use for all redis keys
+20
View File
@@ -1798,6 +1798,26 @@ function legend_custom() {
});
}
function legend_tiles() {
const chart = c3.generate({
data: {
columns: [
["sample", 30, 200, 100, 400, 150, 250]
]
},
legend: {
// amount of padding to put between each legend element
padding: 5,
// define custom height and width for the legend item tile
item: {
tile: {
width: 15,
height: 2
}
}
}});
}
/////////////////////
// Tooltip Tests
/////////////////////
+62 -31
View File
@@ -1,11 +1,12 @@
// Type definitions for C3js 0.4
// Type definitions for C3js 0.6
// Project: http://c3js.org/
// Definitions by: Marc Climent <https://github.com/mcliment>
// Gerin Jacob <https://github.com/gerinjacob>
// Bernd Hacker <https://github.com/denyo>
// Dzmitry Shyndzin <https://github.com/dmitryshindin>
// Tim Niemueller <https://github.com/timn>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
// TypeScript Version: 2.3
import * as d3 from "d3";
@@ -28,7 +29,7 @@ export interface ChartConfiguration {
* Note: When chart is not binded, c3 starts observing if chart.element is binded by MutationObserver. In this case, polyfill is required in IE9 and IE10 becuase they do not support
* MutationObserver. On the other hand, if chart always will be binded, polyfill will not be required because MutationObserver will never be called.
*/
bindto?: string | HTMLElement | d3.Selection<any> | null;
bindto?: string | HTMLElement | d3.Selection<any, any, any, any> | null;
size?: {
/**
* The desired width of the chart element.
@@ -172,16 +173,18 @@ export interface ChartConfiguration {
/**
* Change the width of bar chart. If ratio is specified, change the width of bar chart by ratio.
*/
width?: number | {
/**
* Set the width of each bar by ratio
*/
ratio: number,
/**
* Set max width of each bar
*/
max?: number
};
width?:
| number
| {
/**
* Set the width of each bar by ratio
*/
ratio: number;
/**
* Set max width of each bar
*/
max?: number;
};
/**
* Set if min or max value will be 0 on bar chart.
*/
@@ -205,7 +208,7 @@ export interface ChartConfiguration {
/**
* Set threshold to show/hide labels.
*/
threshold?: number
threshold?: number;
};
/**
* Enable or disable expanding pie pieces.
@@ -226,7 +229,7 @@ export interface ChartConfiguration {
/**
* Set threshold to show/hide labels.
*/
threshold?: number
threshold?: number;
};
/**
* Enable or disable expanding pie pieces.
@@ -280,7 +283,17 @@ export interface ChartConfiguration {
/**
* Set custom spline interpolation
*/
type?: 'linear' | 'linear-closed' | 'basis' | 'basis-open' | 'basis-closed' | 'bundle' | 'cardinal' | 'cardinal-open' | 'cardinal-closed' | 'monotone';
type?:
| "linear"
| "linear-closed"
| "basis"
| "basis-open"
| "basis-closed"
| "bundle"
| "cardinal"
| "cardinal-open"
| "cardinal-closed"
| "monotone";
};
};
}
@@ -309,7 +322,7 @@ export interface Data {
/**
* Choose which JSON object keys correspond to desired data.
*/
keys?: { x?: string; value: string[]; };
keys?: { x?: string; value: string[] };
/**
* Specify the key of x values in the data.
* We can show the data with non-index x values by this option. This option is required when the type of x axis is timeseries. If this option is set on category axis, the values of the data
@@ -365,9 +378,7 @@ export interface Data {
* - j is the sub index of the data point where the label is shown.
* Formatter function can be defined for each data by specifying as an object and D3 formatter function can be set (e.g. d3.format('$'))
*/
labels?: boolean |
{ format: FormatFunction } |
{ format: { [key: string]: FormatFunction } };
labels?: boolean | { format: FormatFunction } | { format: { [key: string]: FormatFunction } };
/**
* Define the order of the data.
* This option changes the order of stacking the data and pieces of pie/donut. If null specified, it will be the order the data loaded. If function specified, it will be used to sort the data
@@ -387,11 +398,11 @@ export interface Data {
* This option should a function and the specified function receives color (e.g. '#ff0000') and d that has data parameters like id, value, index, etc. And it must return a string that
* represents color (e.g. '#00ff00').
*/
color?(color: string, d: any): string | d3.Rgb;
color?(color: string, d: any): string | d3.RGBColor;
/**
* Set color for each data.
*/
colors?: { [key: string]: string | d3.Rgb | ((d: any) => string | d3.Rgb) };
colors?: { [key: string]: string | d3.RGBColor | ((d: any) => string | d3.RGBColor) };
/**
* Hide each data when the chart appears.
* If true specified, all of data will be hidden. If multiple ids specified as an array, those will be hidden.
@@ -690,6 +701,10 @@ export interface LegendOptions {
y?: number;
step?: number;
};
/**
* Padding between legend elements.
*/
padding?: number;
item?: {
/**
@@ -704,6 +719,19 @@ export interface LegendOptions {
* Set mouseout event handler to the legend item.
*/
onmouseout?(id: any): void;
/**
* Tile settings for legend color display.
*/
tile?: {
/**
* Tile width.
*/
width?: number;
/**
* Tile height
*/
height?: number;
}
};
}
@@ -813,7 +841,7 @@ export interface PointOptions {
/**
* The radius size of each point on focus.
*/
r?: number
r?: number;
};
};
@@ -877,7 +905,7 @@ export interface ChartAPI {
load(args: {
url?: string;
json?: {};
keys?: { x?: string; value: string[]; }
keys?: { x?: string; value: string[] };
rows?: PrimitiveArray[];
columns?: PrimitiveArray[];
xs?: { [key: string]: string };
@@ -885,7 +913,7 @@ export interface ChartAPI {
classes?: { [key: string]: string };
categories?: string[];
axes?: { [key: string]: string };
colors?: { [key: string]: string | d3.Rgb };
colors?: { [key: string]: string | d3.RGBColor };
type?: string;
types?: { [key: string]: string };
unload?: boolean | ArrayOrString;
@@ -911,7 +939,7 @@ export interface ChartAPI {
*/
flow(args: {
json?: {};
keys?: { x?: string; value: string[]; }
keys?: { x?: string; value: string[] };
rows?: PrimitiveArray[];
columns?: PrimitiveArray[];
to?: any;
@@ -997,7 +1025,7 @@ export interface ChartAPI {
* Get and set colors of the data loaded in the chart.
* @param colors If this argument is given, the colors of data will be updated. If not given, the current colors will be returned. The format of this argument is the same as data.colors.
*/
colors(colors?: { [key: string]: string | d3.Rgb }): { [key: string]: string };
colors(colors?: { [key: string]: string | d3.RGBColor }): { [key: string]: string };
/**
* Get and set axes of the data loaded in the chart.
* @param axes If this argument is given, the axes of data will be updated. If not given, the current axes will be returned. The format of this argument is the same as data.axes.
@@ -1040,22 +1068,25 @@ export interface ChartAPI {
* Get and set axis labels.
* @param labels If labels is given, specified axis' label will be updated.
*/
labels(labels?: { [key: string]: string }): { [key: string]: string }
labels(labels?: { [key: string]: string }): { [key: string]: string };
/**
* Get and set axis min value.
* @param min If min is given, specified axis' min value will be updated. If no argument is given, the current min values for each axis will be returned.
*/
min(min?: number | { [key: string]: number }): number | { [key: string]: number }
min(min?: number | { [key: string]: number }): number | { [key: string]: number };
/**
* Get and set axis max value.
* @param max If max is given, specified axis' max value will be updated. If no argument is given, the current max values for each axis will be returned.
*/
max(max?: number | { [key: string]: number }): number | { [key: string]: number }
max(max?: number | { [key: string]: number }): number | { [key: string]: number };
/**
* Get and set axis min and max value.
* @param range If range is given, specified axis' min and max value will be updated. If no argument is given, the current min and max values for each axis will be returned.
*/
range(range?: { min?: number | { [key: string]: number }; max?: number | { [key: string]: number } }): { min: number | { [key: string]: number }; max: number | { [key: string]: number } }
range(range?: {
min?: number | { [key: string]: number };
max?: number | { [key: string]: number };
}): { min: number | { [key: string]: number }; max: number | { [key: string]: number } };
};
legend: {
+6 -15
View File
@@ -1,29 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"lib": ["es6", "dom"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"typeRoots": ["../"],
"types": [],
"paths": {
"d3": [
"d3/v3"
]
"d3-scale": ["d3-scale/v1"],
"d3": ["d3/v4"]
},
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"c3-tests.ts"
]
}
"files": ["index.d.ts", "c3-tests.ts"]
}
+128 -25
View File
@@ -1,6 +1,7 @@
// Type definitions for cassandra-driver v3.2.2
// Type definitions for cassandra-driver v3.4.1
// Project: https://github.com/datastax/nodejs-driver
// Definitions by: Marc Fisher <https://github.com/Svjard>
// Christian D <https://github.com/pc-jedi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -115,7 +116,11 @@ export namespace policies {
interface RetryPolicyStatic {
new (): RetryPolicy;
retryDecision: any;
retryDecision: {
rethrow: number,
retry: number,
ignore: number
};
}
interface RetryPolicy {
@@ -126,15 +131,55 @@ export namespace policies {
retryResult(): { decision: retryDecision, consistency: types.consistencies, useCurrentHost: boolean };
}
}
namespace speculativeExecution {
let NoSpeculativeExecutionPolicy: NoSpeculativeExecutionPolicyStatic
interface SpeculativeExecutionPolicy {
init(client: Client): void;
newPlan(keyspace: string, queryInfo: string | Array<string>): {
nextExecution: Function
}
}
interface NoSpeculativeExecutionPolicyStatic {
new (): NoSpeculativeExecutionPolicy
}
interface NoSpeculativeExecutionPolicy extends SpeculativeExecutionPolicy { }
interface ConstantSpeculativeExecutionPolicyStatic {
new (delay: number, maxSpeculativeExecutions: number): ConstantSpeculativeExecutionPolicy
}
interface ConstantSpeculativeExecutionPolicy extends SpeculativeExecutionPolicy { }
}
namespace timestampGeneration {
let MonotonicTimestampGenerator: MonotonicTimestampGeneratorStatic
interface TimestampGenerator {
next(client: Client): null | number | _Long
}
interface MonotonicTimestampGeneratorStatic {
new (warningThreshold?: number, minLogInterval?: number): MonotonicTimestampGeneratorStatic
}
interface MonotonicTimestampGenerator extends TimestampGenerator {
getDate(): number
}
}
}
export namespace types {
let BigDecimal: BigDecimalStatic;
let Duration: DurationStatic;
let Long: _Long;
let InetAddress: InetAddressStatic;
let Integer: IntegerStatic;
let LocalDate: LocalDateStatic;
let LocalTime: LocalTimeStatic;
let Long: _Long;
let ResultSet: ResultSetStatic;
// let ResultStream: ResultStreamStatic;
let Row: RowStatic;
@@ -221,6 +266,19 @@ export namespace types {
toJSON(): string;
}
interface DurationStatic {
new (month: number, days: number, nanoseconds: number | _Long): Duration;
fromBuffer(buffer: Buffer): Duration;
fromString(input: string): Duration;
}
interface Duration {
equals(other: Duration): boolean;
toBuffer(): Buffer;
toString(): string;
}
interface InetAddressStatic {
new (buffer: Buffer): InetAddress;
@@ -336,13 +394,14 @@ export namespace types {
}
interface ResultSetStatic {
new (response: any, host: string, triedHost: { [key: string]: any }, consistency: consistencies): ResultSet;
new (response: any, host: string, triedHost: { [key: string]: any }, speculativeExecutions: number, consistency: consistencies): ResultSet;
}
interface ResultSet {
info: {
queriedHost: Host,
triedHosts: { [key: string]: string; },
speculativeExecutions: number,
achievedConsistency: consistencies,
traceId: Uuid,
warnings: Array<string>,
@@ -352,11 +411,13 @@ export namespace types {
rowLength: number;
columns: Array<{ [key: string]: string; }>;
pageState: string;
nextPage: any; // function
nextPage: Function;
first(): Row;
getPageState(): string;
getColumns(): Array<{ [key: string]: string; }>;
wasApplied(): boolean;
[Symbol.iterator](): Iterator<Row>;
}
interface ResultStreamStatic {
@@ -442,40 +503,50 @@ export let Encoder: EncoderStatic;
export interface ClientOptions {
contactPoints: Array<string>,
keyspace?: string,
refreshSchemaDelay?: number,
isMetadataSyncEnabled?: boolean,
prepareOnAllHosts?: boolean,
rePrepareOnUp?: boolean,
maxPrepared?: number,
policies?: {
addressResolution?: policies.addressResolution.AddressTranslator,
loadBalancing?: policies.loadBalancing.LoadBalancingPolicy,
retry?: policies.retry.RetryPolicy,
reconnection?: policies.reconnection.ReconnectionPolicy,
retry?: policies.retry.RetryPolicy
addressResolution?: policies.addressResolution.AddressTranslator,
speculativeExecution?: policies.speculativeExecution.SpeculativeExecutionPolicy,
timestampGeneration?: policies.timestampGeneration.TimestampGenerator,
},
queryOptions?: QueryOptions,
pooling?: {
heartBeatInterval: number,
coreConnectionsPerHost: { [key: number]: number; },
warmup: boolean;
heartBeatInterval?: number,
coreConnectionsPerHost?: { [key: number]: number; },
maxRequestsPerConnection?: number,
warmup?: boolean;
},
protocolOptions?: {
port: number,
maxSchemaAgreementWaitSeconds: number,
maxVersion: number
port?: number,
maxSchemaAgreementWaitSeconds?: number,
maxVersion?: number
},
socketOptions?: {
connectTimeout: number,
defunctReadTimeoutThreshold: number,
keepAlive: boolean,
keepAliveDelay: number,
readTimeout: number,
tcpNoDelay: boolean,
coalescingThreshold: number
connectTimeout?: number,
defunctReadTimeoutThreshold?: number,
keepAlive?: boolean,
keepAliveDelay?: number,
readTimeout?: number,
tcpNoDelay?: boolean,
coalescingThreshold?: number
},
authProvider?: auth.AuthProvider,
sslOptions?: tls.ConnectionOptions,
encoding?: {
map: Function,
set: Function,
copyBuffer: boolean,
useUndefinedAsUnset: boolean
}
map?: Function,
set?: Function,
copyBuffer?: boolean,
useUndefinedAsUnset?: boolean
},
profiles?: Array<ExecutionProfile>,
promiseFactory?: Function,
}
export interface QueryOptions {
@@ -483,8 +554,11 @@ export interface QueryOptions {
captureStackTrace?: boolean;
consistency?: number;
customPayload?: any;
executionProfile?: string | ExecutionProfile;
fetchSize?: number;
hints?: Array<string> | Array<Array<string>>;
isIdempotent?: boolean;
keyspace?: string;
logged?: boolean;
pageState?: Buffer | string;
prepare?: boolean;
@@ -520,6 +594,7 @@ export interface Client extends events.EventEmitter {
execute(query: string, callback: ResultCallback): void;
execute(query: string, params?: any, options?: QueryOptions): Promise<types.ResultSet>;
getReplicas(keyspace: string, token: Buffer): Array<any>; // TODO: Should this be a more explicit return?
getState(): metadata.ClientState;
shutdown(callback?: Callback): void;
shutdown(): Promise<void>;
stream(query: string, params?: any, options?: QueryOptions, callback?: Callback): NodeJS.ReadableStream;
@@ -548,6 +623,7 @@ export interface HostMapStatic {
export interface HostMap extends events.EventEmitter {
length: number;
clear(): Array<Host>;
forEach(callback: Callback): void;
get(key: string): Host;
keys(): Array<string>;
@@ -566,6 +642,22 @@ export interface Encoder {
encode(value: any, typeInfo?: string | number | { code: number, info?: any }): Buffer;
}
interface ExecutionProfileOptions {
consistency: number,
loadBalancing: policies.loadBalancing.LoadBalancingPolicy,
name: string,
readTimeout: number,
retry: policies.retry.RetryPolicy,
serialConsistency: number
}
export interface ExecutionProfileStatic {
new (name: string, options: ExecutionProfileOptions): ExecutionProfile
}
export interface ExecutionProfile extends ExecutionProfileOptions {
}
export namespace auth {
let Authenticator: AuthenticatorStatic;
let PlainTextAuthProvider: PlainTextAuthProviderStatic;
@@ -649,6 +741,17 @@ export namespace metadata {
stateFunction: string;
stateType: string;
}
interface ClientStateStatic {
new (): ClientState;
}
interface ClientState {
getConnectedHosts(): Array<Host>;
getInFlightQueries(host: Host): number;
getOpenConnections(host: Host): number;
toString(): string;
}
interface DataTypeInfo {
code: number,
-42
View File
@@ -1,42 +0,0 @@
import * as React from "react";
import { Config, render, markdown, Catalog, ReactSpecimen, Page } from "catalog";
const config: Config = {
title: 'Test',
pages: [
{
path: '/',
title: 'Introduction',
content: '/patd/to/file.md',
},
{
path: '/materials',
title: 'Materials',
pages: [
{
path: '/materials/typeface',
title: 'Typeface',
component: <Page />,
},
],
},
],
useBrowserHistory: true,
basePath: '/doc',
responsiveSizes: [
{ name: 'large', width: 978, height: 1100 },
{ name: 'medium', width: 640, height: 900 },
{ name: 'small', width: 471, height: 700 },
],
};
render(config, document.body);
<Catalog {...config} />;
markdown`
# Test
${<ReactSpecimen sourceText='.'>
<div />
</ReactSpecimen>}
`;
-109
View File
@@ -1,109 +0,0 @@
// Type definitions for catalog 3.2
// Project: https://github.com/interactivethings/catalog/
// Definitions by: Peter Gassner <https://github.com/grossbart>, Tomas Carnecky <https://github.com/wereHamster>
// Definitions: https://github.com/interactivethings/catalog/
// TypeScript Version: 2.6
import * as React from "react";
// Configuration
// XXX: Can not name this 'Page' because there's already a 'Page'
// component here.
export interface ConfigPage {
path: string;
title: string;
content?: any;
component?: any;
pages?: ConfigPage[];
}
export interface ConfigResponsiveSize {
name: string;
width: number;
height: number;
}
export interface Config {
title: string;
pages: ConfigPage[];
useBrowserHistory?: boolean;
basePath?: string;
responsiveSizes?: ConfigResponsiveSize[];
}
export function render(config: Config, element: HTMLElement): void;
export function configure(config: any): any;
export function configureRoutes(config: any): any;
export function configureJSXRoutes(config: any): any;
export function pageLoader(f: () => Promise<any>): any;
export function markdown(...x: any[]): JSX.Element;
// Components
export interface DefaultCatalogProps extends React.Props<{}> {
span?: number;
theme?: any;
}
export class Card extends React.Component<DefaultCatalogProps> {}
export class Page extends React.Component<DefaultCatalogProps> {}
export interface SpanProps extends DefaultCatalogProps {
style?: any;
}
export class Span extends React.Component<SpanProps> {}
// Specimens
export class AudioSpecimen extends React.Component<DefaultCatalogProps> {}
export interface CodeSpecimenProps extends DefaultCatalogProps {
rawBody: string;
collapsed: boolean;
lang: string;
raw: boolean;
}
export class CodeSpecimen extends React.Component<CodeSpecimenProps> {}
export interface ColorSpecimenProps extends DefaultCatalogProps {
value: string;
name: string;
}
export class ColorSpecimen extends React.Component<ColorSpecimenProps> {}
export interface ColorPaletteSpecimenProps extends DefaultCatalogProps {
colors: Array<{name?: string, value: string}>;
horizontal?: boolean;
}
export class ColorPaletteSpecimen extends React.Component<ColorPaletteSpecimenProps> {}
export class HtmlSpecimen extends React.Component<DefaultCatalogProps> {}
export class HintSpecimen extends React.Component<DefaultCatalogProps> {}
export class ImageSpecimen extends React.Component<DefaultCatalogProps> {}
export interface TypeSpecimenProps extends DefaultCatalogProps {
color?: string;
font: string;
headings: string[] | number[];
style?: string;
weight: string;
}
export class TypeSpecimen extends React.Component<TypeSpecimenProps> {}
export class DownloadSpecimen extends React.Component<DefaultCatalogProps> {}
export interface ReactSpecimenProps extends DefaultCatalogProps {
noSource?: boolean;
plain?: boolean;
light?: boolean;
dark?: boolean;
frame?: boolean;
state?: any;
responsive?: boolean | string | string[];
sourceText?: string;
}
export class ReactSpecimen extends React.Component<ReactSpecimenProps> {}
export class VideoSpecimen extends React.Component<DefaultCatalogProps> {}
export class Catalog extends React.Component<Config> {}
-3
View File
@@ -1,3 +0,0 @@
{
"extends": "dtslint/dt.json"
}
+1
View File
@@ -49,4 +49,5 @@ declare global {
}
declare function chaiString(chai: any, utils: any): void;
declare namespace chaiString { }
export = chaiString;
+2 -3
View File
@@ -1,8 +1,7 @@
import chai = require('chai');
import chaiThings = require('chai-things');
import * as chai from 'chai';
import * as chaiThings from 'chai-things';
chai.use(chaiThings);
function test_somethingSyntax() {
+1
View File
@@ -60,5 +60,6 @@ interface Array<T> {
declare module "chai-things" {
function chaiThings(chai: any, utils: any): void;
namespace chaiThings { }
export = chaiThings;
}
+7
View File
@@ -21,6 +21,12 @@ const chart: Chart = new Chart(new CanvasRenderingContext2D(), {
hover: {
intersect: true
},
onHover(ev: MouseEvent, points: any[]) {
return;
},
title: {
text: ["foo", "bar"]
},
tooltips: {
filter: data => Number(data.yLabel) > 0,
intersect: true,
@@ -52,6 +58,7 @@ const chart: Chart = new Chart(new CanvasRenderingContext2D(), {
padding: 40
}
},
devicePixelRatio: 2,
}
});
chart.update();
+22 -19
View File
@@ -9,6 +9,7 @@
// Dan Manastireanu <https://github.com/danmana>
// Guillaume Rodriguez <https://github.com/guillaume-ro-fr>
// Sergey Rubanov <https://github.com/chicoxyzzy>
// Simon Archer <https://github.com/archy-bold>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -126,6 +127,10 @@ declare namespace Chart {
pointStyle?: PointStyle;
}
interface ChartLegendLabelItem extends ChartLegendItem {
datasetIndex: number;
}
interface ChartTooltipItem {
xLabel?: string;
yLabel?: string;
@@ -184,6 +189,7 @@ declare namespace Chart {
aspectRatio?: number;
maintainAspectRatio?: boolean;
events?: string[];
onHover?(this: Chart, event: MouseEvent, activeElements: Array<{}>): any;
onClick?(event?: MouseEvent, activeElements?: Array<{}>): any;
title?: ChartTitleOptions;
legend?: ChartLegendOptions;
@@ -198,6 +204,7 @@ declare namespace Chart {
cutoutPercentage?: number;
circumference?: number;
rotation?: number;
devicePixelRatio?: number;
// Plugins can require any options
plugins?: { [plugin: string]: any };
}
@@ -218,15 +225,15 @@ declare namespace Chart {
fontColor?: ChartColor;
fontStyle?: string;
padding?: number;
text?: string;
text?: string | string[];
}
interface ChartLegendOptions {
display?: boolean;
position?: PositionType;
fullWidth?: boolean;
onClick?(event: MouseEvent, legendItem: ChartLegendItem): void;
onHover?(event: MouseEvent, legendItem: ChartLegendItem): void;
onClick?(event: MouseEvent, legendItem: ChartLegendLabelItem): void;
onHover?(event: MouseEvent, legendItem: ChartLegendLabelItem): void;
labels?: ChartLegendLabelOptions;
reverse?: boolean;
}
@@ -239,7 +246,7 @@ declare namespace Chart {
fontFamily?: string;
padding?: number;
generateLabels?(chart: any): any;
filter?(item: ChartLegendItem, data: ChartData): any;
filter?(legendItem: ChartLegendLabelItem, data: ChartData): any;
usePointStyle?: boolean;
}
@@ -291,7 +298,7 @@ declare namespace Chart {
mode?: string;
animationDuration?: number;
intersect?: boolean;
onHover?(active: any): void;
onHover?(this: Chart, event: MouseEvent, activeElements: Array<{}>): any;
}
interface ChartAnimationObject {
@@ -395,6 +402,10 @@ declare namespace Chart {
interface TickOptions {
autoSkip?: boolean;
autoSkipPadding?: number;
backdropColor?: ChartColor;
backdropPaddingX?: number;
backdropPaddingY?: number;
beginAtZero?: boolean;
callback?(value: any, index: any, values: any): string|number;
display?: boolean;
fontColor?: ChartColor;
@@ -402,14 +413,17 @@ declare namespace Chart {
fontSize?: number;
fontStyle?: string;
labelOffset?: number;
max?: any;
maxRotation?: number;
maxTicksLimit?: number;
min?: any;
minRotation?: number;
mirror?: boolean;
padding?: number;
reverse?: boolean;
min?: any;
max?: any;
showLabelBackdrop?: boolean;
}
interface AngleLineOptions {
display?: boolean;
color?: ChartColor;
@@ -424,26 +438,15 @@ declare namespace Chart {
fontStyle?: string;
}
interface TickOptions {
backdropColor?: ChartColor;
backdropPaddingX?: number;
backdropPaddingY?: number;
maxTicksLimit?: number;
showLabelBackdrop?: boolean;
}
interface LinearTickOptions extends TickOptions {
beginAtZero?: boolean;
min?: number;
max?: number;
maxTicksLimit?: number;
stepSize?: number;
suggestedMin?: number;
suggestedMax?: number;
}
// tslint:disable-next-line no-empty-interface
interface LogarithmicTickOptions extends TickOptions {
min?: number;
max?: number;
}
type ChartColor = string | CanvasGradient | CanvasPattern | string[];
+20
View File
@@ -1678,6 +1678,17 @@ declare namespace chrome.devtools.inspectedWindow {
* Parameter exceptionInfo: An object providing details if an exception occurred while evaluating the expression.
*/
export function eval<T>(expression: string, callback?: (result: T, exceptionInfo: EvaluationExceptionInfo) => void): void;
/**
* Evaluates a JavaScript expression in the context of the main frame of the inspected page. The expression must evaluate to a JSON-compliant object, otherwise an exception is thrown. The eval function can report either a DevTools-side error or a JavaScript exception that occurs during evaluation. In either case, the result parameter of the callback is undefined. In the case of a DevTools-side error, the isException parameter is non-null and has isError set to true and code set to an error code. In the case of a JavaScript error, isException is set to true and value is set to the string value of thrown object.
* @param expression An expression to evaluate.
* @param options The options parameter can contain one or more options.
* @param callback A function called when evaluation completes.
* If you specify the callback parameter, it should be a function that looks like this:
* function(object result, object exceptionInfo) {...};
* Parameter result: The result of evaluation.
* Parameter exceptionInfo: An object providing details if an exception occurred while evaluating the expression.
*/
export function eval<T>(expression: string, options: EvalOptions, callback?: (result: T, exceptionInfo: EvaluationExceptionInfo) => void): void;
/**
* Retrieves the list of resources from the inspected page.
* @param callback A function that receives the list of resources when the request completes.
@@ -1690,6 +1701,15 @@ declare namespace chrome.devtools.inspectedWindow {
export var onResourceAdded: ResourceAddedEvent;
/** Fired when a new revision of the resource is committed (e.g. user saves an edited version of the resource in the Developer Tools). */
export var onResourceContentCommitted: ResourceContentCommittedEvent;
export interface EvalOptions {
/** If specified, the expression is evaluated on the iframe whose URL matches the one specified. By default, the expression is evaluated in the top frame of the inspected page. */
frameURL?: string;
/** Evaluate the expression in the context of the content script of the calling extension, provided that the content script is already injected into the inspected page. If not, the expression is not evaluated and the callback is invoked with the exception parameter set to an object that has the isError field set to true and the code field set to E_NOTFOUND. */
useContentScriptContext?: boolean;
/** Evaluate the expression in the context of a content script of an extension that matches the specified origin. If given, contextSecurityOrigin overrides the 'true' setting on userContentScriptContext. */
contextSecurityOrigin?: string;
}
}
////////////////////
@@ -0,0 +1,20 @@
import CircuitBreaker = require('circuit-breaker-js');
const breaker = new CircuitBreaker();
breaker.isOpen();
const options: CircuitBreaker.Options = {};
let status: number = CircuitBreaker.CLOSED;
status = CircuitBreaker.OPEN;
breaker.forceOpen();
breaker.forceClose();
breaker.run((success, failure) => {
if (Math.random() > 0.5) {
success();
} else {
failure();
}
});
+44
View File
@@ -0,0 +1,44 @@
// Type definitions for circuit-breaker-js 0.0
// Project: http://yammer.github.io/circuit-breaker-js/
// Definitions by: Timur Amirov <https://github.com/DeTeam>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = CircuitBreaker;
declare namespace CircuitBreaker {
interface Options {
windowDuration?: number;
numBuckets?: number;
timeoutDuration?: number;
errorThreshold?: number;
volumeThreshold?: number;
onCircuitOpen?: (m: Metrics) => void;
onCircuitClose?: (m: Metrics) => void;
}
interface Metrics {
totalCount: number;
errorCount: number;
errorPercentage: number;
}
}
declare class CircuitBreaker {
static OPEN: 0;
static HALF_OPEN: 1;
static CLOSED: 2;
constructor(options?: CircuitBreaker.Options);
run(
command: (
success: () => void,
failure: () => void,
) => void,
fallback?: () => void
): void;
forceClose(): void;
forceOpen(): void;
unforce(): void;
isOpen(): boolean;
}
+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",
"circuit-breaker-js-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+11 -1
View File
@@ -323,7 +323,11 @@ function test_adding_dialog_by_definition() {
title: 'Abbreviation Properties',
minWidth: 400,
minHeight: 200,
onLoad: () => {},
onOk: () => {},
onCancel: () => {},
onShow: () => {},
onHide: () => {},
contents: [
{
id: 'tab-basic',
@@ -506,3 +510,9 @@ function test_editor_instance_event() {
}
});
}
function test_dtd() {
var brConsideredEmptyTag = CKEDITOR.dtd.$empty["br"];
var spanCanContainText = CKEDITOR.dtd["span"]["#"];
var divCanContainSpan = CKEDITOR.dtd["div"]["span"];
}
+51 -32
View File
@@ -24,8 +24,8 @@ declare namespace CKEDITOR {
var DIALOG_RESIZE_HEIGHT: number;
var DIALOG_RESIZE_NONE: number;
var DIALOG_RESIZE_WIDTH: number;
var DIALOG_STATE_IDLE: number;
var DIALOG_STATE_BUSY: number;
var DIALOG_STATE_IDLE: number;
var DIALOG_STATE_BUSY: number;
var ELEMENT_MODE_APPENDTO: number;
var ELEMENT_MODE_INLINE: number;
var ELEMENT_MODE_NONE: number;
@@ -44,10 +44,10 @@ declare namespace CKEDITOR {
var NODE_DOCUMENT_FRAGMENT: number;
var NODE_ELEMENT: number;
var NODE_TEXT: number;
var POSITION_BEFORE_START: number;
var POSITION_BEFORE_END: number;
var POSITION_AFTER_START: number;
var POSITION_AFTER_END: number;
var POSITION_BEFORE_START: number;
var POSITION_BEFORE_END: number;
var POSITION_AFTER_START: number;
var POSITION_AFTER_END: number;
var SELECTION_ELEMENT: number;
var SELECTION_NONE: number;
var SELECTION_TEXT: number;
@@ -55,9 +55,9 @@ declare namespace CKEDITOR {
var SHRINK_ELEMENT: number;
var SHRINK_TEXT: number;
var START: number;
var STYLE_BLOCK: string;
var STYLE_INLINE: string;
var STYLE_OBJECT: string;
var STYLE_BLOCK: string;
var STYLE_INLINE: string;
var STYLE_OBJECT: string;
var TRISTATE_DISABLED: number;
var TRISTATE_OFF: number;
var TRISTATE_ON: number;
@@ -288,7 +288,7 @@ declare namespace CKEDITOR {
class elementPath {
constructor(startNode: element, root: element);
constructor(startNode: element);
constructor(startNode: element);
block: element;
blockLimit: element;
root: element;
@@ -342,7 +342,7 @@ declare namespace CKEDITOR {
setStartAt(node: node, position: number): void;
setEndAt(node: node, position: number): void;
fixBlock(isStart: boolean, blockTag: Object): Object;
select(): selection;
select(): selection;
splitBlock(blockTag: Object): Object;
splitElement(toSplit: element): element;
removeEmptyBlocksAtEnd(atEnd: boolean): void;
@@ -836,7 +836,7 @@ declare namespace CKEDITOR {
templates_files?: Object;
templates_replaceContent?: boolean;
title?: string | boolean;
toolbar?: string | (string | string[] | { name: string, items?: string[], groups?: string[] })[] | null;
toolbar?: string | (string | string[] | { name: string, items?: string[], groups?: string[] })[] | null;
toolbarCanCollapse?: boolean;
toolbarGroupCycling?: boolean;
toolbarGroups?: (toolbarGroups | string)[];
@@ -869,19 +869,19 @@ declare namespace CKEDITOR {
}
module skin {
var icons: { [name: string]: { path: string } };
function addIcon(name: string, path: string, offset?: number, bgsize?: string): void;
}
var icons: { [name: string]: { path: string } };
function addIcon(name: string, path: string, offset?: number, bgsize?: string): void;
}
class style {
constructor(something: { element: string, attributes: { [att: string]: string } });
applyToRange(range: Range, editor: editor): void;
}
constructor(something: { element: string, attributes: { [att: string]: string } });
applyToRange(range: Range, editor: editor): void;
}
interface editable extends dom.element {
hasFocus: boolean;
attachListener(obj: event | editable, eventName: string, listenerFunction: (ei: eventInfo) => void,
scopeobj?: {}, listenerData?: any, priority?: number): listenerRegistration;
hasFocus: boolean;
attachListener(obj: event | editable, eventName: string, listenerFunction: (ei: eventInfo) => void,
scopeobj?: {}, listenerData?: any, priority?: number): listenerRegistration;
}
@@ -978,7 +978,7 @@ declare namespace CKEDITOR {
destroy(widget: CKEDITOR.plugins.widget, offline?: boolean): void;
destroyAll(offline?: boolean): void;
finalizeCreation(container: any): void;
focused: widget;
focused: widget;
fire(eventName: string, data: Object, editor: editor): any; // should be boolean | Object
getByElement(element: any, checkWrapperOnly: boolean): CKEDITOR.plugins.widget;
hasListeners(eventName: string): boolean;
@@ -1089,7 +1089,7 @@ declare namespace CKEDITOR {
interface IMenuItemDefinition {
label:string,
command:string,
icon: string
icon: string
group:string,
order:number
}
@@ -1142,7 +1142,7 @@ declare namespace CKEDITOR {
createFakeParserElement(realElement: Object, className: Object, realElementType: Object, isResizable: Object): void;
createRange(): dom.range;
destroy(noUpdate?: boolean): void;
editable(): editable | null;
editable(): editable | null;
editable(elementOrEditable: dom.element): void;
editable(elementOrEditable: editable): void;
elementPath(startNode?: dom.node): dom.elementPath;
@@ -1300,14 +1300,14 @@ declare namespace CKEDITOR {
stop(): void;
}
module filter {
interface allowedContentRules {
module filter {
interface allowedContentRules {
}
}
}
}
class filter {
allow(newRules: CKEDITOR.filter.allowedContentRules, featureName?: string, overrideCustom?: boolean): boolean;
allow(newRules: CKEDITOR.filter.allowedContentRules, featureName?: string, overrideCustom?: boolean): boolean;
}
@@ -1370,10 +1370,28 @@ declare namespace CKEDITOR {
}
class dtd {
interface dtdDefinition {
[outerTagName: string]: {[innerTagName: string]: 1};
$block: {[tagName: string]: 1};
$blockLimit: {[tagName: string]: 1};
$cdata: {[tagName: string]: 1};
$editable: {[tagName: string]: 1};
$empty: {[tagName: string]: 1};
$inline: {[tagName: string]: 1};
$intermediate: {[tagName: string]: 1};
$list: {[tagName: string]: 1};
$listItem: {[tagName: string]: 1};
$nonBodyContent: {[tagName: string]: 1};
$nonEditable: {[tagName: string]: 1};
$object: {[tagName: string]: 1};
$removeEmpty: {[tagName: string]: 1};
$tabIndex: {[tagName: string]: 1};
$tableContent: {[tagName: string]: 1};
$transparent: {[tagName: string]: 1};
}
var dtd: dtdDefinition;
class ui extends event {
constructor(editor: editor);
@@ -1717,6 +1735,7 @@ declare namespace CKEDITOR {
onLoad?: Function;
onOk?: Function;
onShow?: Function;
onHide?: Function;
resizable?: number;
title?: string;
width?: number;
@@ -1819,7 +1838,7 @@ declare namespace CKEDITOR {
children: any[];
type: number;
add(node: node): number;
add(node: node, index: number): void;
add(node: node, index: number): void;
clone(): element;
filter(filter: filter): boolean;
filterChildren(filter: filter): void;
@@ -0,0 +1,193 @@
// Testing type definitions for clearbladejs-client 1.0
// Project: https://github.com/ClearBlade/JavaScript-API
// Definitions by: Jim Bouquet <https://github.com/ClearBlade>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
let genericCallback = (error: boolean, response: Resp) => {};
///////////////////////////////////////
// ClearBlade object API invocations
///////////////////////////////////////
ClearBlade.init({
systemKey: "abcdef",
systemSecret: "abcdefg",
callback: genericCallback
});
ClearBlade.setUser("test@test.com", "password");
ClearBlade.registerUser("test@test.com", "password", genericCallback);
ClearBlade.isCurrentUserAuthenticated(genericCallback);
ClearBlade.logoutUser(genericCallback);
ClearBlade.loginAnon(genericCallback);
ClearBlade.loginUser("test@test.com", "password", genericCallback);
ClearBlade.loginUserMqtt("test@test.com", "password", genericCallback);
ClearBlade.sendPush(["user1", "user2"], {data: "Test"}, "appId: string", genericCallback);
ClearBlade.getAllCollections(genericCallback);
let coll1 = ClearBlade.Collection("collectionID");
let coll2 = ClearBlade.Collection({ collectionName: "collectionName" });
let coll3 = ClearBlade.Collection({ collectionID: "collectionID" });
let query1 = ClearBlade.Query("collectionID");
let query2 = ClearBlade.Query({ offset: 5, limit: 5, collectionID: "collectionID" });
let query3 = ClearBlade.Query({ collectionName: "collectionName" });
let item1 = ClearBlade.Item({}, "collectionID");
let item2 = ClearBlade.Item({}, { collectionID: "collectionID" });
let code = ClearBlade.Code();
let user = ClearBlade.User();
let messaging = ClearBlade.Messaging({}, genericCallback);
let stats = ClearBlade.MessagingStats();
let edge = ClearBlade.Edge();
let metrics = ClearBlade.Metrics();
let device = ClearBlade.Device();
let analytics = ClearBlade.Analytics();
let portal = ClearBlade.Portal("MyPortal");
let triggers = ClearBlade.Triggers();
ClearBlade.getEdges(query1.query, genericCallback);
///////////////////////////////////////
// Collection API invocations
///////////////////////////////////////
coll1.fetch(query1.query, genericCallback);
coll1.create(ClearBlade.Item({}, ""), genericCallback);
coll1.update(query1.query, {}, genericCallback);
coll1.remove(query1.query, genericCallback);
coll1.columns(genericCallback);
coll1.count(query1.query, genericCallback);
///////////////////////////////////////
// Query API invocations
///////////////////////////////////////
query1.addSortToQuery(
query1,
QuerySortDirections.QUERY_SORT_ASCENDING,
"column1"
);
query1.addFilterToQuery(
query1,
QueryConditions.QUERY_GREATERTHAN,
"key",
"value"
);
query1.ascending("string");
query1.descending("string");
query1.equalTo("string", "string");
query1.greaterThan("string", 2);
query1.greaterThanEqualTo("string", false);
query1.lessThan("string", "string");
query1.lessThanEqualTo("string", "string");
query1.notEqualTo("string", "string");
query1.matches("string", new RegExp(/.*/));
query1.or(query2);
query1.setPage(1, 1);
query1.fetch(genericCallback);
query1.update({}, genericCallback);
query1.columns([]);
query1.remove(genericCallback);
///////////////////////////////////////
// Item API invocations
///////////////////////////////////////
item1.save(genericCallback);
item1.refresh(genericCallback);
item1.destroy(genericCallback);
///////////////////////////////////////
// Code API invocations
///////////////////////////////////////
code.create("codeName", "body: string", genericCallback);
code.update("codeName", "body: string", genericCallback);
code.delete("codeName", genericCallback);
code.execute("codeName", {}, genericCallback);
code.getCompletedServices(genericCallback);
code.getFailedServices(genericCallback);
code.getAllServices(genericCallback);
///////////////////////////////////////
// User API invocations
///////////////////////////////////////
user.getUser(genericCallback);
user.setUser({}, genericCallback);
user.allUsers(query1.query, genericCallback);
user.setPassword("old_password", "new_password", genericCallback);
user.count(query1.query, genericCallback);
///////////////////////////////////////
// Messaging API invocations
///////////////////////////////////////
messaging.getMessageHistoryWithTimeFrame("topic", 5, 10, 15, 20, genericCallback);
messaging.getMessageHistory("topic", 5, 15, genericCallback);
messaging.getAndDeleteMessageHistory("topic", 5, 10, 1, 20, genericCallback);
messaging.currentTopics(genericCallback);
messaging.publish("topic", {});
messaging.publishREST("topic", { payload: Object }, genericCallback);
let mcb = (message: string) => {};
messaging.subscribe("topic", {}, mcb);
messaging.unsubscribe("topic", {});
messaging.disconnect();
///////////////////////////////////////
// MessagingStats API invocations
///////////////////////////////////////
stats.getAveragePayloadSize("topic: string", 5, 5, genericCallback);
stats.getOpenConnections(genericCallback);
stats.getCurrentSubscribers("topic: string", genericCallback);
///////////////////////////////////////
// Edge API invocations
///////////////////////////////////////
edge.updateEdgeByName("edgename", {changedColumn: "New value"}, genericCallback);
edge.deleteEdgeByName("edgename", genericCallback);
edge.create({newEdge: Object}, "edgename", genericCallback);
edge.columns(genericCallback);
edge.count(query1.query, genericCallback);
///////////////////////////////////////
// Metrics API invocations
///////////////////////////////////////
metrics.setQuery(query1.query);
metrics.getStatistics(genericCallback);
metrics.getStatisticsHistory(genericCallback);
metrics.getDBConnections(genericCallback);
metrics.getLogs(genericCallback);
///////////////////////////////////////
// Device API invocations
///////////////////////////////////////
device.getDeviceByName("devicename", genericCallback);
device.updateDeviceByName("devicename", { object: Object }, true, genericCallback);
device.deleteDeviceByName("devicename", genericCallback);
device.fetch(query1.query, genericCallback);
device.update(query1.query, { object: Object }, false, genericCallback);
device.delete(query1.query, genericCallback);
device.create({ newDevice: Object }, genericCallback);
device.columns(genericCallback);
device.count(query1.query, genericCallback);
///////////////////////////////////////
// Analytics API invocations
///////////////////////////////////////
analytics.getStorage({}, genericCallback);
analytics.getCount({}, genericCallback);
analytics.getEventList({}, genericCallback);
analytics.getEventTotals({}, genericCallback);
analytics.getUserEvents({}, genericCallback);
///////////////////////////////////////
// Portal API invocations
///////////////////////////////////////
portal.fetch(genericCallback);
portal.update({data: Object}, genericCallback);
///////////////////////////////////////
// Triggers API invocations
///////////////////////////////////////
triggers.fetchDefinitions(genericCallback);
triggers.create("triggername", {data: Object}, genericCallback);
triggers.update("triggername", {data: Object}, genericCallback);
triggers.delete("triggername", genericCallback);
+5
View File
@@ -0,0 +1,5 @@
declare global {
var ClearBlade: ClearBladeGlobal;
}
export {};
+436
View File
@@ -0,0 +1,436 @@
// Type definitions for clearbladejs-client 1.0
// Project: https://github.com/ClearBlade/JavaScript-API
// Definitions by: Jim Bouquet <https://github.com/ClearBlade>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/// <reference types="paho-mqtt" />
interface Resp {
error(msg: any): never; // todo: figure out if we can have the compiler throw an error if someone adds code after this
success(msg: any): never;
}
declare enum MessagingQOS {
MESSAGING_QOS_AT_MOST_ONCE = 0,
MESSAGING_QOS_AT_LEAST_ONCE = 1,
MESSAGING_QOS_EXACTLY_ONCE = 2
}
interface InitOptions {
systemKey: string;
systemSecret: string;
masterSecret?: string;
logging?: boolean;
callback?: CbCallback;
email?: string;
password?: string;
registerUser?: boolean;
useUser?: APIUser;
URI?: string;
messagingURI?: string;
messagingPort?: number;
defaultQoS?: MessagingQOS;
callTimeout?: number;
messagingAuthPort?: number;
}
interface RequestOptions {
method?: string;
endpoint?: string;
body?: string;
qs?: string;
URI?: string;
useUser?: boolean;
authToken?: string;
timeout?: number;
user?: APIUser;
}
interface APIUser {
email: string;
authToken: string;
}
type CbCallback = (error: boolean, response: Resp) => void;
interface ClearBladeGlobal extends ClearBladeInt {
MESSAGING_QOS_AT_MOST_ONCE: MessagingQOS.MESSAGING_QOS_AT_MOST_ONCE;
MESSAGING_QOS_AT_LEAST_ONCE: MessagingQOS.MESSAGING_QOS_AT_LEAST_ONCE;
MESSAGING_QOS_EXACTLY_ONCE: MessagingQOS.MESSAGING_QOS_EXACTLY_ONCE;
request(options: RequestOptions, callback: CbCallback): void;
}
interface ClearBladeInt {
systemKey: string;
systemSecret: string;
masterSecret: string;
URI: string;
messagingURI: string;
messagingPort: number;
logging: boolean;
defaultQoS: MessagingQOS;
init(options: InitOptions): void;
setUser(email: string, password: string): void;
registerUser(email: string, password: string, callback: CbCallback): void;
isCurrentUserAuthenticated(callback: CbCallback): void;
logoutUser(callback: CbCallback): void;
loginAnon(callback: CbCallback): void;
loginUser(email: string, password: string, callback: CbCallback): void;
loginUserMqtt(email: string, password: string, callback: CbCallback): void;
registerMasterCallback(callback: CbCallback): void;
Collection(options: string | CollectionOptionsWithName | CollectionOptionsWithID): Collection;
Query(
options: string | QueryOptionsWithName | QueryOptionsWithID
): QueryObj;
Item(data: object, collectionID: string | ItemOptions): Item;
Code(): Code;
User(): AppUser;
Messaging(options: MessagingOptions, callback: CbCallback): Messaging;
MessagingStats(): MessagingStats;
sendPush(
users: string[],
payload: object,
appId: string,
callback: CbCallback
): void;
getEdges(query: Query, callback: CbCallback): void;
Edge(): Edge;
Metrics(): Metrics;
Device(): Device;
Analytics(): Analytics;
Portal(name: string): Portal;
Triggers(): Triggers;
getAllCollections(callback: CbCallback): void;
}
interface CollectionOptionsWithName {
collectionName: string;
}
interface CollectionOptionsWithID {
collectionID: string;
}
interface Collection {
name: string;
endpoint: string;
isUsingCollectionName: boolean;
user: APIUser;
URI: string;
systemKey: string;
systemSecret: string;
fetch(query: Query, callback: CbCallback): void;
create(newItem: Item, callback: CbCallback): void;
update(query: Query, changes: object, callback: CbCallback): void;
remove(query: Query, callback: CbCallback): void;
columns(callback: CbCallback): void;
count(query: Query, callback: CbCallback): void;
}
declare enum QuerySortDirections {
QUERY_SORT_ASCENDING = "ASC",
QUERY_SORT_DESCENDING = "DESC"
}
declare enum QueryConditions {
QUERY_EQUAL = "EQ",
QUERY_NOTEQUAL = "NEQ",
QUERY_GREATERTHAN = "GT",
QUERY_GREATERTHAN_EQUAL = "GTE",
QUERY_LESSTHAN = "LT",
QUERY_LESSTHAN_EQUAL = "LTE",
QUERY_MATCHES = "RE"
}
type QueryValue = string | number | boolean;
interface QueryOptions {
offset?: number;
limit?: number;
}
interface QueryOptionsWithName
extends CollectionOptionsWithName,
QueryOptions {}
interface QueryOptionsWithID extends CollectionOptionsWithID, QueryOptions {}
interface Query {
SELECTCOLUMNS?: string[];
SORT?: QuerySortDirections;
FILTERS?: QueryFilter[];
PAGESIZE?: number;
PAGENUM?: number;
}
interface QueryFilter {
[QueryConditions: string]: QueryFilterValue;
}
interface QueryFilterValue {
[name: string]: QueryValue;
}
interface QueryObj {
endpoint: string;
user: APIUser;
URI: string;
systemKey: string;
systemSecret: string;
query: Query;
OR: Query[];
offset: number;
limit: number;
addSortToQuery(
query: QueryObj,
direction: QuerySortDirections,
column: string
): void;
addFilterToQuery(
query: QueryObj,
condition: QueryConditions,
key: string,
value: QueryValue
): void;
ascending(field: string): void;
descending(field: string): void;
equalTo(field: string, value: QueryValue): void;
greaterThan(field: string, value: QueryValue): void;
greaterThanEqualTo(field: string, value: QueryValue): void;
lessThan(field: string, value: QueryValue): void;
lessThanEqualTo(field: string, value: QueryValue): void;
notEqualTo(field: string, value: QueryValue): void;
matches(field: string, pattern: RegExp): void;
or(query: QueryObj): void;
setPage(pageSize: number, pageNum: number): void;
fetch(callback: CbCallback): void;
update(changes: object, callback: CbCallback): void;
columns(columnsArray: string[]): void;
remove(callback: CbCallback): void;
}
interface ItemOptions extends CollectionOptionsWithID {}
interface Item {
data: object;
save(callback: CbCallback): void;
refresh(callback: CbCallback): void;
destroy(callback: CbCallback): void;
}
interface Code {
user: APIUser;
URI: string;
systemKey: string;
systemSecret: string;
callTimeout: number;
create(name: string, body: string, callback: CbCallback): void;
update(name: string, body: string, callback: CbCallback): void;
delete(name: string, callback: CbCallback): void;
execute(name: string, params: object, callback: CbCallback): void;
getCompletedServices(callback: CbCallback): void;
getFailedServices(callback: CbCallback): void;
getAllServices(callback: CbCallback): void;
}
interface AppUser {
user: APIUser;
URI: string;
endpoint: string;
systemKey: string;
systemSecret: string;
callTimeout: number;
getUser(callback: CbCallback): void;
setUser(data: object, callback: CbCallback): void;
allUsers(query: Query, callback: CbCallback): void;
setPassword(
old_password: string,
new_password: string,
callback: CbCallback
): void;
count(query: Query, callback: CbCallback): void;
}
interface Messaging {
user: APIUser;
URI: string;
endpoint: string;
systemKey: string;
systemSecret: string;
callTimeout: number;
client: Paho.MQTT.Client;
getMessageHistoryWithTimeFrame(
topic: string,
count: number,
last: number,
start: number,
stop: number,
callback: CbCallback
): void;
getMessageHistory(
topic: string,
last: number,
count: number,
callback: CbCallback
): void;
getAndDeleteMessageHistory(
topic: string,
count: number,
last: number,
start: number,
stop: number,
callback: CbCallback
): void;
currentTopics(callback: CbCallback): void;
publish(topic: string, payload: object): void;
publishREST(topic: string, payload: object, callback: CbCallback): void;
subscribe(
topic: string,
options: MessagingSubscribeOptions,
messageCallback: MessageCallback
): void;
unsubscribe(topic: string, options: MessagingSubscribeOptions): void;
disconnect(): void;
}
interface CommonMessagingProperties {
cleanSession?: boolean;
useSSL?: boolean;
hosts?: string;
ports?: string;
onSuccess?: Function;
onFailure?: Function;
}
interface MessagingOptions extends CommonMessagingProperties {
qos?: MessagingQOS;
}
interface MessagingConfiguration extends CommonMessagingProperties {
userName: string;
password: string;
}
type MessageCallback = (message: string) => void;
interface MessagingSubscribeOptions {
qos?: MessagingQOS;
invocationContext?: object;
onSuccess?: Function;
onFailure?: Function;
timeout?: number;
}
interface MessagingStats {
user: APIUser;
URI: string;
endpoint: string;
systemKey: string;
getAveragePayloadSize(
topic: string,
start: number,
stop: number,
callback: CbCallback
): void;
getOpenConnections(callback: CbCallback): void;
getCurrentSubscribers(topic: string, callback: CbCallback): void;
}
interface Edge {
user: APIUser;
URI: string;
systemKey: string;
systemSecret: string;
updateEdgeByName(name: string, object: object, callback: CbCallback): void;
deleteEdgeByName(name: string, callback: CbCallback): void;
create(newEdge: object, name: string, callback: CbCallback): void;
columns(callback: CbCallback): void;
count(query: Query, callback: CbCallback): void;
}
interface Metrics {
user: APIUser;
URI: string;
systemKey: string;
setQuery(query: Query): void;
getStatistics(callback: CbCallback): void;
getStatisticsHistory(callback: CbCallback): void;
getDBConnections(callback: CbCallback): void;
getLogs(callback: CbCallback): void;
}
interface Device {
user: APIUser;
URI: string;
systemKey: string;
systemSecret: string;
getDeviceByName(name: string, callback: CbCallback): void;
updateDeviceByName(
name: string,
object: object,
trigger: boolean,
callback: CbCallback
): void;
deleteDeviceByName(name: string, callback: CbCallback): void;
fetch(query: Query, callback: CbCallback): void;
update(
query: Query,
object: object,
trigger: boolean,
callback: CbCallback
): void;
delete(query: Query, callback: CbCallback): void;
create(newDevice: object, callback: CbCallback): void;
columns(callback: CbCallback): void;
count(query: Query, callback: CbCallback): void;
}
interface Analytics {
user: APIUser;
URI: string;
systemKey: string;
systemSecret: string;
getStorage(filter: QueryFilter, callback: CbCallback): void;
getCount(filter: QueryFilter, callback: CbCallback): void;
getEventList(filter: QueryFilter, callback: CbCallback): void;
getEventTotals(filter: QueryFilter, callback: CbCallback): void;
getUserEvents(filter: QueryFilter, callback: CbCallback): void;
}
interface Portal {
name: string;
user: APIUser;
URI: string;
systemKey: string;
systemSecret: string;
fetch(callback: CbCallback): void;
update(data: object, callback: CbCallback): void;
}
interface Triggers {
user: APIUser;
URI: string;
systemKey: string;
systemSecret: string;
fetchDefinitions(callback: CbCallback): void;
create(name: string, data: object, callback: CbCallback): void;
update(name: string, data: object, callback: CbCallback): void;
delete(name: string, callback: CbCallback): void;
}
declare var ClearBlade: ClearBladeGlobal;

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