Merge branch 'master' of https://github.com/DefinitelyTyped/DefinitelyTyped into feature/update-localforage-typings

This commit is contained in:
recuedav
2016-10-04 14:55:15 +02:00
683 changed files with 180226 additions and 150309 deletions
+1
View File
@@ -401,6 +401,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](egg.js/egg.js.d.ts) [Egg.js](https://github.com/mikeflynn/egg.js) by [Markus Peloso](https://github.com/ToastHawaii)
* [:link:](ejs-locals/ejs-locals.d.ts) [ejs-locals](https://github.com/randometc/ejs-locals) by [jt000](https://github.com/jt000)
* [:link:](ejs/ejs.d.ts) [ejs.js](http://ejs.co) by [Ben Liddicott](https://github.com/benliddicott/DefinitelyTyped)
* [:link:](elasticsearch/elasticsearch.d.ts) [elasticsearch](https://www.elastic.co) by [Casper Skydt](https://github.com/CasperSkydt/DefinitelyTyped), [Blake Smith](https://github.com/bfsmith/DefinitelyTyped)
* [:link:](jquery.elang/jquery.elang.d.ts) [eLang](https://github.com/sumegizoltan/ELang) by [Zoltan Sumegi](https://github.com/sumegizoltan)
* [:link:](github-electron/github-electron.d.ts) [Electron](http://electron.atom.io) by [jedmao](https://github.com/jedmao), [rhysd](https://rhysd.github.io), [Milan Burda](https://github.com/miniak)
* [:link:](electron-builder/electron-builder.d.ts) [electron-builder](https://github.com/loopline-systems/electron-builder) by [Maxime LUCE](https://github.com/SomaticIT)
+4 -3
View File
@@ -8,10 +8,11 @@ interface HeadroomOptions {
tolerance?: any;
classes?: {
initial?: string;
pinned?: string;
unpinned?: string;
top?: string;
notBottom?:string;
notTop?: string;
pinned?: string;
top?: string;
unpinned?: string;
};
scroller?: Element;
onPin?: () => void;
+1 -1
View File
@@ -20,7 +20,7 @@ declare module "acl" {
type Callback = (err: Error) => any;
type AnyCallback = (err: Error, obj: any) => any;
type AllowedCallback = (err: Error, allowed: boolean) => any;
type GetUserId = (req: http.ServerRequest, res: http.ServerResponse) => Value;
type GetUserId = (req: http.IncomingMessage, res: http.ServerResponse) => Value;
interface AclStatic {
new (backend: Backend<any>, logger: Logger, options: Option): Acl;
@@ -0,0 +1,136 @@
/// <reference path="../node/node.d.ts" />
///<reference path="./algoliasearch-client-js.d.ts"/>
var algoliasearch = require('algoliasearch');
var _clientOptions: ClientOptions = {
timeout : 12,
protocol: "",
httpAgent: ""
};
var _synonymOption: SynonymOption = {
forwardToSlaves: false,
replaceExistingSynonyms: false
};
var _algoliaUserKeyOptions : AlgoliaUserKeyOptions = {
validity: 0,
maxQueriesPerIPPerHour: 0,
indexes: [""],
queryParameters: { attributesToRetrieve: ["algolia"] },
description: ""
};
var _searchSynonymOptions : SearchSynonymOptions = {
query: "",
page: 0,
type: "",
hitsPerPage: 0
};
var _algoliaSecuredApiOptions: AlgoliaSecuredApiOptions = {
filters: "",
validUntil: 0,
restrictIndices: "",
userToken: ""
};
var _algoliaIndexSettings : AlgoliaIndexSettings = {
attributesToIndex: [""],
attributesforFaceting: [""],
unretrievableAttributes: [""],
attributesToRetrieve: [""],
ranking: [""],
customRanking: [""],
slaves: [""],
maxValuesPerFacet: '',
attributesToHighlight: [""],
attributesToSnippet: [""],
highlightPreTag: '',
highlightPostTag: '',
snippetEllipsisText: '',
restrictHighlightAndSnippetArrays: false,
hitsPerPage: 0,
minWordSizefor1Typo: 0,
minWordSizefor2Typos: 0,
typoTolerance: false,
allowTyposOnNumericTokens: false,
ignorePlurals: false,
disableTypoToleranceOnAttributes: '',
separatorsToIndex: '',
queryType: '',
removeWordsIfNoResults: '',
advancedSyntax: false,
optionalWords: [""],
removeStopWords: [""],
disablePrefixOnAttributes: [""],
disableExactOnAttributes: [""],
exactOnSingleWordQuery: '',
alternativesAsExact: false,
attributeForDistinct: "",
distinct: false,
numericAttributesToIndex: [""],
allowCompressionOfIntegerArray: false,
altCorrections: [{}],
minProximity: 0,
placeholders: ''
};
var _algoliaQueryParameters : AlgoliaQueryParameters = {
query: '',
filters: '',
attributesToRetrieve: [""],
restrictSearchableAttributes: [""],
facets: '',
maxValuesPerFacet: '',
attributesToHighlight: [''],
attributesToSnippet: [''],
highlightPreTag: '',
highlightPostTag: '',
snippetEllipsisText: '',
restrictHighlightAndSnippetArrays: false,
hitsPerPage: 0,
page: 0,
offset: 0,
length: 0,
minWordSizefor1Typo: 0,
minWordSizefor2Typos: 0,
typoTolerance: false,
allowTyposOnNumericTokens: false,
ignorePlurals: false,
disableTypoToleranceOnAttributes: '',
aroundLatLng: '',
aroundLatLngViaIP: '',
aroundRadius: '',
aroundPrecision: 0,
minimumAroundRadius: 0,
insideBoundingBox: '',
queryType: '',
insidePolygon: '',
removeWordsIfNoResults: '',
advancedSyntax: false,
optionalWords: [''],
removeStopWords: [''],
disableExactOnAttributes: [''],
exactOnSingleWordQuery: '',
alternativesAsExact: true,
distinct: 0,
getRankingInfo: false,
numericAttributesToIndex: [''],
numericFilters: [''],
tagFilters: '',
facetFilters: '',
analytics: false,
analyticsTags: [''],
synonyms: true,
replaceSynonymsInHighlight: false,
minProximity: 0
};
var index: AlgoliaIndex = algoliasearch('', '').initIndex('');
var search = index.search({query: ""});
index.search({query: ""}, function(err, res){});
File diff suppressed because it is too large Load Diff
+9
View File
@@ -27,6 +27,9 @@ declare namespace AmCharts {
/** Clears all the charts on page, removes listeners and intervals. */
function clear();
/** Handle ready event */
function ready(Function): void;
/** Create chart by params. */
function makeChart(selector: string, params: any, delay?: number): AmChart;
@@ -961,6 +964,10 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val
@Default 150
*/
hideBalloonTime: number;
/** Allows changing language easily.
* Note, you should include the language.js file from amcharts/lang or ammap/lang folder and then use variable name used in this file, like chart.language = "de";
* Note, for maps this works differently - you use language only for country names, as there are no other strings in the maps application. */
language: string;
/** Legend of a chart. */
legend: AmLegend;
/** Reference to the div of the legend. */
@@ -989,6 +996,8 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val
prefixesOfBigNumbers: any[];
/** Prefixes which are used to make small numbers shorter: 2μ instead of 0.000002, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e-24, prefix:"y"},{number:1e-21, prefix:"z"},{number:1e-18, prefix:"a"},{number:1e-15, prefix:"f"},{number:1e-12, prefix:"p"},{number:1e-9, prefix:"n"},{number:1e-6, prefix:"μ"},{number:1e-3, prefix:"m"}] */
prefixesOfSmallNumbers: any[];
/** A config object for Responsive plugin. */
responsive: any;
/** Theme of a chart. Config files of themes can be found in amcharts/themes/ folder. More info about using themes. */
theme: string;
/** Thousands separator.
+87
View File
@@ -0,0 +1,87 @@
// Tests for Amplitude SDK TypeScript definitions
/// <reference path="amplitude-js.d.ts" />
module Amplitude.Tests {
function all() {
amplitude.init('YOUR_API_KEY_HERE', null, {
// optional configuration options
saveEvents: true,
includeUtm: true,
includeReferrer: true,
batchEvents: true,
eventUploadThreshold: 50
});
amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE', null, () => {});
amplitude.logEvent('EVENT_IDENTIFIER_HERE');
amplitude.setUserId('USER_ID_HERE');
amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE');
amplitude.setUserId(null); // not string 'null'
amplitude.setVersionName('VERSION_NAME_HERE');
amplitude.regenerateDeviceId();
amplitude.setDeviceId('CUSTOM_DEVICE_ID');
amplitude.logEvent('EVENT_IDENTIFIER_HERE', {
'color': 'blue',
'age': 20,
'key': 'value'
});
amplitude.logEvent("EVENT_IDENTIFIER_HERE", null, (httpCode, response) => { });
let identify = new amplitude.Identify().set('gender', 'female').set('age', 20);
amplitude.identify(identify);
identify = new amplitude.Identify().setOnce('sign_up_date', '08/24/2015');
amplitude.identify(identify);
identify = new amplitude.Identify().setOnce('sign_up_date', '09/14/2015');
amplitude.identify(identify);
identify = new amplitude.Identify().unset('gender').unset('age');
amplitude.identify(identify);
identify = new amplitude.Identify().add('karma', 1).add('friends', 1);
amplitude.identify(identify);
identify = new amplitude.Identify().append('ab-tests', 'new-user-test').append('some_list', [1, 2, 3, 4, 'values']);
amplitude.identify(identify);
identify = new amplitude.Identify().prepend('ab-tests', 'new-user-test').prepend('some_list', [1, 2, 3, 4, 'values']);
amplitude.identify(identify);
identify = new amplitude.Identify()
.set('karma', 10)
.add('karma', 1)
.unset('karma');
amplitude.identify(identify);
identify = new amplitude.Identify()
.set('colors', ['rose', 'gold'])
.append('ab-tests', 'campaign_a')
.append('existing_list', [4, 5]);
amplitude.identify(identify);
amplitude.setUserProperties({
gender: 'female',
age: 20
});
amplitude.clearUserProperties();
amplitude.setOptOut(true);
amplitude.setOptOut(false);
amplitude.setGroup('orgId', '15');
amplitude.setGroup('sport', ['soccer', 'tennis']);
// TODO: Implement those.
/*
var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3);
amplitude.logRevenueV2(revenue);
amplitude.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' });
*/
}
}
+61
View File
@@ -0,0 +1,61 @@
// Type definitions for Amplitude SDK 2.12.1
// Project: https://github.com/amplitude/Amplitude-Javascript
// Definitions by: Arvydas Sidorenko <https://github.com/Asido>
// Definitions: https://github.com/Asido/DefinitelyTyped
declare module amplitude {
interface Config {
batchEvents?: boolean;
cookieExpiration?: number;
cookieName?: string;
deviceId?: string;
domain?: string;
eventUploadPeriodMillis?: number;
eventUploadThreshold?: number;
includeReferrer?: boolean;
includeUtm?: boolean;
language?: string;
optOut?: boolean;
platform?: string;
saveEvents?: boolean;
savedMaxCount?: number;
sessionTimeout?: number;
uploadBatchSize?: number;
}
export class Identify {
set(key: string, value: any): Identify;
setOnce(key: string, value: any): Identify;
add(key: string, value: number): Identify;
append(key: string, value: any): Identify;
prepend(key: string, value: any): Identify;
unset(key: string): Identify;
}
export function init(apiKey: string): void;
export function init(apiKey: string, userId: string): void;
export function init(apiKey: string, userId: string, options: Config): void;
export function init(apiKey: string, userId: string, options: Config, callback: () => void): void;
export function setVersionName(version: string): void;
export function setUserId(userId: string): void;
export function setDeviceId(id: string): void;
export function regenerateDeviceId(): void;
export function identify(identify: Identify): void;
export function setUserProperties(properties: Object): void;
export function clearUserProperties(): void;
export function setOptOut(optOut: boolean): void;
export function setGroup(groupType: string, groupName: string | string[]): void;
export function logEvent(event: string): void;
export function logEvent(event: string, data: Object): void;
export function logEvent(event: string, data: Object, callback: (httpCode: number, response: any) => void): void;
export var options: Config;
}
+2 -2
View File
@@ -14,7 +14,7 @@ declare namespace angular.ui {
/**
* Override the parent state (only for the breadcrumb)
**/
parent?: string;
parent?: string|Function;
/**
* When defined to true, the state is never included in the chain of states and never appears in the breadcrumb
**/
@@ -76,4 +76,4 @@ declare namespace ncy {
**/
getLastStep(): angular.ui.IState;
}
}
}
+1
View File
@@ -20,6 +20,7 @@ declare namespace angular.dynamicLocale {
interface tmhDynamicLocaleProvider extends angular.IServiceProvider {
localeLocationPattern(location: string): tmhDynamicLocaleProvider;
localeLocationPattern(): string;
storageKey(storageKey: string): void;
useStorage(storageName: string): void;
useCookieStorage(): void;
}
+15 -15
View File
@@ -45,12 +45,12 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Component: (component: iComponent) => ngESDecorator;
function Component(component: iComponent): ngESDecorator;
/**
* Register config block
*/
var Config: () => ngESDecorator;
function Config(): ngESDecorator;
/**
* Register constant
@@ -59,7 +59,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Constant: (name: string) => ngESDecorator;
function Constant(name: string): ngESDecorator;
/**
* Register controller
@@ -68,7 +68,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Controller: (name: string) => ngESDecorator;
function Controller(name: string): ngESDecorator;
/**
* Register decorator
@@ -77,7 +77,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Decorator: (name: string) => ngESDecorator;
function Decorator(name: string): ngESDecorator;
/**
* Register directive
@@ -86,7 +86,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Directive: (name: string) => ngESDecorator;
function Directive(name: string): ngESDecorator;
/**
* Register factory
@@ -95,7 +95,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Factory: (name: string) => ngESDecorator;
function Factory(name: string): ngESDecorator;
/**
* Register filter
@@ -104,7 +104,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Filter: (name: string) => ngESDecorator;
function Filter(name: string): ngESDecorator;
/**
* Add $inject property to target
@@ -113,7 +113,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Inject: (...dependencies: Array<string>) => ngESDecorator;
function Inject(...dependencies: Array<string>): ngESDecorator;
/**
* Inject dependencies as properties to target
@@ -122,7 +122,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var InjectAsProperty: (...dependencies: Array<string>) => ngESDecorator;
function InjectAsProperty(...dependencies: Array<string>): ngESDecorator;
/**
* Attach target to the specified module
@@ -131,7 +131,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Module: (name: string) => ngESDecorator;
function Module(name: string): ngESDecorator;
/**
* Register provider
@@ -140,14 +140,14 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Provider: (name: string) => ngESDecorator;
function Provider(name: string): ngESDecorator;
/**
* Register run block
*
* @returns {ngESDecorator} - decorated class
*/
var Run: () => ngESDecorator;
function Run(): ngESDecorator;
/**
* Register service
@@ -156,7 +156,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Service: (name: string) => ngESDecorator;
function Service(name: string): ngESDecorator;
/**
* Register value
@@ -165,7 +165,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Value: (name: string) => ngESDecorator;
function Value(name: string): ngESDecorator;
export {
Component,
@@ -0,0 +1,31 @@
/// <reference path="angular-feature-flags.d.ts" />
let myApp = angular.module('myApp', ['feature-flags']);
const flagsData: Array<angular.featureflags.FlagData> = [
{
key: '1',
active: true,
name: 'flag1',
description: 'This is the first flag'
},
{
key: '2',
active: false,
name: 'flag2',
description: 'This is the second flag'
}
];
myApp.config(function (featureFlagsProvider: angular.featureflags.FeatureFlagsProvider) {
featureFlagsProvider.setInitialFlags(flagsData);
});
myApp.run(function ($q: angular.IQService, $http: angular.IHttpService, featureFlags: angular.featureflags.FeatureFlagsService) {
let deferred = $q.defer();
deferred.resolve(flagsData);
featureFlags.set(deferred.promise);
featureFlags.set($http.get('/data/flags.json'));
});
+38
View File
@@ -0,0 +1,38 @@
// Type definitions for angular-feature-flags 1.4.0
// Project: https://github.com/mjt01/angular-feature-flags
// Definitions by: Borislav Zhivkov <https://github.com/borislavjivkov/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare namespace angular.featureflags {
export interface FlagData {
/**
* Unique key that is used from the markup to resolve whether a flag is active or not.
*/
key: string;
/**
* Boolean value for enabling/disabling the feature
*/
active: boolean;
/**
* A short name of the flag (only visible in the list of flags)
*/
name: string;
/**
* A long description of the flag to further explain the feature being toggled (only visible in the list of flags)
*/
description: string;
}
export interface FeatureFlagsProvider {
setInitialFlags(flags: Array<FlagData>): void;
}
export interface FeatureFlagsService {
set(flagsPromise: angular.IPromise<FlagData> | angular.IHttpPromise<FlagData>): void;
}
}
+3 -3
View File
@@ -51,12 +51,12 @@ declare namespace angular.gettext {
/** Get the correct pluralized (but untranslated) string for the value of n. */
getStringForm(string: string, n: number): string;
/** Translate a string with the given context. Uses Angular.JS interpolation, so something like this will do what you expect:
/** Translate a string with the given scope. Uses Angular.JS interpolation, so something like this will do what you expect:
* var hello = gettextCatalog.getString("Hello {{name}}!", { name: "Ruben" });
* // var hello will be "Hallo Ruben!" in Dutch.
* The context parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster.
* The scope parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster.
*/
getString(string: string, context?: any): string;
getString(string: string, scope?: any, context?: string): string;
/** Translate a plural string with the given context. */
getPlural(n: number, string: string, stringPlural: string, context?: any): string;
+15
View File
@@ -15,3 +15,18 @@ var $jwtInterceptor: ng.jwt.IJwtInterceptor;
$jwtInterceptor.tokenGetter = () => {
return expToken;
}
var authManager: ng.jwt.IAuthManagerServiceProvider;
// Indicate the user is authenticated
authManager.authenticate();
// Indicate the user is unauthenticated
authManager.unauthenticate();
// Keep the user authenticated
authManager.checkAuthOnRefresh();
// Redirect the user on unauthorized requests
authManager.redirectWhenUnauthenticated();
+7
View File
@@ -27,4 +27,11 @@ declare namespace angular.jwt {
interface IJwtInterceptor {
tokenGetter(...params : any[]): string;
}
interface IAuthManagerServiceProvider {
authenticate(): void;
unauthenticate(): void;
checkAuthOnRefresh(): void;
redirectWhenUnauthenticated(): void;
}
}
+45 -1
View File
@@ -20,6 +20,13 @@ myApp.config((
.warnPalette('red')
.dark(true);
var browserColors: ng.material.IBrowserColors = {
theme: 'default',
palette: 'neonRed',
hue: '500'
};
$mdThemingProvider.enableBrowserColor(browserColors);
$mdIconProvider
.defaultIconSet('my/app/icons.svg') // Register a default set of SVG icons
.iconSet('social', 'my/app/social.svg') // Register a named icon set of SVGs
@@ -41,6 +48,25 @@ myApp.controller('BottomSheetController', ($scope: ng.IScope, $mdBottomSheet: ng
$scope['cancelBottomSheet'] = $mdBottomSheet.cancel.bind($mdBottomSheet, 'cancel');
});
myApp.controller('ColorController', ($scope: ng.IScope, $mdColor: ng.material.IColorService) => {
var colorExpression : ng.material.IColorExpression;
var element : Element;
colorExpression = { color: '#FFFFFF' }
element = new Element();
$scope['applyThemeColors'] = () => {
$mdColor.applyThemeColors(element, colorExpression);
};
$scope['getThemeColor'] = () => {
$mdColor.getThemeColor('default-neonRed')
};
$scope['hasTheme'] = () => {
$mdColor.hasTheme();
};
});
myApp.controller('DialogController', ($scope: ng.IScope, $mdDialog: ng.material.IDialogService) => {
$scope['openDialog'] = () => {
$mdDialog.show({
@@ -127,15 +153,33 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia
instance.isOpen();
instance.isLockedOpen();
});
$scope['onClose'] = $mdSidenav(componentId).onClose(() => {});
});
myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => {
$scope['openToast'] = () => $mdToast.show($mdToast.simple().textContent('Hello!'));
$scope['openToast'] = () => {
$mdToast.show($mdToast.simple().textContent('Hello!'));
$mdToast.updateTextContent('New Content');
}
$scope['customToast'] = () => {
var options = {
hideDelay: 3000,
position: 'top right',
controller : 'ToastCtrl',
templateUrl : 'toast-template.html',
toastClass: 'my-class'
};
$mdToast.show(options);
}
});
myApp.controller('PanelController', ($scope: ng.IScope, $mdPanel: ng.material.IPanelService) => {
$scope['createPanel'] = () => {
var config = {
id: 'myPanel',
template: '<h1>Hello!</h1>',
hasBackdrop: true,
disableParentScroll: true,
+40 -12
View File
@@ -22,7 +22,7 @@ declare namespace angular.material {
clickOutsideToClose?: boolean;
disableBackdrop?: boolean;
escapeToClose?: boolean;
resolve?: {[index: string]: angular.IPromise<any>};
resolve?: {[index: string]: () => angular.IPromise<any>};
controllerAs?: string;
parent?: Function|string|Object; // default: root node
disableParentScroll?: boolean; // default: true
@@ -53,7 +53,7 @@ declare namespace angular.material {
controller(controller?: string|Function): T;
locals(locals?: {[index: string]: any}): T;
bindToController(bindToController?: boolean): T; // default: false
resolve(resolve?: {[index: string]: angular.IPromise<any>}): T;
resolve(resolve?: {[index: string]: () => angular.IPromise<any>}): T;
controllerAs(controllerAs?: string): T;
parent(parent?: string|Element|JQuery): T; // default: root node
onComplete(onComplete?: Function): T;
@@ -73,6 +73,16 @@ declare namespace angular.material {
initialValue(initialValue: string): IPromptDialog;
}
interface IColorExpression {
[cssPropertyName: string]: string
}
interface IColorService {
applyThemeColors(element: Element|JQuery, colorExpression: IColorExpression): void;
getThemeColor(expression: string): string;
hasTheme(): boolean;
}
interface IDialogOptions {
templateUrl?: string;
template?: string;
@@ -91,7 +101,7 @@ declare namespace angular.material {
controller?: string|Function;
locals?: {[index: string]: any};
bindToController?: boolean; // default: false
resolve?: {[index: string]: angular.IPromise<any>}
resolve?: {[index: string]: () => angular.IPromise<any>}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
onShowing?: Function;
@@ -132,6 +142,7 @@ declare namespace angular.material {
close(): angular.IPromise<void>;
isOpen(): boolean;
isLockedOpen(): boolean;
onClose(onClose: Function): void;
}
interface ISidenavService {
@@ -162,10 +173,11 @@ declare namespace angular.material {
preserveScope?: boolean; // default: false
hideDelay?: number; // default (ms): 3000
position?: string; // any combination of 'bottom'/'left'/'top'/'right'/'fit'; default: 'bottom left'
toastClass?: string;
controller?: string|Function;
locals?: {[index: string]: any};
bindToController?: boolean; // default: false
resolve?: {[index: string]: angular.IPromise<any>}
resolve?: {[index: string]: () => angular.IPromise<any>}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
}
@@ -175,7 +187,8 @@ declare namespace angular.material {
showSimple(content: string): angular.IPromise<any>;
simple(): ISimpleToastPreset;
build(): IToastPreset<any>;
updateContent(): void;
updateContent(newContent: string): void;
updateTextContent(newContent: string): void
hide(response?: any): void;
cancel(response?: any): void;
}
@@ -213,6 +226,12 @@ declare namespace angular.material {
hues: IThemeHues;
}
interface IBrowserColors{
theme: string;
palette: string;
hue: string;
}
interface IThemeColors {
accent: IThemePalette;
background: IThemePalette;
@@ -242,12 +261,14 @@ declare namespace angular.material {
}
interface IThemingProvider {
theme(name: string, inheritFrom?: string): ITheme;
definePalette(name: string, palette: IPalette): IThemingProvider;
extendPalette(name: string, palette: IPalette): IPalette;
setDefaultTheme(theme: string): void;
alwaysWatchTheme(alwaysWatch: boolean): void;
definePalette(name: string, palette: IPalette): IThemingProvider;
enableBrowserColor(browserColors: IBrowserColors): Function;
extendPalette(name: string, palette: IPalette): IPalette;
registerStyles(styles: String): void;
setDefaultTheme(theme: string): void;
setNonce(nonce: string): void;
theme(name: string, inheritFrom?: string): ITheme;
}
interface IDateLocaleProvider {
@@ -291,13 +312,14 @@ declare namespace angular.material {
}
interface IPanelConfig {
id?: string;
template?: string;
templateUrl?: string;
controller?: string|Function;
controllerAs?: string;
bindToController?: boolean; // default: true
locals?: {[index: string]: any};
resolve?: {[index: string]: angular.IPromise<any>}
resolve?: {[index: string]: () => angular.IPromise<any>}
attachTo?: string|JQuery|Element;
propagateContainerEvents?: boolean;
panelClass?: string;
@@ -333,6 +355,9 @@ declare namespace angular.material {
removeClass(oldClass: string): void;
toggleClass(toggleClass: string): void;
updatePosition(position: IPanelPosition): void;
registerInterceptor(type: string, callback: () => angular.IPromise<any>): IPanelRef;
removeInterceptor(type: string, callback: () => angular.IPromise<any>): IPanelRef;
removeAllInterceptors(type?: string): IPanelRef;
}
interface IPanelPosition {
@@ -348,8 +373,8 @@ declare namespace angular.material {
centerVertically(): IPanelPosition;
center(): IPanelPosition;
addPanelPosition(xPosition: string, yPosition: string): IPanelPosition;
withOffsetX(offsetX: string): IPanelPosition;
withOffsetY(offsetY: string): IPanelPosition;
withOffsetX(offsetX: string|((panel: IPanelPosition) => string)): IPanelPosition;
withOffsetY(offsetY: string|((panel: IPanelPosition) => string)): IPanelPosition;
}
interface IPanelAnimation {
@@ -382,5 +407,8 @@ declare namespace angular.material {
SCALE: string,
FADE: string,
};
interceptorTypes: {
CLOSE: string,
};
}
}
@@ -1,5 +1,5 @@
/// <reference path='angular-signalr-hub.d.ts' />
/// <reference path='../angularjs/angular.d.ts' />
/// <reference path='angular-signalr-hub.d.ts' />
angular
.module('app', ['SignalR'])
+6
View File
@@ -3,8 +3,14 @@
// Definitions by: Adam Santaniello <https://github.com/AdamSantaniello>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path='../angularjs/angular.d.ts' />
/// <reference path='../signalr/signalr.d.ts' />
declare module "angular-signalr-hub" {
let _: string;
export = _;
}
declare namespace ngSignalr {
interface HubFactory {
/**
+3 -3
View File
@@ -2,9 +2,9 @@
/// <reference path='angular-touchspin.d.ts' />
angular
.module('touchspin-tests', ['lm.touchspin'])
.config(function(touchspinConfigProvider: angularTouchSpin.ITouchSpinConfigProvider) {
touchspinConfigProvider.defaults(<angularTouchSpin.ITouchSpinOptions>{
.module('touchspin-tests', ['nk.touchspin'])
.config(function(touchspinConfigProvider: angular.touchspin.ITouchSpinConfigProvider) {
touchspinConfigProvider.defaults(<angular.touchspin.ITouchSpinOptions>{
min: 0,
max: 0,
step: 0,
+1 -1
View File
@@ -11,7 +11,7 @@ declare module "angular-touchspin" {
export = _;
}
declare namespace angularTouchSpin {
declare namespace angular.touchspin {
interface ITouchSpinOptions {
min?: number;
max?: number;
+11
View File
@@ -400,6 +400,17 @@ declare namespace angular.ui.bootstrap {
* @default 'body'
*/
appendTo?: angular.IAugmentedJQuery;
/**
* A string reference to the component to be rendered that is registered with Angular's compiler. If using a directive, the directive must have `restrict: 'E'` and a template or templateUrl set.
*
* It supports these bindings:
* - `close` - A method that can be used to close a modal, passing a result. The result must be passed in this format: `{$value: myResult}`
* - `dismiss` - A method that can be used to dismiss a modal, passing a result. The result must be passed in this format: `{$value: myRejectedResult}`
* - `modalInstance` - The modal instance. This is the same `$uibModalInstance` injectable found when using `controller`.
* - `resolve` - An object of the modal resolve values. See [UI Router resolves] for details.
*/
component?: string;
}
interface IModalStackService {
@@ -0,0 +1,30 @@
/// <reference path="angular-ui-notification.d.ts" />
function TestNotifications(NotificationProvider: angular.uiNotification.INotificationProvider, Notification: angular.uiNotification.INotificationService) {
NotificationProvider.setOptions({
delay: 10000,
startTop: 20,
startRight: 10,
verticalSpacing: 20,
horizontalSpacing: 20,
positionX: 'left',
positionY: 'bottom'
});
Notification.primary('Primary notification');
Notification('Primary notification');
Notification.success('Success notification');
Notification({message: 'Warning notification'}, 'warning');
Notification({message: 'Primary notification', title: 'Primary notification'});
Notification.error({message: 'Error notification 1s', delay: 1000});
Notification.success({message: 'Success notification<br>Some other <b>content</b><br><a href="https://github.com/alexcrack/angular-ui-notification">This is a link</a><br><img src="https://angularjs.org/img/AngularJS-small.png">', title: 'Html content'});
Notification.error({message: 'Error Bottom Right', positionY: 'bottom', positionX: 'right'});
Notification.error({message: 'Error notification 1s', replaceMessage: true});
}
+82
View File
@@ -0,0 +1,82 @@
// Type definitions for angular-ui-notification
// Project: https://github.com/alexcrack/angular-ui-notification
// Definitions by: Kamil Rojewski <https://github.com/krojew/DefinitelyTyped>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace angular.uiNotification {
// Taken from angular to avoid dependency
interface IPromise<T> {
/**
* Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected.
* The successCallBack may return IPromise<void> for when a $q.reject() needs to be returned
* This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method.
*/
then<TResult>(successCallback: (promiseValue: T) => IPromise<TResult>|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise<TResult>;
/**
* Shorthand for promise.then(null, errorCallback)
*/
catch<TResult>(onRejected: (reason: any) => IPromise<TResult>|TResult): IPromise<TResult>;
/**
* Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information.
*
* Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible.
*/
finally(finallyCallback: () => any): IPromise<T>;
}
type XPosition = 'right'|'left'|'center';
type YPosition = 'top'|'bottom';
type MessageType = 'primary'|'info'|'success'|'warning'|'error';
interface IGlobalMessageOptions {
delay?: number;
startTop?: number;
startRight?: number;
verticalSpacing?: number;
horizontalSpacing?: number;
positionX?: XPosition;
positionY?: YPosition;
replaceMessage?: boolean;
templateUrl?: string;
onClose?: (element: any) => any;
closeOnClick?: boolean;
maxCount?: number;
}
interface IMessageOptions {
title?: string;
message?: string;
templateUrl?: string;
delay?: number;
type?: MessageType;
positionX?: XPosition;
positionY?: YPosition;
replaceMessage?: boolean;
closeOnClick?: boolean;
}
interface INotificationScope {
kill(isHard: boolean): void;
}
interface INotificationProvider {
setOptions(options: IGlobalMessageOptions): void;
}
type Message = string|IMessageOptions;
interface INotificationService {
primary(message: Message): IPromise<INotificationScope>;
info(message: Message): IPromise<INotificationScope>;
success(message: Message): IPromise<INotificationScope>;
warning(message: Message): IPromise<INotificationScope>;
error(message: Message): IPromise<INotificationScope>;
clearAll(): void;
(message: Message, type?: MessageType): IPromise<INotificationScope>;
}
}
+3 -2
View File
@@ -42,9 +42,10 @@ declare namespace angular.ui {
*/
topVisibleScope: ng.IRepeatScope;
/**
* calling this method reinitializes and reloads the scroller content.
* calling this method reinitializes and reloads the scroller content.
* @param startIndex is an integer indicating what item index the scroller will use to start the load process.
*/
reload(): void;
reload(startIndex?: number): void;
/**
* Replaces the item in the buffer at the given index with the new items.
*
+14 -3
View File
@@ -42,15 +42,20 @@ declare namespace angular.resource {
(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): IResourceClass<IResource<any>>;
actions?: IActionHash, options?: IResourceOptions): IResourceClass<IResource<any>>;
<T, U>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): U;
actions?: IActionHash, options?: IResourceOptions): U;
<T>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): IResourceClass<T>;
actions?: IActionHash, options?: IResourceOptions): IResourceClass<T>;
}
// Hash of action descriptors allows custom action names
interface IActionHash {
[action: string]: IActionDescriptor
}
// Just a reference to facilitate describing new actions
@@ -186,6 +191,12 @@ declare namespace angular {
/** creating a resource service factory */
factory(name: string, resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction<any>): IModule;
}
namespace auto {
interface IInjectorService {
get(name: '$resource'): ng.resource.IResourceService;
}
}
}
interface Array<T>
+28 -6
View File
@@ -1,10 +1,32 @@
/// <reference path="angular-sanitize.d.ts" />
var shouldBeString: string;
///////////////////////////////////////////////////////////////////////////////
// Variables
///////////////////////////////////////////////////////////////////////////////
let shouldBeString: string;
let testInputText: string = 'TEST';
declare var $sanitizeService: ng.sanitize.ISanitizeService;
shouldBeString = $sanitizeService(shouldBeString);
///////////////////////////////////////////////////////////////////////////////
// Test sanitize service
///////////////////////////////////////////////////////////////////////////////
declare let $sanitizeService: ng.sanitize.ISanitizeService;
shouldBeString = $sanitizeService(testInputText);
declare var $linky: ng.sanitize.filter.ILinky;
shouldBeString = $linky(shouldBeString);
shouldBeString = $linky(shouldBeString, shouldBeString);
///////////////////////////////////////////////////////////////////////////////
// Test `linky` filter
///////////////////////////////////////////////////////////////////////////////
declare let $linky: ng.sanitize.filter.ILinky;
// Should be string for simple text and target parameters
shouldBeString = $linky(testInputText, testInputText);
// Should be string for simple text, target and attributes parameters
let attributesAsFunction = () => {
};
shouldBeString = $linky(shouldBeString, testInputText, {
"attributeKey1": "attributeValue1",
"attributeKey2": "attributeValue2"
});
shouldBeString = $linky(shouldBeString, testInputText, (url: string) => {
return {"attributeKey1": "attributeValue1"}
});
+18 -5
View File
@@ -29,12 +29,25 @@ declare namespace angular.sanitize {
// see https://github.com/angular/angular.js/tree/v1.2.0/src/ngSanitize/filter
///////////////////////////////////////////////////////////////////////////
export module filter {
// Finds links in text input and turns them into html links.
// Supports http/https/ftp/mailto and plain email address links.
// see http://code.angularjs.org/1.2.0/docs/api/ngSanitize.filter:linky
/**
* Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and plain email address links.
* @param text Input text.
* @param target ILinkyTargetType Window (_blank|_self|_parent|_top) or named frame to open links in.
* @param attributes Add custom attributes to the link element.
* @return Html-linkified and sanitized text.
* see https://docs.angularjs.org/api/ngSanitize/filter/linky
*/
interface ILinky {
(text: string, target?: string): string;
(text: string, target: string, attributes?: { [attribute: string]: string } | ((url: string) => { [attribute: string]: string })): string;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Extend angular $filter declarations to include filters from angular.sanitize module
///////////////////////////////////////////////////////////////////////////////
declare namespace angular {
interface IFilterService {
(name: 'linky'): angular.sanitize.filter.ILinky;
}
}
+55 -9
View File
@@ -180,25 +180,51 @@ namespace My.Namespace {
// IModule Registering Test
var mod = angular.module('tests', []);
mod.controller('name', function ($scope: ng.IScope) { })
mod.controller('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.controller(My.Namespace);
mod.controller('name', function ($scope: ng.IScope) { });
mod.controller('name', ['$scope', function ($scope: ng.IScope) { }]);
mod.controller('name', class {
// Uncommenting the next line should lead to a type error because this signature isn't compatible
// with the signature of the `$onChanges` hook:
// $onChanges(x: number) { }
});
mod.controller({
MyCtrl: class{},
MyCtrl2: function() {},
MyCtrl3: ['$fooService', function($fooService: any) { }]
});
mod.directive('name', <any>function ($scope: ng.IScope) { })
mod.directive('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.directive(My.Namespace);
mod.directive({
myFooDir: () => ({
template: 'my-foo-dir.tpl.html'
}),
myBarDir: ['$fooService', ($fooService: any) => ({
template: 'my-bar-dir.tpl.html'
})]
});
mod.factory('name', function ($scope: ng.IScope) { })
mod.factory('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.factory(My.Namespace);
mod.factory('name', ['$scope', function ($scope: ng.IScope) { }])
mod.factory({
name1: function (foo: any) { },
name2: ['foo', function (foo: any) { }]
});
mod.filter('name', function ($scope: ng.IScope) { })
mod.filter('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.filter(My.Namespace);
mod.filter('name', ['$scope', function ($scope: ng.IScope) { }])
mod.filter({
name1: function (foo: any) { },
name2: ['foo', function (foo: any) { }]
});
mod.provider('name', function ($scope: ng.IScope) { return { $get: () => { } } })
mod.provider('name', TestProvider);
mod.provider('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.provider(My.Namespace);
mod.service('name', function ($scope: ng.IScope) { })
mod.service('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.service(My.Namespace);
mod.service({
MyCtrl: class{},
MyCtrl2: function() {},
MyCtrl3: ['$fooService', function($fooService: any) { }]
});
mod.constant('name', 23);
mod.constant('name', "23");
mod.constant(My.Namespace);
@@ -867,6 +893,26 @@ angular.module('docsTabsExample', [])
};
});
angular.module('multiSlotTranscludeExample', [])
.directive('dropDownMenu', function() {
return {
transclude: {
button: 'button',
list: 'ul',
},
link: function(scope, element, attrs, ctrl, transclude) {
// without scope
transclude().appendTo(element);
transclude(clone => clone.appendTo(element));
// with scope
transclude(scope, clone => clone.appendTo(element));
transclude(scope, clone => clone.appendTo(element), element, 'button');
transclude(scope, null, element, 'list').addClass('drop-down-list').appendTo(element);
}
};
});
angular.module('componentExample', [])
.component('counter', {
require: {'ctrl': '^ctrl'},
+90 -97
View File
@@ -1,6 +1,6 @@
// Type definitions for Angular JS 1.5
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Georgii Dolzhykov <http://github.com/thorn0>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -25,6 +25,8 @@ declare module 'angular' {
///////////////////////////////////////////////////////////////////////////////
declare namespace angular {
type Injectable<T extends Function> = T | (string | T)[];
// not directly implemented, but ensures that constructed class implements $get
interface IServiceProviderClass {
new (...args: any[]): IServiceProvider;
@@ -125,6 +127,7 @@ declare namespace angular {
isFunction(value: any): value is Function;
isNumber(value: any): value is number;
isObject(value: any): value is Object;
isObject<T>(value: any): value is T;
isString(value: any): value is string;
isUndefined(value: any): boolean;
lowercase(str: string): string;
@@ -213,50 +216,26 @@ declare namespace angular {
* @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors.
* @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation).
*/
controller(name: string, controllerConstructor: Function): IModule;
/**
* The $controller service is used by Angular to create new controllers.
*
* This provider allows controller registration via the register method.
*
* @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors.
* @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation).
*/
controller(name: string, inlineAnnotatedConstructor: any[]): IModule;
controller(object: Object): IModule;
controller(name: string, controllerConstructor: Injectable<IControllerConstructor>): IModule;
controller(object: {[name: string]: Injectable<IControllerConstructor>}): IModule;
/**
* Register a new directive with the compiler.
*
* @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind)
* @param directiveFactory An injectable directive factory function.
*/
directive(name: string, directiveFactory: IDirectiveFactory): IModule;
/**
* Register a new directive with the compiler.
*
* @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind)
* @param directiveFactory An injectable directive factory function.
*/
directive(name: string, inlineAnnotatedFunction: any[]): IModule;
directive(object: Object): IModule;
directive(name: string, directiveFactory: Injectable<IDirectiveFactory>): IModule;
directive(object: {[directiveName: string]: Injectable<IDirectiveFactory>}): IModule;
/**
* Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider.
*
* @param name The name of the instance.
* @param $getFn The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}).
*/
factory(name: string, $getFn: Function): IModule;
/**
* Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider.
*
* @param name The name of the instance.
* @param inlineAnnotatedFunction The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}).
*/
factory(name: string, inlineAnnotatedFunction: any[]): IModule;
factory(object: Object): IModule;
filter(name: string, filterFactoryFunction: Function): IModule;
filter(name: string, inlineAnnotatedFunction: any[]): IModule;
filter(object: Object): IModule;
factory(name: string, $getFn: Injectable<Function>): IModule;
factory(object: {[name: string]: Injectable<Function>}): IModule;
filter(name: string, filterFactoryFunction: Injectable<Function>): IModule;
filter(object: {[name: string]: Injectable<Function>}): IModule;
provider(name: string, serviceProviderFactory: IServiceProviderFactory): IModule;
provider(name: string, serviceProviderConstructor: IServiceProviderClass): IModule;
provider(name: string, inlineAnnotatedConstructor: any[]): IModule;
@@ -265,26 +244,15 @@ declare namespace angular {
/**
* Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
*/
run(initializationFunction: Function): IModule;
/**
* Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
*/
run(inlineAnnotatedFunction: any[]): IModule;
run(initializationFunction: Injectable<Function>): IModule;
/**
* Register a service constructor, which will be invoked with new to create the service instance. This is short for registering a service where its provider's $get property is a factory function that returns an instance instantiated by the injector from the service constructor function.
*
* @param name The name of the instance.
* @param serviceConstructor An injectable class (constructor function) that will be instantiated.
*/
service(name: string, serviceConstructor: Function): IModule;
/**
* Register a service constructor, which will be invoked with new to create the service instance. This is short for registering a service where its provider's $get property is a factory function that returns an instance instantiated by the injector from the service constructor function.
*
* @param name The name of the instance.
* @param inlineAnnotatedConstructor An injectable class (constructor function) that will be instantiated.
*/
service(name: string, inlineAnnotatedConstructor: any[]): IModule;
service(object: Object): IModule;
service(name: string, serviceConstructor: Injectable<Function>): IModule;
service(object: {[name: string]: Injectable<Function>}): IModule;
/**
* Register a value service with the $injector, such as a string, a number, an array, an object or a function. This is short for registering a service where its provider's $get property is a factory function that takes no arguments and returns the value service.
@@ -301,8 +269,7 @@ declare namespace angular {
* @param name The name of the service to decorate
* @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to.
*/
decorator(name:string, decoratorConstructor: Function): IModule;
decorator(name:string, inlineAnnotatedConstructor: any[]): IModule;
decorator(name: string, decorator: Injectable<Function>): IModule;
// Properties
name: string;
@@ -612,11 +579,11 @@ declare namespace angular {
/**
* calling stopPropagation function will cancel further event propagation (available only for events that were $emit-ed).
*/
stopPropagation?: Function;
stopPropagation?(): void;
/**
* calling preventDefault sets defaultPrevented flag to true.
*/
preventDefault: Function;
preventDefault(): void;
/**
* true if preventDefault was called.
*/
@@ -1220,19 +1187,12 @@ declare namespace angular {
// see http://docs.angularjs.org/api/ng.$compileProvider
///////////////////////////////////////////////////////////////////////////
interface ICompileService {
(element: string, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction;
(element: Element, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction;
(element: JQuery, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction;
(element: string | Element | JQuery, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction;
}
interface ICompileProvider extends IServiceProvider {
directive(name: string, directiveFactory: Function): ICompileProvider;
directive(directivesMap: Object, directiveFactory: Function): ICompileProvider;
directive(name: string, inlineAnnotatedFunction: any[]): ICompileProvider;
directive(directivesMap: Object, inlineAnnotatedFunction: any[]): ICompileProvider;
// Undocumented, but it is there...
directive(directivesMap: any): ICompileProvider;
directive(name: string, directiveFactory: Injectable<IDirectiveFactory>): ICompileProvider;
directive(object: {[directiveName: string]: Injectable<IDirectiveFactory>}): ICompileProvider;
component(name: string, options: IComponentOptions): ICompileProvider;
@@ -1242,7 +1202,8 @@ declare namespace angular {
imgSrcSanitizationWhitelist(): RegExp;
imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider;
debugInfoEnabled(enabled?: boolean): any;
debugInfoEnabled(): boolean;
debugInfoEnabled(enabled: boolean): ICompileProvider;
}
interface ICloneAttachFunction {
@@ -1255,12 +1216,16 @@ declare namespace angular {
(scope: IScope, cloneAttachFn?: ICloneAttachFunction): JQuery;
}
// This corresponds to $transclude (and also the transclude function passed to link).
/**
* This corresponds to $transclude passed to controllers and to the transclude function passed to link functions.
* https://docs.angularjs.org/api/ng/service/$compile#-controller-
* http://teropa.info/blog/2015/06/09/transclusion.html
*/
interface ITranscludeFunction {
// If the scope is provided, then the cloneAttachFn must be as well.
(scope: IScope, cloneAttachFn: ICloneAttachFunction): JQuery;
(scope: IScope, cloneAttachFn: ICloneAttachFunction, futureParentElement?: JQuery, slotName?: string): JQuery;
// If one argument is provided, then it's assumed to be the cloneAttachFn.
(cloneAttachFn?: ICloneAttachFunction): JQuery;
(cloneAttachFn?: ICloneAttachFunction, futureParentElement?: JQuery, slotName?: string): JQuery;
}
///////////////////////////////////////////////////////////////////////////
@@ -1411,6 +1376,16 @@ declare namespace angular {
* Absolute or relative URL of the resource that is being requested.
*/
url: string;
/**
* Event listeners to be bound to the XMLHttpRequest object.
* To bind events to the XMLHttpRequest upload object, use uploadEventHandlers. The handler will be called in the context of a $apply block.
*/
eventHandlers?: { [type: string]: EventListenerOrEventListenerObject };
/**
* Event listeners to be bound to the XMLHttpRequest upload object.
* To bind events to the XMLHttpRequest object, use eventHandlers. The handler will be called in the context of a $apply block.
*/
uploadEventHandlers?: { [type: string]: EventListenerOrEventListenerObject };
}
interface IHttpHeadersGetter {
@@ -1538,7 +1513,7 @@ declare namespace angular {
* Register service factories (names or implementations) for interceptors which are called before and after
* each request.
*/
interceptors: (string|IHttpInterceptorFactory|(string|IHttpInterceptorFactory)[])[];
interceptors: (string | Injectable<IHttpInterceptorFactory>)[];
useApplyAsync(): boolean;
useApplyAsync(value: boolean): IHttpProvider;
@@ -1686,11 +1661,10 @@ declare namespace angular {
* controller if passed as a string. Empty function by default.
* Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection)
*/
controller?: string | Function | (string | Function)[] | IComponentController;
controller?: string | Injectable<IControllerConstructor>;
/**
* An identifier name for a reference to the controller. If present, the controller will be published to scope under
* the controllerAs name. If not present, this will default to be the same as the component name.
* @default "$ctrl"
* An identifier name for a reference to the controller. If present, the controller will be published to its scope under
* the specified name. If not present, this will default to '$ctrl'.
*/
controllerAs?: string;
/**
@@ -1701,24 +1675,24 @@ declare namespace angular {
* $attrs - Current attributes object for the element
* Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection)
*/
template?: string | Function | (string | Function)[];
template?: string | Injectable<(...args: any[]) => string>;
/**
* path or function that returns a path to an html template that should be used as the contents of this component.
* Path or function that returns a path to an html template that should be used as the contents of this component.
* If templateUrl is a function, then it is injected with the following locals:
* $element - Current element
* $attrs - Current attributes object for the element
* Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection)
*/
templateUrl?: string | Function | (string | Function)[];
templateUrl?: string | Injectable<(...args: any[]) => string>;
/**
* Define DOM attribute binding to component properties. Component properties are always bound to the component
* controller and not to the scope.
*/
bindings?: {[binding: string]: string};
bindings?: {[boundProperty: string]: string};
/**
* Whether transclusion is enabled. Enabled by default.
* Whether transclusion is enabled. Disabled by default.
*/
transclude?: boolean | string | {[slot: string]: string};
transclude?: boolean | {[slot: string]: string};
/**
* Requires the controllers of other directives and binds them to this component's controller.
* The object keys specify the property names under which the required controllers (object values) will be bound.
@@ -1728,16 +1702,18 @@ declare namespace angular {
require?: {[controller: string]: string};
}
interface IComponentTemplateFn {
( $element?: JQuery, $attrs?: IAttributes ): string;
}
type IControllerConstructor =
(new (...args: any[]) => IController) |
// Instead of classes, plain functions are often used as controller constructors, especially in examples.
((...args: any[]) => (void | IController));
/**
* Components have a well-defined lifecycle Each component can implement "lifecycle hooks". These are methods that
* will be called at certain points in the life of the component.
* @url https://docs.angularjs.org/guide/component
* Directive controllers have a well-defined lifecycle. Each controller can implement "lifecycle hooks". These are methods that
* will be called by Angular at certain points in the life cycle of the directive.
* https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks
* https://docs.angularjs.org/guide/component
*/
interface IComponentController {
interface IController {
/**
* Called on each controller after all the controllers on an element have been constructed and had their bindings
* initialized (and before the pre & post linking functions for the directives on this element). This is a good
@@ -1745,12 +1721,21 @@ declare namespace angular {
*/
$onInit?(): void;
/**
* Called whenever one-way bindings are updated. The changesObj is a hash whose keys are the names of the bound
* properties that have changed, and the values are an {@link IChangesObject} object of the form
* Called on each turn of the digest cycle. Provides an opportunity to detect and act on changes.
* Any actions that you wish to take in response to the changes that you detect must be invoked from this hook;
* implementing this has no effect on when `$onChanges` is called. For example, this hook could be useful if you wish
* to perform a deep equality check, or to check a `Dat`e object, changes to which would not be detected by Angular's
* change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments; if detecting changes,
* you must store the previous value(s) for comparison to the current values.
*/
$doCheck?(): void;
/**
* Called whenever one-way bindings are updated. The onChangesObj is a hash whose keys are the names of the bound
* properties that have changed, and the values are an {@link IChangesObject} object of the form
* { currentValue, previousValue, isFirstChange() }. Use this hook to trigger updates within a component such as
* cloning the bound value to prevent accidental mutation of the outer value.
*/
$onChanges?(changesObj: {[property:string]: IChangesObject}): void;
$onChanges?(onChangesObj: IOnChangesObject): void;
/**
* Called on a controller when its containing scope is destroyed. Use this hook for releasing external resources,
* watches and event handlers.
@@ -1767,9 +1752,13 @@ declare namespace angular {
$postLink?(): void;
}
interface IChangesObject {
currentValue: any;
previousValue: any;
interface IOnChangesObject {
[property: string]: IChangesObject<any>;
}
interface IChangesObject<T> {
currentValue: T;
previousValue: T;
isFirstChange(): boolean;
}
@@ -1809,12 +1798,12 @@ declare namespace angular {
* that is passed to the link function instead.
*/
transclude: ITranscludeFunction
): void | IDirectivePrePost;
): void | IDirectiveLinkFn | IDirectivePrePost;
}
interface IDirective {
compile?: IDirectiveCompileFn;
controller?: any;
controller?: string | Injectable<IControllerConstructor>;
controllerAs?: string;
/**
* @deprecated
@@ -1822,10 +1811,9 @@ declare namespace angular {
* the controller constructor is called, this use is now deprecated. Please place initialization code that
* relies upon bindings inside a $onInit method on the controller, instead.
*/
bindToController?: boolean | Object;
bindToController?: boolean | {[boundProperty: string]: string};
link?: IDirectiveLinkFn | IDirectivePrePost;
multiElement?: boolean;
directiveName?: string;
priority?: number;
/**
* @deprecated
@@ -1833,12 +1821,12 @@ declare namespace angular {
replace?: boolean;
require?: string | string[] | {[controller: string]: string};
restrict?: string;
scope?: boolean | Object;
template?: string | Function;
scope?: boolean | {[boundProperty: string]: string};
template?: string | ((tElement: JQuery, tAttrs: IAttributes) => string);
templateNamespace?: string;
templateUrl?: string | Function;
templateUrl?: string | ((tElement: JQuery, tAttrs: IAttributes) => string);
terminal?: boolean;
transclude?: boolean | string | {[slot: string]: string};
transclude?: boolean | 'element' | {[slot: string]: string};
}
/**
@@ -1851,6 +1839,11 @@ declare namespace angular {
interface IAugmentedJQueryStatic extends JQueryStatic {}
interface IAugmentedJQuery extends JQuery {}
/**
* Same as IController. Keeping it for compatibility with older versions of these type definitions.
*/
interface IComponentController extends IController {}
///////////////////////////////////////////////////////////////////////////
// AUTO module (angular.js)
///////////////////////////////////////////////////////////////////////////
+1
View File
@@ -137,6 +137,7 @@ declare module "apn" {
}
export interface NotificationAlertOptions {
title?:string;
subtitle?:string;
body:string;
"title-loc-key"?:string;
"title-loc-args"?:string[];
+4 -4
View File
@@ -346,24 +346,24 @@ interface Client {
* Log an incoming http request to your server. The request data will be tracked during the response "finish" event if it is successful or the request "error"
* event if it fails. The request duration is automatically calculated as the timespan between when the trackRequest method was called, and when the response "finish"
* or request "error" events were fired.
* @param request The http.ServerRequest object to track
* @param request The http.IncomingMessage object to track
* @param response The http.ServerResponse object for this request
* @param properties map[string, string] - additional data used to filter requests in the portal. Defaults to empty.
*/
trackRequest(request: any /* http.ServerRequest */, response: any /* http.ServerResponse */, properties?: {
trackRequest(request: any /* http.IncomingMessage */, response: any /* http.ServerResponse */, properties?: {
[key: string]: string;
}): void;
/**
* Log an incoming http request to your server. The request data is tracked synchronously rather than waiting for the response "finish"" or request "error"" events.
* Use this if you need your request telemetry to respect custom app insights operation and user context (for example if you set any appInsights.client.context.tags).
* @param request The http.ServerRequest object to track
* @param request The http.IncomingMessage object to track
* @param response The http.ServerResponse object for this request
* @param ellapsedMilliseconds The duration for this request. Defaults to 0.
* @param properties map[string, string] - additional data used to filter requests in the portal. Defaults to empty.
* @param error An error that was returned for this request if it was unsuccessful. Defaults to null.
*/
trackRequestSync(request: any /*http.ServerRequest */, response: any /*http.ServerResponse */, ellapsedMilliseconds?: number, properties?: {
trackRequestSync(request: any /*http.IncomingMessage */, response: any /*http.ServerResponse */, ellapsedMilliseconds?: number, properties?: {
[key: string]: string;}, error?: any) : void;
/**
+435 -45
View File
@@ -1,4 +1,4 @@
// Type definitions for ArcGIS API for JavaScript v3.17
// Type definitions for ArcGIS API for JavaScript v3.18
// Project: http://js.arcgis.com
// Definitions by: Esri <http://www.esri.com>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -44,6 +44,7 @@ declare module "esri" {
import QueryTask = require("esri/tasks/QueryTask");
import TextSymbol = require("esri/symbols/TextSymbol");
import StandardGeographyQueryTask = require("esri/tasks/geoenrichment/StandardGeographyQueryTask");
import WCSConnection = require("esri/layers/WCSConnection");
import WMSLayerInfo = require("esri/layers/WMSLayerInfo");
import WMTSLayerInfo = require("esri/layers/WMTSLayerInfo");
@@ -483,12 +484,14 @@ declare module "esri" {
featureLayers: FeatureLayer[];
/** Reference to the map object. */
map?: Map;
/** The point feature layer containing the origin points. */
originsLayer: FeatureLayer;
/** The point feature layers containing the origin points. */
originsLayers: FeatureLayer[];
/** The name of the output layer to be shown in the Result layer name input box. */
outputLayerName?: string;
/** The url to the ArcGIS.com site or in-house portal where the GP server is hosted. */
portalUrl?: string;
/** Indicates whether to display a drop down menu listing valid input analysis layers. */
showSelectAnalysisLayer?: boolean;
}
export interface CoordinatesLocationProviderOptions {
/** The attribute field in the graphic object that contains the longitude (X) values. */
@@ -563,12 +566,14 @@ declare module "esri" {
export interface CreateWatershedsOptions {
/** The URL to the GPServer used to execute an analysis job. */
analysisGpServer?: string;
/** The feature layer containing input points used for calculating watersheds. */
inputLayer: FeatureLayer;
/** The feature layers containing input points used for calculating watersheds. */
inputLayers: FeatureLayer[];
/** Reference to the map object. */
map?: Map;
/** The url to the ArcGIS.com site or in-house portal where the GP server is hosted. */
portalUrl?: string;
/** Indicates whether to display a drop down menu listing valid input analysis layers. */
showSelectAnalysisLayer?: boolean;
}
export interface CutOptions {
/** The feature(s) added to the feature layer by the cut operation. */
@@ -939,6 +944,10 @@ declare module "esri" {
outFields?: string[];
/** Displays or hides the attachment column. */
showAttachments?: boolean;
/** Displays or hides tooltips for column headers. */
showColumnHeaderTooltips?: boolean;
/** Shows or hides cyclical relationship. */
showCyclicalRelationships?: boolean;
/** Displays the data type of the field right under the field label. */
showDataTypes?: boolean;
/** Displays or hides total number of features and selected number of features in the grid header. */
@@ -947,6 +956,8 @@ declare module "esri" {
showGridHeader?: boolean;
/** Displays or hides 'Options' drop-down menu of the FeatureTable. */
showGridMenu?: boolean;
/** Displays or hides the option to show related records in a table if the layer has pre-established relationship. */
showRelatedRecords?: boolean;
/** Displays or hides the 'Statistics' option in column menus for numeric fields. */
showStatistics?: boolean;
/** Enables an interaction between the map and the feature table. */
@@ -1996,6 +2007,30 @@ declare module "esri" {
/** The URL to use for connecting to a socket. */
socketUrl?: string;
}
export interface StretchFilterOptions {
/** Indicates whether to perform dynamic range adjustment using the current pixel data. */
dra?: boolean;
/** An array of gamma values, for example [0.8, 0.8, 0.8]. */
gamma?: number[];
/** The maximum value of stretched pixels. */
max?: number;
/** Percent of pixels clipped on the right histogram tail, for example 0.25. */
maxPercent?: number;
/** The minimum value of stretched pixels. */
min?: number;
/** Percent of pixels clipped on the left histogram tail, for example 1.5. */
minPercent?: number;
/** The number of standard deviations for StandardDeviation stretch, for example 2.5. */
numberOfStandardDeviations?: number;
/** The output pixel type. */
outputPixelType?: string;
/** An array of arrays containing custom statistics objects. */
statistics?: any[][];
/** See the constants table for a list of possible stretchType values. */
stretchType?: number;
/** Indicates whether to perform non-linear gamma stretch. */
useGamma?: boolean;
}
export interface SummarizeNearbyOptions {
/** The URL to the GPServer used to execute an analysis job. */
analysisGpServer?: string;
@@ -2023,6 +2058,8 @@ declare module "esri" {
showCredits?: boolean;
/** When true, the help links will be shown. */
showHelp?: boolean;
/** Indicates whether to display a drop down menu listing valid input analysis layers. */
showSelectAnalysisLayer?: boolean;
/** When true, the select folder dropdown will be shown. */
showSelectFolder?: boolean;
/** An array of possible statistics attribute field names and summary types that you wish to calculate for all nearby features. */
@@ -2031,8 +2068,8 @@ declare module "esri" {
summaryLayer?: FeatureLayer;
/** An array of possible feature layers summarizing toward. */
summaryLayers: FeatureLayer[];
/** The point, line, or polygon feature layer from which distances will be measured to features in summarizeLayer. */
sumNearbyLayer: FeatureLayer;
/** The point, line, or polygon feature layers from which distances will be measured to features in summarizeLayer. */
sumNearbyLayers: FeatureLayer[];
/** If true. */
sumShape?: boolean;
/** Type of units shown as the defeault value in the Find nearest features using a option. */
@@ -2184,27 +2221,37 @@ declare module "esri" {
/** Region of preview scale thumbnails. */
region?: string;
}
export interface WCSConnectionOptions {
/** The coverage identifier, defaults to the first coverage. */
coverageId?: string;
/** The version of WCSLayer, can be: 1.0.01.1.01.1.11.1.22.0.1 */
version?: string;
}
export interface WCSLayerOptions {
/** The coverage identifier, defaults to the first coverage. */
coverageId?: string;
/** Sets the layer's draw mode. */
drawMode?: boolean;
/** Sets the context of the Canvas. */
drawType?: string;
/** A function that takes a pixelData object as input and processes it. */
pixelFilter?: Function;
/** The version of WCSLayer, can be: 1.0.01.1.01.1.11.1.22.0.1 */
version?: string;
/** A WCS Connection object. */
wcsConnection?: WCSConnection;
}
export interface WFSLayerOptions {
/** Full WFS body request sent to WFS server via POST method. */
getFeatureRequest?: string;
/** URL used when executing getFeature request. */
getFeatureUrl?: string;
/** Use this to append custom parameters to WFS requests. */
customParameters?: any;
/** The template that defines the content to display in the map info window when the user clicks on a feature. */
infoTemplate?: InfoTemplate;
/** For "ondemand" mode only. */
inverseFilter?: boolean;
/** When true, the XY coordinates should be swapped (this is required for some WFS vendors, versions, and WKIDS). */
inverseResponse?: boolean;
/** Specifies the maximum number of features to return in one response. */
maxFeatures?: number;
/** The query mode for the WFS layer. */
mode?: string;
/** For "ondemand" mode only. */
nsGeometryFieldName?: string;
/** The full layer name including the namespace as a prefix. */
nsLayerName?: string;
/** When true, more details will be printed to console when the first connection to a WFS server is established. */
showDetails?: boolean;
/** The simple layer name (excluding the namespace). */
name?: string;
/** URL to the WFS server. */
url: string;
/** OGC WFS version number. */
@@ -2235,6 +2282,10 @@ declare module "esri" {
title?: string;
}
export interface WMSLayerOptions {
/** The customLayerParameters object used for the WMS Layer. */
customLayerParameters?: any;
/** The customParameters object used for the WMS Layer. */
customParameters?: any;
/** Specify the map image format, valid options are png,jpg,bmp,gif,svg. */
format?: string;
/** An optional resourceInfo object. */
@@ -2267,6 +2318,10 @@ declare module "esri" {
title?: string;
}
export interface WMTSLayerOptions {
/** The customLayerParameters object used for the WMTS Layer. */
customLayerParameters?: any;
/** The customParameters object used for the WMTS Layer. */
customParameters?: any;
/** A WMTSLayerInfo object that when ResourceInfo options are not specified the map will display the first layer in the WMTS capabilities that matches the properties specified by WMTSLayerInfo. */
layerInfo?: WMTSLayerInfo;
/** When true, tile resampling is enabled. */
@@ -2783,7 +2838,7 @@ declare module "esri/TimeExtent" {
* Returns a new time extent indicating the intersection between "this" and the argument time extent.
* @param timeExtent The input time extent.
*/
intersection(timeExtent: number): TimeExtent;
intersection(timeExtent: TimeExtent): TimeExtent;
/**
* Returns a new time extent with the given offset from "this' time extent.
* @param offsetValue The length of time to offset from "this" time extent.
@@ -2946,7 +3001,7 @@ declare module "esri/arcgis/Portal" {
/** The prefix selected by the organization's administrator to be used with the customBaseURL. */
urlKey: string;
/** User information for the accessing user is returned only when a token is passed in. */
user: any;
user: PortalUser;
/** If true, only simple where clauses that are complaint with SQL92 can be used when querying layers and tables. */
useStandardizedQuery: boolean;
/**
@@ -3951,6 +4006,8 @@ declare module "esri/dijit/ElevationProfile" {
startup(): void;
/** Fires when the elevation profile is cleared. */
on(type: "clear-profile", listener: (event: { target: ElevationProfile }) => void): esri.Handle;
/** Fires after the profile is generated. */
on(type: "elevation-values", listener: (event: { data: any; target: ElevationProfile }) => void): esri.Handle;
/** Fires when the widget has fully loaded. */
on(type: "load", listener: (event: { target: ElevationProfile }) => void): esri.Handle;
/** Fires when the title of the elevation profile is changed */
@@ -3967,6 +4024,7 @@ declare module "esri/dijit/FeatureTable" {
import FeatureLayer = require("esri/layers/FeatureLayer");
import Map = require("esri/map");
import FeatureEditResult = require("esri/layers/FeatureEditResult");
import Graphic = require("esri/graphic");
/** Creates an instance of the FeatureTable widget within the provided DOM node. */
class FeatureTable {
@@ -4012,6 +4070,10 @@ declare module "esri/dijit/FeatureTable" {
selectedRows: any[];
/** Displays or hides the attachment column. */
showAttachments: boolean;
/** Displays or hides tooltips for column headers. */
showColumnHeaderTooltips: boolean;
/** Relies on showRelatedRecords property. */
showCyclicalRelationships: boolean;
/** Displays or hides the data type of the field right under the field label in the column header. */
showDataTypes: boolean;
/** Displays or hides total number of features and selected number of features in the grid header. */
@@ -4020,6 +4082,8 @@ declare module "esri/dijit/FeatureTable" {
showGridHeader: boolean;
/** Displays or hides 'Options' drop-down menu of the FeatureTable. */
showGridMenu: boolean;
/** Displays or hides the option to show related records in a table if the layer has pre-established relationship. */
showRelatedRecords: boolean;
/** Displays or hides the 'Statistics' option in column menus for numeric fields. */
showStatistics: boolean;
/** Enables an interaction between the map and the feature table. */
@@ -4032,35 +4096,55 @@ declare module "esri/dijit/FeatureTable" {
* @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into.
*/
constructor(params: esri.FeatureTableOptions, srcNodeRef: Node | string);
/** Removes all current selections including subsets from filterSelectedRecords(). */
/** Centers the map on combined extent of selected rows. */
centerOnSelection(): void;
/** Removes all filters and selections in the table. */
clearFilter(): void;
/** Removes all selections. */
clearSelection(): void;
/** Destroys the FeatureTable widget. */
destroy(): void;
/**
* Allows users to see the sub-set of currently selected records (uses dGrid.query).
* @param toggle When true only a subset of currently selected features will be displayed in the FeatureTable.
* Filters the table based on the provided row ids.
* @param ids Array of row ids.
*/
filterSelectedRecords(toggle: boolean): void;
filterRecordsByIds(ids: number[]): void;
/** Allows users to see the sub-set of records. */
filterSelectedRecords(): void;
/**
* Queries and gets selected features from the FeatureLayer instead of the store.
* @param id Array of row ids
* @param id Row id or an array of row ids
*/
getFeatureDataById(id: number[]): any;
getFeatureDataById(id: number | number[]): any;
/**
* Gets row object by the row ID.
* @param id row ID
*/
getRowDataById(id: number): any;
/** Refreshes the data in the grid. */
/** Refreshes the data in the table. */
refresh(): void;
/** Resizes the grid's container. */
resize(): void;
/**
* Allows users to select rows(s) based on row id(s).
* @param ids Row id or an array of row ids
* @param scrollToRow Indicates whether the table should scroll to selected rows.
*/
selectRows(ids: number | number[], scrollToRow?: boolean): void;
/**
* Sorts a given field in ascending or descending order.
* @param field Name of the field
* @param descending Defines whether the specified field will be sorted in ascending or descending order.
*/
sort(field: string, descending?: boolean): void;
/** Finalizes the creation of the widget. */
startup(): void;
/** This event fires in response to clearSelection() method. */
on(type: "clear-selection", listener: (event: { target: FeatureTable }) => void): esri.Handle;
/** Fires when the grid column is resized. */
on(type: "column-resize", listener: (event: { target: FeatureTable }) => void): esri.Handle;
on(type: "column-resize", listener: (event: { resizeEvent: any; target: FeatureTable }) => void): esri.Handle;
/** Fires when a column is hidden or shown via 'Options' drop-down menu. */
on(type: "column-state-change", listener: (event: { target: FeatureTable }) => void): esri.Handle;
on(type: "column-state-change", listener: (event: { stateChangeEvent: any; target: FeatureTable }) => void): esri.Handle;
/** Fires when grid editor field loses focus after being changed. */
on(type: "data-change", listener: (event: { target: FeatureTable }) => void): esri.Handle;
/** Fires when grid editor is hidden. */
@@ -4072,19 +4156,23 @@ declare module "esri/dijit/FeatureTable" {
/** Fires when an error occurs in the grid. */
on(type: "error", listener: (event: { target: FeatureTable }) => void): esri.Handle;
/** Fires when grid is filtered. */
on(type: "filter", listener: (event: { target: FeatureTable }) => void): esri.Handle;
on(type: "filter", listener: (event: { ids: number[]; target: FeatureTable }) => void): esri.Handle;
/** Fires when the FeatureTable is loaded. */
on(type: "load", listener: (event: { target: FeatureTable }) => void): esri.Handle;
/** Fires when the grid is refreshed. */
on(type: "refresh", listener: (event: { target: FeatureTable }) => void): esri.Handle;
/** Fires when a row is deselected. */
on(type: "row-deselect", listener: (event: { target: FeatureTable }) => void): esri.Handle;
on(type: "row-deselect", listener: (event: { event: any; target: FeatureTable }) => void): esri.Handle;
/** Fires when a row is selected. */
on(type: "row-select", listener: (event: { target: FeatureTable }) => void): esri.Handle;
on(type: "row-select", listener: (event: { event: any; target: FeatureTable }) => void): esri.Handle;
/** Fires when attachment is displayed in the table. */
on(type: "show-attachments", listener: (event: { attachments: any; dialog: any; featureId: number; target: FeatureTable }) => void): esri.Handle;
/** Fires when related records are displayed in the table. */
on(type: "show-related-records", listener: (event: { features: Graphic[]; relationship: any; row: any; target: FeatureTable }) => void): esri.Handle;
/** Fires when the statistics dialog box shows the calculated statistics on a column with numeric data. */
on(type: "show-statistics", listener: (event: { statistics: any; target: FeatureTable }) => void): esri.Handle;
/** Fires when a column is sorted. */
on(type: "sort", listener: (event: { target: FeatureTable }) => void): esri.Handle;
on(type: "sort", listener: (event: { sortEvent: any; target: FeatureTable }) => void): esri.Handle;
on(type: string, listener: (event: any) => void): esri.Handle;
}
export = FeatureTable;
@@ -4168,7 +4256,7 @@ declare module "esri/dijit/Geocoder" {
import GraphicsLayer = require("esri/layers/GraphicsLayer");
import Symbol = require("esri/symbols/Symbol");
/** Starting with version 3.13, the Search Widget supersedes the Geocoder Widget and is deprecated. */
/** The Geocoder widget was deprecated in version 3.13 and replaced by the Search widget. */
class Geocoder {
/** Currently selected locator object. */
activeGeocoder: any;
@@ -9403,6 +9491,8 @@ declare module "esri/layers/FeatureLayer" {
labelingInfo: LabelClass[];
/** Unique ID of the layer that the FeatureLayer was constructed against. */
layerId: number;
/** The maximum allowable offset, only applicable for layers that are not editable. */
maxAllowableOffset: number;
/** The maximum number of results that will be returned from a query. */
maxRecordCount: number;
/** Maximum visible scale for the layer. */
@@ -10914,7 +11004,7 @@ declare module "esri/layers/VectorTileLayer" {
import SpatialReference = require("esri/SpatialReference");
import TileInfo = require("esri/layers/TileInfo");
/** A VectorTileLayer accesses cached tiles of data and renders it in vector format. */
/** A VectorTileLayer renders cached tiles of data. */
class VectorTileLayer extends Layer {
/** The full extent of the layer. */
fullExtent: Extent;
@@ -10946,6 +11036,224 @@ declare module "esri/layers/VectorTileLayer" {
export = VectorTileLayer;
}
declare module "esri/layers/WCSConnection" {
import esri = require("esri");
import WCSCoverageDescription = require("esri/layers/WCSCoverageDescription");
import DimensionalDefinition = require("esri/layers/DimensionalDefinition");
/** (Currently in beta), a helper class to discover available coverages in an OGC Web Coverage Service. */
class WCSConnection {
/** Resamples pixel by bilinear interpolation. */
static INTERPOLATION_BILINEAR: any;
/** Resamples pixel by cubic convolution. */
static INTERPOLATION_CUBICCONVOLUTION: any;
/** Resamples pixel by nearest neighbor. */
static INTERPOLATION_NEARESTNEIGHBOR: any;
/** An array of coverages offered by the WCS server. */
coverages: WCSCoverageDescription[];
/** Multiple dimensional definitions are usually used to filter data. */
multidimensionalDefinition: DimensionalDefinition[];
/** The name of the WCS server. */
name: string;
/** Key-value pairs for URLs of different WCS operations: GetCapabilitiesDescribeCoverage */
onlineResources: any;
/** An array of string values indicating WCS 2.0.1 profiles. */
profiles: string[];
/** An array of supported formats by the server. */
supportedFormats: string[];
/** The interpolation method affects how the raster dataset is transformed when it undergoes warping or when it changes coordinate space. */
supportedInterpolations: number[];
/** An array of supported WCS versions by the server. */
supportedVersions: string[];
/** URL to a WCS Server endpoint. */
url: string;
/** The version of WCSLayer, can be: 1.0.01.1.01.1.11.1.22.0.1 */
version: string;
/**
* Creates a new WCSConnection.
* @param url URL to a WCS Server endpoint.
* @param options Optional parameters.
*/
constructor(url: string, options?: esri.WCSConnectionOptions);
/** Triggered when successfully retrieved list of coverages. */
on(type: "onConnected", listener: (event: { target: WCSConnection }) => void): esri.Handle;
/** Triggered when an error occurred. */
on(type: "onConnectionFailed", listener: (event: { error: Error; target: WCSConnection }) => void): esri.Handle;
on(type: string, listener: (event: any) => void): esri.Handle;
}
export = WCSConnection;
}
declare module "esri/layers/WCSCoverageDescription" {
import Extent = require("esri/geometry/Extent");
import Point = require("esri/geometry/Point");
import TimeInfo = require("esri/layers/TimeInfo");
/** (Currently in beta), the WCSCoverageDescription models the coverage properties offered by the WCS Server. */
class WCSCoverageDescription {
/** Resamples pixel by bilinear interpolation. */
static INTERPOLATION_BILINEAR: any;
/** Resamples pixel by cubic convolution. */
static INTERPOLATION_CUBICCONVOLUTION: any;
/** Resamples pixel by nearest neighbor. */
static INTERPOLATION_NEARESTNEIGHBOR: any;
/** An array of band names. */
bandInfo: string[];
/** Number of columns at the source resolution. */
columns: number;
/** The coverage description text. */
description: string;
/** Coverage extent in the native spatial reference. */
extent: Extent;
/** The coverage id. */
id: string;
/** Coverage extent in WGS84. */
lonLatEnvelope: Extent;
/** A parsed multidimensional object that describes variables and dimensions. */
multiDimensionalInfo: any;
/** A parsed coverage description object in a structure similar to WCS Coverage Description schema. */
nativeCoverageDescription: any;
/** Coverage's source resolution. */
resolution: Point;
/** Number of rows at the source resolution. */
rows: number;
/** Generalized from the following properties:SupportedFormats for WCS 1.0.0 and 1.1.xserviceParameters.supportedFormats for WCS 2.0.1. */
supportedFormats: string[];
/** The interpolation method affects how the raster dataset is transformed when it undergoes warping or when it changes coordinate space. */
supportedInterpolations: number[];
/** Temporal information for the layer, such as time extent. */
timeInfo: TimeInfo;
/** The current version of the coverage. */
version: string;
/**
* Creates a new WCSCoverageDescription.
* @param coverageDocument The coverage description XML.
* @param version The version of the coverage description document.
*/
constructor(coverageDocument: string, version: string);
}
export = WCSCoverageDescription;
}
declare module "esri/layers/WCSLayer" {
import esri = require("esri");
import WCSCoverageDescription = require("esri/layers/WCSCoverageDescription");
import Extent = require("esri/geometry/Extent");
import DimensionalDefinition = require("esri/layers/DimensionalDefinition");
import TimeInfo = require("esri/layers/TimeInfo");
import WCSConnection = require("esri/layers/WCSConnection");
import Point = require("esri/geometry/Point");
import Layer = require("esri/layers/layer");
/** (Currently in beta) The WCSLayer works with OGC Web Coverage Services. */
class WCSLayer {
/** Resamples pixel by bilinear interpolation. */
static INTERPOLATION_BILINEAR: any;
/** Resamples pixel by cubic convolution. */
static INTERPOLATION_CUBICCONVOLUTION: any;
/** Resamples pixel by nearest neighbor. */
static INTERPOLATION_NEARESTNEIGHBOR: any;
/** Zero-based array of current band selections. */
bandIds: number[];
/** A reference to a WCSCoverageDescription object. */
coverageDescription: WCSCoverageDescription;
/** The coverage identifier, defaults to the first coverage. */
coverageId: string;
/** The extent of the full coverage. */
extent: Extent;
/** Raster format of the layer. */
format: string;
/** Current interpolation method. */
interpolation: number;
/** When the layer is loaded, the value becomes "true", and layer properties can be accessed. */
loaded: boolean;
/** Multiple dimensional definitions are usually used to filter data. */
multidimensionalDefinition: DimensionalDefinition[];
/** Opacity or transparency of layer. */
opacity: number;
/** A function that takes a pixelData object as input and processes it. */
pixelFilter: Function;
/** The pixel type of the image service. */
pixelType: string;
/** The projected extent in the map's spatial reference. */
projectedFullExtent: Extent;
/** When true, the layer is suspended. */
suspended: boolean;
/** Temporal information for the layer, such as time extent. */
timeInfo: TimeInfo;
/** URL to a WCS Server endpoint. */
url: string;
/** The version of WCSLayer, can be: 1.0.01.1.01.1.11.1.22.0.1 */
version: string;
/** The visibility of the layer. */
visible: boolean;
/** A WCS Connection object. */
wcsConnection: WCSConnection;
/**
* Creates a new WCSLayer.
* @param url URL to a WCS Server endpoint.
* @param options Optional parameters.
*/
constructor(url: string, options?: esri.WCSLayerOptions);
/** Returns the context of the Canvas. */
getContext(): any;
/**
* Returns an array of graphics as a Promise.
* @param mapPoint The map point location in which to identify.
*/
identify(mapPoint: Point): any;
/** Resumes layer drawing. */
resume(): void;
/**
* Sets the opacity of the layer.
* @param opacity Value from 0 to 1, where 0 is 100% transparent and 1 has no transparency.
*/
setOpacity(opacity: number): void;
/**
* Sets a pixelFilter on the layer.
* @param pixelFilter The function defining the PixelFilter to set on the layer.
* @param doNotRefresh When true the layer will not refresh the map image.
*/
setPixelFilter(pixelFilter: Function, doNotRefresh?: boolean): void;
/**
* Determines if the layer will update its content based on the map's current time extent.
* @param use Use true to update the layer's content based on the map's current time extent.
*/
setUseMapTime(use: boolean): void;
/**
* Sets the visibility of the layer.
* @param isVisible Indicate whether to set layer visibility.
*/
setVisibility(isVisible: boolean): void;
/** Suspends layer drawing. */
suspend(): void;
/** Fires when there is a problem retrieving a layer. */
on(type: "error", listener: (event: { error: Error; target: WCSLayer }) => void): esri.Handle;
/** Fires after layer properties for the layer are successfully populated. */
on(type: "load", listener: (event: { layer: Layer; target: WCSLayer }) => void): esri.Handle;
/** Fires when the layer opacity has been changed, and returns an object with the opacity value. */
on(type: "opacity-change", listener: (event: { opacity: number; target: WCSLayer }) => void): esri.Handle;
/** This event is fired when the layer's refreshInterval is modified. */
on(type: "refresh-interval-change", listener: (event: { target: WCSLayer }) => void): esri.Handle;
/** Fires when a layer resumes drawing. */
on(type: "resume", listener: (event: { target: WCSLayer }) => void): esri.Handle;
/** Fires when a layer's minScale and/or maxScale is changed. */
on(type: "scale-range-change", listener: (event: { target: WCSLayer }) => void): esri.Handle;
/** Fires when a layer's scale visibility changes. */
on(type: "scale-visibility-change", listener: (event: { target: WCSLayer }) => void): esri.Handle;
/** Fires when a layer suspends drawing */
on(type: "suspend", listener: (event: { target: WCSLayer }) => void): esri.Handle;
/** Fires when a layer has finished updating its content. */
on(type: "update-end", listener: (event: { error: Error; target: WCSLayer }) => void): esri.Handle;
/** Fires when a layer begins to update its content. */
on(type: "update-start", listener: (event: { target: WCSLayer }) => void): esri.Handle;
/** Fires when the layer visibility has been changed, and returns an object with a Boolean visible property containing the new visibility value of the layer. */
on(type: "visibility-change", listener: (event: { visible: boolean; target: WCSLayer }) => void): esri.Handle;
on(type: string, listener: (event: any) => void): esri.Handle;
}
export = WCSLayer;
}
declare module "esri/layers/WFSLayer" {
import esri = require("esri");
import GraphicsLayer = require("esri/layers/GraphicsLayer");
@@ -10957,6 +11265,8 @@ declare module "esri/layers/WFSLayer" {
/** (Currently in beta) A layer for OGC Web Feature Services (WFS). */
class WFSLayer extends GraphicsLayer {
/** Use this to append custom parameters to WFS requests. */
customParameters: any;
/** An array of fields in the layer. */
fields: Field[];
/** The full extent of the layer. */
@@ -10987,6 +11297,11 @@ declare module "esri/layers/WFSLayer" {
redraw(): void;
/** Refreshes the features in the WFS layer. */
refresh(): void;
/**
* Sets the custom parameters used on the WFS layer.
* @param customParameters The customParameters object used append WFS requests.
*/
setCustomParameters(customParameters: any): void;
/** Sets the default line symbol to be used if no renderer is specified. */
setLineSymbol(): void;
/** Sets the default point symbol to be used if no renderer is specified. */
@@ -11012,12 +11327,20 @@ declare module "esri/layers/WMSLayer" {
allExtents: Extent[];
/** Copyright of the WMS service. */
copyright: string;
/** Use this to append different custom parameters to WMS layer requests. */
customLayerParameters: any;
/** Use this to append custom parameters to all WMS requests. */
customParameters: any;
/** Description of the WMS service. */
description: string;
/** Extent of the WMS service. */
extent: Extent;
/** Feature info MIME type to request. */
featureInfoFormat: string;
/** The URL for the WMS GetFeatureInfo call. */
getFeatureInfoURL: string;
/** The URL for the WMS GetMap call. */
getMapUrl: string;
getMapURL: string;
/** The map image format. */
imageFormat: string;
/** List of layers in the WMS service. */
@@ -11034,12 +11357,22 @@ declare module "esri/layers/WMSLayer" {
title: string;
/** Version of the WMS service. */
version: string;
/** A list of layer names that represent the layers to include in the exported map. */
visibleLayers: string[];
/**
* Creates a new WMSLayer object.
* @param url URL to the OGC Web Map Service.
* @param options Optional parameters.
*/
constructor(url: string, options?: esri.WMSLayerOptions);
/** Returns the current map image format. */
getImageFormat(): string;
/**
* Sets the custom parameters used on the WMS layer.
* @param customParameters The customParameters object used append WMS requests.
* @param customLayerParameters The customLayerParameters object used append specific WMS layer requests.
*/
setCustomParameters(customParameters: any, customLayerParameters?: any): void;
/**
* Set the map image format; valid values are "png", "jpg", "pdf", "bmp", "gif" and "svg".
* @param format The image format.
@@ -11106,6 +11439,10 @@ declare module "esri/layers/WMTSLayer" {
class WMTSLayer extends TiledMapServiceLayer {
/** Copyright information for the service. */
copyright: string;
/** Use this to append different custom parameters to a WMTS tile request. */
customLayerParameters: any;
/** Use this to append custom parameters to all WMTS requests. */
customParameters: any;
/** The description of the active layer if specified in the capabilties file or the resource info. */
description: string;
/** The tile format. */
@@ -11137,6 +11474,12 @@ declare module "esri/layers/WMTSLayer" {
* @param WMTSLayerInfo The WMTSLayerInfo for the layer to make active.
*/
setActiveLayer(WMTSLayerInfo: WMTSLayerInfo): void;
/**
* Sets the custom parameters used on the WMTS layer.
* @param customParameters The customParameters object used append WMTS requests.
* @param customLayerParameters The customLayerParameters object used append specific WMTS layer requests.
*/
setCustomParameters(customParameters: any, customLayerParameters?: any): void;
}
export = WMTSLayer;
}
@@ -11315,6 +11658,47 @@ declare module "esri/layers/layer" {
export = Layer;
}
declare module "esri/layers/pixelfilters/StretchFilter" {
import esri = require("esri");
/** A stretch filter used to work with client -side pixel data to enhance raster/image appearances. */
class StretchFilter {
/** Indicates whether to perform dynamic range adjustment using the current pixel data. */
dra: boolean;
/** An array of gamma values, for example [0.8, 0.8, 0.8]. */
gamma: number[];
/** The maximum value of stretched pixels. */
max: number;
/** Percent of pixels clipped on the right histogram tail, for example 0.25. */
maxPercent: number;
/** The minimum value of stretched pixels. */
min: number;
/** Percent of pixels clipped on the left histogram tail, for example 1.5. */
minPercent: number;
/** The number of standard deviations for StandardDeviation stretch, for example 2.5. */
numberOfStandardDeviations: number;
/** The output pixel type. */
outputPixelType: string;
/** An array of arrays containing custom statistics objects. */
statistics: any[][];
/** Number indicating the various stretch types. */
stretchType: number;
/** Indicates whether to perform non-linear gamma stretch. */
useGamma: boolean;
/**
* Creates an instance of a StretchFilter.
* @param options Optional parameters.
*/
constructor(options?: esri.StretchFilterOptions);
/**
* It takes a pixelData object as input and processes it.
* @param pixelData The pixelData object used as filter input.
*/
filter(pixelData: any): void;
}
export = StretchFilter;
}
declare module "esri/map" {
import esri = require("esri");
import Attribution = require("esri/dijit/Attribution");
@@ -11779,8 +12163,8 @@ declare module "esri/opsdashboard/ExtensionBase" {
static POLYLINE: any;
/** Read-only: Indicates if the host application is the Windows Operations Dashboard. */
isNative: boolean;
/** Read Only: It will list all of the Portal helper services. */
portalHelperServices: string;
/** Read-only: It will list all of the Portal helper services. */
portalHelperServices: any;
/** Read-only: The URL to the ArcGIS.com site or in-house portal that you are currently signed in to. */
portalUrl: string;
/** Get the collection of data sources from the host application. */
@@ -11838,8 +12222,11 @@ declare module "esri/opsdashboard/ExtensionConfigurationBase" {
class ExtensionConfigurationBase extends ExtensionBase {
/** The object that will store the Widget/MapTool/FeatureAction configuration. */
config: any;
/** Indicates that the configuration is ready to be persisted or not. */
readyToPersistConfig: boolean;
/**
* Indicates if the configuration is ready to be persisted or not.
* @param ready Indicates that the configuration is ready to be persisted or not.
*/
readyToPersistConfig(ready: boolean): void;
}
export = ExtensionConfigurationBase;
}
@@ -14127,6 +14514,8 @@ declare module "esri/tasks/FeatureSet" {
features: Graphic[];
/** Set of name-value pairs for the attribute's field and alias names. */
fieldAliases: any;
/** The array of fields. */
fields: any[];
/** The geometry type of the FeatureSet. */
geometryType: string;
/** When a FeatureSet is used as input to Geoprocessor, the spatial reference is set to the map's spatial reference by default. */
@@ -14379,7 +14768,7 @@ declare module "esri/tasks/GeometryService" {
url: string;
/**
* Creates a new GeometryService object.
* @param url URL to the ArcGIS Server REST resource that represents a GeometryService, e.g., http://sampleserver6.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer.
* @param url URL to the ArcGIS Server REST resource that represents a GeometryService, https://utility.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer.
*/
constructor(url: string);
/**
@@ -15165,6 +15554,7 @@ declare module "esri/tasks/PrintParameters" {
declare module "esri/tasks/PrintTask" {
import esri = require("esri");
import PrintParameters = require("esri/tasks/PrintParameters");
import DataFile = require("esri/tasks/DataFile");
/** The PrintTask class generates a printer-ready version of the map using an Export Web Map Task available with ArGIS Server 10.1 and later. */
class PrintTask {
@@ -15184,7 +15574,7 @@ declare module "esri/tasks/PrintTask" {
*/
execute(printParameters: PrintParameters, callback?: Function, errback?: Function): any;
/** Fired when the print operation is complete. */
on(type: "complete", listener: (event: { url: string; target: PrintTask }) => void): esri.Handle;
on(type: "complete", listener: (event: { result: DataFile; target: PrintTask }) => void): esri.Handle;
/** Fired when an error occurs while executing the print task. */
on(type: "error", listener: (event: { error: Error; target: PrintTask }) => void): esri.Handle;
on(type: string, listener: (event: any) => void): esri.Handle;
+6
View File
@@ -946,9 +946,14 @@ declare namespace AtomCore {
registry: any;
repository: Object;
scopeName: string;
tokenizeLines: (text: string) => any;
// TBD
}
interface IGrammars {
grammarForScopeName(scope: string): IGrammar;
}
interface IPane /* extends Theorist.Model */ {
itemForURI: (uri:string)=>IEditor;
@@ -1302,6 +1307,7 @@ declare namespace AtomCore {
deserializers:IDeserializerManager;
config: IConfig;
commands: ICommandRegistry;
grammars: IGrammars;
keymaps: IKeymapManager;
keymap: IKeymapManager;
packages: IPackageManager;
+2 -1
View File
@@ -42,6 +42,7 @@ interface Auth0ClientOptions {
/** Represents a normalized UserProfile. */
interface Auth0UserProfile {
email: string;
email_verified: boolean;
family_name: string;
gender: string;
given_name: string;
@@ -127,6 +128,6 @@ interface Auth0DelegationToken {
declare var Auth0: Auth0Static;
declare module "auth0" {
declare module "auth0-js" {
export = Auth0
}
+1 -1
View File
@@ -92,7 +92,7 @@ interface Auth0LockConstructorOptions {
initialScreen?: "login" | "signUp" | "forgotPassword";
language?: string;
languageDictionary?: any;
loginAfterSignup?: boolean;
loginAfterSignUp?: boolean;
mustAcceptTerms?: boolean;
popupOptions?: Auth0LockPopupOptions;
prefill?: { email?: string, username?: string};
+1 -1
View File
@@ -211,7 +211,7 @@ declare namespace autobahn {
retry_delay_jitter?: number;
url?: string;
protocols?: string[];
onchallenge?: (session: Session, method: string, extra: any) => OnChallengeHandler;
onchallenge?: OnChallengeHandler;
realm?: string;
authmethods?: string[];
authid?: string;
@@ -0,0 +1,43 @@
/// <reference path="autobind-decorator.d.ts" />
import autobind = require('autobind-decorator');
class Test {
public static what: string = 'static';
@autobind
public static test(): void {
console.log(this.what);
}
public constructor(public what: string) {
this.what = what;
}
@autobind
public test(): void {
console.warn(this.what);
}
}
const tester: Test = new Test('bind');
const { test } = tester;
tester.test(); // warns 'bind'.
test(); // warns 'bind'.
Test.test(); // logs 'static'.
@autobind
class Component {
public constructor(private someMember: string) {
this.someMember = someMember;
}
public someMethod(): void {
console.error(this.someMember);
}
}
const component: Component = new Component('React vs Angular2');
const { someMethod } = component;
component.someMethod(); // errors 'React vs Angular2'
someMethod(); // errors 'React vs Angular2'
+10
View File
@@ -0,0 +1,10 @@
// Type definitions for autobind-decorator v1.3.3
// Project: https://github.com/andreypopp/autobind-decorator
// Definitions by: Ivo Stratev <https://github.com/NoHomey/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'autobind-decorator' {
function autobind<TFunction extends Function>(target: TFunction): TFunction | void;
function autobind<T extends Function>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T> | void;
export = autobind;
}
@@ -0,0 +1 @@
--experimentalDecorators
+27 -36
View File
@@ -4,46 +4,37 @@ import lambda = require('aws-lambda');
var str: string;
var date: Date;
var sns: lambda.SNS;
var kinesis: lambda.Kinesis;
var recordsList: lambda.Record[];
var anyObj: any;
var num: number;
/* Records */
var records: lambda.Records;
recordsList = records.Records;
/* Record */
var record: lambda.Record;
str = record.EventVersion;
str = record.EventSubscriptionArn;
str = record.EnventSource;
sns = record.Sns;
kinesis = record.kinesis;
/* SNS */
str = sns.Type;
str = sns.MessageId;
str = sns.TopicArn;
str = sns.Subject;
str = sns.Message;
date = sns.Timestamp;
/* Kinesis */
var kinesis: lambda.Kinesis;
str = kinesis.data;
var identity: lambda.CognitoIdentity;
var error: Error;
var b: boolean;
var clientCtx: lambda.ClientContext;
/* Context */
var context: lambda.Context;
context.log(str, anyObj);
context.fail(str);
context.succeed(str);
context.succeed(anyObj);
context.succeed(str, anyObj);
b = context.callbackWaitsForEmptyEventLoop;
str = context.functionName;
str = context.functionVersion;
str = context.invokedFunctionArn;
num = context.memoryLimitInMB;
str = context.awsRequestId;
num = context.getRemainingTimeInMillis();
str = context.logGroupName;
str = context.logStreamName;
identity = context.identity;
clientCtx = context.clientContext;
/* CognitoIdentity */
var identity: lambda.CognitoIdentity;
str = identity.cognitoIdentityId;
str = identity.cognitoIdentityPoolId;
/* Callback */
function callback(cb: lambda.Callback) {
cb();
cb(null);
cb(error);
cb(null, anyObj);
}
+56 -31
View File
@@ -1,43 +1,68 @@
// Type definitions for AWS Lambda
// Project: http://docs.aws.amazon.com/lambda
// Definitions by: Michael Skarum <https://github.com/skarum>
// Definitions by: James Darbyshire <https://github.com/darbio/aws-lambda-typescript>, Michael Skarum <https://github.com/skarum>, Stef Heyenrath <https://github.com/StefH/DefinitelyTyped>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "aws-lambda" {
// Context
// http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
interface Context {
// Properties
callbackWaitsForEmptyEventLoop: boolean;
functionName: string;
functionVersion: string;
invokedFunctionArn: string;
memoryLimitInMB: number;
awsRequestId: string;
logGroupName: string;
logStreamName: string;
identity?: CognitoIdentity;
clientContext?: ClientContext;
// Functions
getRemainingTimeInMillis(): number;
export interface Records {
Records: Record[];
}
interface Record {
EventVersion: string;
EventSubscriptionArn: string;
EnventSource: string;
Sns: SNS;
kinesis: Kinesis;
}
interface SNS {
Type: string;
MessageId: string;
TopicArn: string;
Subject: string;
Message: string;
Timestamp: Date;
}
interface Kinesis {
data: string;
}
export interface Context {
// Functions for compatibility with earlier Node.js Runtime v0.10.42
log(message: string, object: any): void;
fail(message: string): void;
succeed(message: string): void;
succeed(object: any): void;
succeed(message: string, object: any): void;
awsRequestId: string;
getRemainingTimeInMillis(): number;
succeed(message: string, object: any): void;
}
export type Callback = (error?: Error, message?: string) => void;
interface CognitoIdentity {
cognitoIdentityId: string;
cognitoIdentityPoolId: string;
}
interface ClientContext {
client: ClientContextClient;
Custom?: any;
env: ClientContextEnv;
}
interface ClientContextClient {
installationId: string;
appTitle: string;
appVersionName: string;
appVersionCode: string;
appPackageName: string;
}
interface ClientContextEnv {
platformVersion: string;
platform: string;
make: string;
model: string;
locale: string;
}
/**
* Optional callback parameter.
* http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
*
* @param error – an optional parameter that you can use to provide results of the failed Lambda function execution.
* @param result – an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible.
*/
export type Callback = (error?: Error, result?: any) => void;
}
+719 -1
View File
@@ -22,6 +22,27 @@ declare module "aws-sdk" {
constructor(profile: string);
}
export module CognitoIdentity {
export interface CognitoIdentityCredentialsParams {
IdentityPoolId?: string;
AccountId?: string;
Logins?: {[k: string]: any};
RoleArn?: string;
RoleSessionName?: string;
WebIdentityToken?: string;
ProviderId?: string;
Policy?: string;
DurationSeconds?: number;
IdentityId?: string;
}
}
export class CognitoIdentityCredentials extends Credentials {
constructor(params: CognitoIdentity.CognitoIdentityCredentialsParams);
}
export interface Logger {
write?: (chunk: any, encoding?: string, callback?: () => void) => void;
log?: (...messages: any[]) => void;
@@ -49,6 +70,51 @@ declare module "aws-sdk" {
stack: string;
}
export interface RetryDelayOption {
base?: number;
customBackoff?: (retryCount: number) => number;
}
export interface Ebs {
SnapshotId?: string;
VolumeSize?: number;
VolumeType?: string;
DeleteOnTermination?: boolean;
Iops?: number;
Encrypted?: boolean;
}
export interface BlockDeviceMapping {
VirtualName?: string;
DeviceName: string;
Ebs?: Ebs;
NoDevice?: boolean;
}
export interface InstanceMonitoring {
SpotPrice?: string;
Enabled?: boolean;
}
export interface Filter {
Name?: string;
Values?: boolean;
}
export interface StepAdjustment {
scalingAdjustment: number;
metricIntervalLowerBound?: number;
metricIntervalUpperBound?: number;
}
export interface Tags {
resourceId?: string;
resourceType?: string;
key: string;
value?: string;
propagateAtLaunch?: boolean;
}
export interface Services {
autoscaling?: any;
cloudformation?: any;
@@ -118,6 +184,37 @@ declare module "aws-sdk" {
region: string;
}
export class CloudFormation {
constructor(options?: CloudFormation.Options);
endpoint: Endpoint;
cancelUpdateStack(params: CloudFormation.CancelUpdateStackParams, callback: (err: AwsError, data: any) => void): void;
continueUpdateRollback(params: CloudFormation.ContinueUpdateRollbackParams, callback: (err: AwsError, data: any) => void): void;
createChangeSet(params: CloudFormation.CreateChangeSetParams, callback: (err: AwsError, data: any) => void): void;
createStack(params: CloudFormation.CreateStackParams, callback: (err: AwsError, data: any) => void): void;
deleteChangeSet(params: CloudFormation.DeleteChangeSetParams, callback: (err: AwsError, data: any) => void): void;
deleteStack(params: CloudFormation.DeleteStackParams, callback: (err: AwsError, data: any) => void): void;
describeAccountLimits(params: CloudFormation.DescribeAccountLimitsParams, callback: (err: AwsError, data: any) => void): void;
describeChangeSet(params: CloudFormation.DescribeChangeSetParams, callback: (err: AwsError, data: any) => void): void;
describeStackEvents(params: CloudFormation.DescribeStackEventsParams, callback: (err: AwsError, data: any) => void): void;
describeStackResource(params: CloudFormation.DescribeStackResourceParams, callback: (err: AwsError, data: any) => void): void;
describeStackResources(params: CloudFormation.DescribeStackResourcesParams, callback: (err: AwsError, data: any) => void): void;
describeStacks(params: CloudFormation.DescribeStacksParams, callback: (err: AwsError, data: any) => void): void;
estimateTemplateCost(params: CloudFormation.EstimateTemplateCostParams, callback: (err: AwsError, data: any) => void): void;
executeChangeSet(params: CloudFormation.ExecuteChangeSetParams, callback: (err: AwsError, data: any) => void): void;
getStackPolicy(params: CloudFormation.GetStackPolicyParams, callback: (err: AwsError, data: any) => void): void;
getTemplate(params: CloudFormation.GetTemplateParams, callback: (err: AwsError, data: any) => void): void;
getTemplateSummary(params: CloudFormation.GetTemplateSummaryParams, callback: (err: AwsError, data: any) => void): void;
listChangeSets(params: CloudFormation.ListChangeSetsParams, callback: (err: AwsError, data: any) => void): void;
listStackResources(params: CloudFormation.ListStackResourcesParams, callback: (err: AwsError, data: any) => void): void;
listStacks(params: CloudFormation.ListStacksParams, callback: (err: AwsError, data: any) => void): void;
setStackPolicy(params: CloudFormation.SetStackPolicyParams, callback: (err: AwsError, data: any) => void): void;
signalResource(params: CloudFormation.SignalResourceParams, callback: (err: AwsError, data: any) => void): void;
updateStack(params: CloudFormation.UpdateStackParams, callback: (err: AwsError, data: any) => void): void;
validateTemplate(params: CloudFormation.ValidateTemplateParams, callback: (err: AwsError, data: any) => void): void;
waitFor(state: string, params: CloudFormation.WaitForParams, callback: (err: AwsError, data: any) => void): void;
}
export class Lambda {
constructor(options?: any);
endpoint: Endpoint;
@@ -147,6 +244,64 @@ declare module "aws-sdk" {
updateFunctionConfiguration(params: Lambda.UpdateFunctionConfigurationParams, callback: (err: AwsError, data: any) => void): void;
}
export class AutoScaling {
constructor(options?: any);
endpoint: Endpoint;
attachInstances(params: AutoScaling.AttachInstancesParams, callback: (err: AwsError, data: any) => void): void;
attachLoadBalancers(params: AutoScaling.AttachLoadBalancersParams, callback: (err: AwsError, data: any) => void): void;
attachLoadBalancerTargetGroups(param: AutoScaling.AttachLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void;
completeLifecycleAction(param: AutoScaling.CompleteLifecycleActionParams, callback: (err: AwsError, data: any) => void): void;
createAutoScalingGroup(param: AutoScaling.CreateAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void;
createLaunchConfiguration(param: AutoScaling.CreateLaunchConfigurationParams, callback: (err: AwsError, data: any) => void): void;
createOrUpdateTags(param: AutoScaling.CreateOrUpdateTagsParams, callback: (err: AwsError, data: any) => void): void;
deleteAutoScalingGroup(param: AutoScaling.DeleteAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void;
deleteLaunchConfiguration(param: AutoScaling.DeleteLaunchConfigurationParams, callback: (err: AwsError, data: any) => void): void;
deleteLifecycleHook(param: AutoScaling.DeleteLifecycleHookParams, callback: (err: AwsError, data: any) => void): void;
deleteNotificationConfiguration(param: AutoScaling.DeleteNotificationConfigurationParams, callback: (err: AwsError, data: any) => void): void;
deletePolicy(param: AutoScaling.DeletePolicyParams, callback: (err: AwsError, data: any) => void): void;
deleteScheduledAction(param: AutoScaling.DeleteScheduledActionParams, callback: (err: AwsError, data: any) => void): void;
deleteTags(param: AutoScaling.DeleteTagsParams, callback: (err: AwsError, data: any) => void): void;
describeAccountLimits(callback: (err: AwsError, data: any) => void): void;
describeAdjustmentTypes(callback: (err: AwsError, data: any) => void): void;
describeAutoScalingGroups(param: AutoScaling.DescribeAutoScalingGroupsParams, callback: (err: AwsError, data: any) => void): void;
describeAutoScalingInstances(param: AutoScaling.DescribeAutoScalingInstancesParams, callback: (err: AwsError, data: any) => void): void;
describeAutoScalingNotificationTypes(callback: (err: AwsError, data: any) => void): void;
describeLaunchConfigurations(param: AutoScaling.DescribeLaunchConfigurationsParams, callback: (err: AwsError, data: any) => void): void;
describeLifecycleHooks(param: AutoScaling.DescribeLifecycleHooksParams, callback: (err: AwsError, data: any) => void): void;
describeLifecycleHookTypes(callback: (err: AwsError, data: any) => void): void;
describeLoadBalancers(param: AutoScaling.DescribeLoadBalancersParams, callback: (err: AwsError, data: any) => void): void;
describeLoadBalancerTargetGroups(param: AutoScaling.DescribeLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void;
describeMetricCollectionTypes(callback: (err: AwsError, data: any) => void): void;
describeNotificationConfigurations(param: AutoScaling.DescribeNotificationConfigurationsParams, callback: (err: AwsError, data: any) => void): void;
describePolicies(param: AutoScaling.DescribePoliciesParams, callback: (err: AwsError, data: any) => void): void;
describeScalingActivities(param: AutoScaling.DescribeScalingActivitiesParams, callback: (err: AwsError, data: any) => void): void;
describeScalingProcessTypes(callback: (err: AwsError, data: any) => void): void;
describeScheduledActions(param: AutoScaling.DescribeScheduledActionsParams, callback: (err: AwsError, data: any) => void): void;
describeTags(param: AutoScaling.DescribeTagsParams, callback: (err: AwsError, data: any) => void): void;
describeTerminationPolicyTypes(callback: (err: AwsError, data: any) => void): void;
detachInstances(param: AutoScaling.DetachInstancesParams, callback: (err: AwsError, data: any) => void): void;
detachLoadBalancers(param: AutoScaling.DetachLoadBalancersParams, callback: (err: AwsError, data: any) => void): void;
detachLoadBalancerTargetGroups(param: AutoScaling.DetachLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void;
disableMetricsCollection(param: AutoScaling.DisableMetricsCollectionParams, callback: (err: AwsError, data: any) => void): void;
enableMetricsCollection(param: AutoScaling.EnableMetricsCollectionParams, callback: (err: AwsError, data: any) => void): void;
enterStandby(param: AutoScaling.EnterStandbyParams, callback: (err: AwsError, data: any) => void): void;
executePolicy(param: AutoScaling.ExecutePolicyParams, callback: (err: AwsError, data: any) => void): void;
exitStandby(param: AutoScaling.ExitStandbyParams, callback: (err: AwsError, data: any) => void): void;
putLifecycleHook(param: AutoScaling.PutLifecycleHookParams, callback: (err: AwsError, data: any) => void): void;
putNotificationConfiguration(param: AutoScaling.PutNotificationConfigurationParams, callback: (err: AwsError, data: any) => void): void;
putScalingPolicy(param: AutoScaling.PutScalingPolicyParams, callback: (err: AwsError, data: any) => void): void;
putScheduledUpdateGroupAction(param: AutoScaling.PutScheduledUpdateGroupActionParams, callback: (err: AwsError, data: any) => void): void;
recordLifecycleActionHeartbeat(params: AutoScaling.RecordLifecycleActionHeartbeatParams, callback: (err: AwsError, data: any) => void): void;
resumeProcesses(params: AutoScaling.ResumeProcessesParams, callback: (err: AwsError, data: any) => void): void;
setDesiredCapacity(params: AutoScaling.SetDesiredCapacityParams, callback: (err: AwsError, data: any) => void): void;
setInstanceHealth(params: AutoScaling.SetInstanceHealthParams, callback: (err: AwsError, data: any) => void): void;
setInstanceProtection(params: AutoScaling.SetInstanceProtectionParams, callback: (err: AwsError, data: any) => void): void;
suspendProcesses(params: AutoScaling.SuspendProcessesParams, callback: (err: AwsError, data: any) => void): void;
terminateInstanceInAutoScalingGroup(params: AutoScaling.TerminateInstanceInAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void;
updateAutoScalingGroup(params: AutoScaling.UpdateAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void;
}
export class SQS {
constructor(options?: any);
endpoint: Endpoint;
@@ -226,7 +381,7 @@ declare module "aws-sdk" {
constructor(options?: any);
endpoint: Endpoint;
getObject(params: s3.GetObjectRequest, callback: (err: Error, data: any) => void): void;
getObject(params: s3.GetObjectRequest, callback?: (err: Error, data: any) => void): any;
putObject(params: s3.PutObjectRequest, callback: (err: Error, data: any) => void): void;
deleteObject(params: s3.DeleteObjectRequest, callback: (err: Error, data: any) => void): void;
headObject(params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void;
@@ -235,6 +390,12 @@ declare module "aws-sdk" {
upload(params?: s3.PutObjectRequest, options?: s3.UploadOptions, callback?: (err: Error, data: any) => void): void;
listObjects(params: s3.ListObjectRequest, callback: (err: Error, data: s3.ListObjectResponse) => void): void;
listObjectsV2(params: s3.ListObjectV2Request, callback: (err: Error, data: s3.ListObjectV2Response) => void): void;
waitFor(state: string, params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void;
createMultipartUpload(params: any, callback: (err: Error, data: any) => void): void;
uploadPart(params: any, callback: (err: Error, data: any) => void): void;
listParts(params: any, callback: (err: Error, data: any) => void): void;
completeMultipartUpload(params: any, callback: (err: Error, data: any) => void): void;
}
export class STS {
@@ -423,6 +584,214 @@ declare module "aws-sdk" {
// ===========================================================
export module CloudFormation {
export interface CancelUpdateStackParams {
StackName: string;
}
export interface ContinueUpdateRollbackParams {
StackName: string;
}
export interface CreateChangeSetParams {
StackName: string;
TemplateBody?: string; // specify either TemplateBody or TemplateURL
TemplateURL?: string; // specify either TemplateBody or TemplateURL
UsePreviousTemplate?: boolean;
Parameters?: CloudFormation.Parameter[];
Capabilities?: string[]; // CAPABILITY_IAM | CAPABILITY_NAMED_IAM
ResourceTypes?: string[];
NotificationARNs?: string[];
Tags?: CloudFormation.Tag[];
ChangeSetName: string;
ClientToken?: string;
Description?: string;
}
export interface CreateStackParams {
StackName: string;
TemplateBody?: string; // specify either TemplateBody or TemplateURL
TemplateURL?: string; // specify either TemplateBody or TemplateURL
Parameters?: CloudFormation.Parameter[];
DisableRollback?: boolean; // cannot specify both DisableRollback and OnFailure
TimeoutInMinutes?: number;
NotificationARNs?: string[];
Capabilities?: string[];
ResourceTypes?: string[];
OnFailure?: string[]; // cannot specify both DisableRollback and OnFailure
// DO_NOTHING | ROLLBACK | DELETE
StackPolicyBody?: string[]; // cannot specify both StackPolicyBody and StackPolicyURL
StackPolicyURL?: string[]; // cannot specify both StackPolicyBody and StackPolicyURL
Tags?: CloudFormation.Tag[];
}
export interface DeleteChangeSetParams {
ChangeSetName: string;
StackName?: string;
}
export interface DeleteStackParams {
StackName: string;
RetainResources?: string[];
}
export interface DescribeAccountLimitsParams {
NextToken?: string;
}
export interface DescribeChangeSetParams {
ChangeSetName: string;
StackName?: string;
NextToken?: string;
}
export interface DescribeStackEventsParams {
StackName?: string;
NextToken?: string;
}
export interface DescribeStackResourceParams {
StackName: string;
LogicalResourceId: string;
}
export interface DescribeStackResourcesParams {
StackName?: string; // must specify either StackName or PhysicalResourceId
LogicalResourceId?: string;
PhysicalResourceId?: string; // must specify either StackName or PhysicalResourceId
}
export interface DescribeStacksParams {
StackName?: string;
NextToken?: string;
}
export interface EstimateTemplateCostParams {
TemplateBody?: string; // must specify either TemplateBody or TemplateURL
// if both are passed, only TemplateBody is used
TemplateURL?: string; // must specify either TemplateBody or TemplateURL
Parameters?: CloudFormation.Parameter[];
}
export interface ExecuteChangeSetParams {
ChangeSetName: string;
StackName?: string;
}
export interface GetStackPolicyParams {
StackName: string;
}
export interface GetTemplateParams {
StackName: string;
}
export interface GetTemplateSummaryParams {
// must specify one of the three
TemplateBody?: string;
TemplateURL?: string;
StackName?: string;
}
export interface ListChangeSetsParams {
StackName: string;
NextToken?: string;
}
export interface ListStackResourcesParams {
StackName: string;
NextToken?: string;
}
export interface ListStacksParams {
NextToken?: string;
StackStatusFilter?: string[];
}
export interface SetStackPolicyParams {
StackName: string;
StackPolicyBody?: string; // cannot set both StackPolicyBody and StackPolicyURL
StackPolicyURL?: string; // cannot set both StackPolicyBody and StackPolicyURL
}
export interface SignalResourceParams {
StackName: string;
LogicalResourceId: string;
UniqueId: string;
Status: string; // SUCCESS | FAILURE
}
export interface UpdateStackParams {
StackName: string;
TemplateBody?: string; // specify either TemplateBody or TemplateURL, not both
TemplateURL?: string; // specify either TemplateBody or TemplateURL, not both
UsePreviousTemplate?: boolean;
StackPolicyDuringUpdateBody?: string; // cannot set both StackPolicyDuringUpdateBody and StackPolicyDuringUpdateURL
StackPolicyDuringUpdateURL?: string; // cannot set both StackPolicyDuringUpdateBody and StackPolicyDuringUpdateURL
Parameters?: CloudFormation.Parameter[];
Capabilities?: string[]; // CAPABILITY_IAM | CAPABILITY_NAMED_IAM
ResourceTypes?: string[];
StackPolicyBody?: string; // cannot set both StackPolicyBody and StackPolicyURL
StackPolicyURL?: string; // cannot set both StackPolicyBody and StackPolicyURL
NotificationARNs?: string[];
Tags?: CloudFormation.Tag[];
}
export interface ValidateTemplateParams {
TemplateBody?: string; // must pass either TemplateBody or TemplateURL
// if both are specified, only TemplateBody is used
TemplateURL?: string; // must pass either TemplateBody or TemplateURL
}
export interface WaitForParams {
StackName: string;
NextToken?: string;
}
export interface Options {
params?: any;
endpoint?: string;
accessKeyId?: string;
secretAccessKey?: string;
sessionToken?: any;
credentials?: any;
credentialProvider?: any;
region?: string;
maxRetries?: number;
maxRedirects?: number;
sslEnabled?: boolean;
paramValidation?: any;
computeChecksums?: boolean;
convertResponseTypes?: boolean;
correctClockSkew?: boolean;
s3ForcePathStyle?: boolean;
s3BucketEndpoint?: boolean;
s3DisableBodySigning?: boolean;
retryDelayOptions?: any;
httpOptions?: any;
apiVersion?: any;
apiVersions?: any;
logger?: any;
systemClockOffset?: number;
signatureVersion?: string;
signatureCache?: boolean;
}
export interface Parameter {
ParameterKey: string;
ParameterValue: string;
UsePreviousValue?: boolean; // if you specify true, do not specify ParameterValue
}
export interface Tag {
Key: string;
Value: string;
}
}
// ===========================================================
export module Lambda {
export interface AddPermissionParams {
@@ -592,6 +961,355 @@ declare module "aws-sdk" {
}
}
export module AutoScaling {
export interface AutoScalingOptions {
params?: any;
endpoint?: string;
accessKeyId?: string;
secretAccessKey?: string;
sessionToken?: Credentials;
credentials?: Credentials;
credentialProvider?: any;
region?: string;
maxRetries?: number;
maxRedirects?: number;
sslEnabled?: boolean;
paramValidation?: boolean;
computeChecksums?: boolean;
convertResponseTypes?: boolean;
correctClockSkew?: boolean;
s3ForcePathStyle?: boolean;
s3BucketEndpoint?: boolean;
s3DisableBodySigning?: boolean;
retryDelayOptions?: RetryDelayOption;
httpOptions?: HttpOptions;
apiVersion?: string;
apiVersions?: { [serviceName: string]: string };
logger?: Logger;
systemClockOffset?: number;
signatureVersion?: string;
signatureCache?: boolean;
}
export interface AttachInstancesParams {
AutoScalingGroupName: string;
InstanceIds: string[];
}
export interface AttachLoadBalancersParams {
AutoScalingGroupName: string;
LoadBalancerNames: string[];
}
export interface AttachLoadBalancerTargetGroupsParams {
AutoScalingGroupName: string;
TargetGroupARNs: string[];
}
export interface CompleteLifecycleActionParams {
AutoScalingGroupName: string;
LifecycleActionResult: string;
LifecycleHookName: string;
lifecycleActionToken?: string;
InstanceId?: string;
}
export interface CreateAutoScalingGroupParams {
AutoScalingGroupName: string;
MinSize: number;
MaxSize: number;
LaunchConfigurationName?: string;
InstanceId?: string;
DesiredCapacity?: number;
DefaultCooldown?: number;
AvailabilityZones?: string[];
LoadBalancerNames?: string[];
TargetGroupARNs?: string[];
HealthCheckType?: string;
HealthCheckGracePeriod?: number;
PlacementGroup?: string;
VPCZoneIdentifier?: string;
TerminationPolicies?: string;
NewInstancesProtectedFromScaleIn?: boolean;
Tags?: Tags;
}
export interface CreateLaunchConfigurationParams {
LaunchConfigurationName: string;
AssociatePublicIpAddress?: boolean;
ImageId?: string;
KeyName?: string;
SecurityGroups?: string[];
ClassicLinkVPCId?: string;
ClassicLinkVPCSecurityGroups?: string[];
UserData?: string;
InstanceId?: string;
InstanceType?: string;
KernelId?: string;
RamdiskId?: string;
BlockDeviceMappings?: BlockDeviceMapping[];
InstanceMonitoring?: InstanceMonitoring;
SpotPrice?: string;
IamInstanceProfile?: string;
EbsOptimized?: boolean;
PlacementTenancy?: string;
}
export interface CreateOrUpdateTagsParams {
Tags: Tags[];
}
export interface DeleteAutoScalingGroupParams {
AutoScalingGroupName: string;
ForceDelete?: boolean;
}
export interface DeleteLaunchConfigurationParams {
LaunchConfigurationName: string;
}
export interface DeleteLifecycleHookParams {
AutoScalingGroupName: string;
LifecycleHookName: string;
}
export interface DeleteNotificationConfigurationParams {
AutoScalingGroupName: string;
TopicARN: string;
}
export interface DeletePolicyParams {
PolicyName: string;
AutoScalingGroupName?: string;
}
export interface DeleteScheduledActionParams {
AutoScalingGroupName: string;
ScheduledActionName: string;
}
export interface DeleteTagsParams {
Tags: Tags[];
}
export interface DescribeAutoScalingGroupsParams {
AutoScalingGroupName?: string;
NextToken?: string;
MaxRecords?: number;
}
export interface DescribeAutoScalingInstancesParams {
InstanceIds?: string[];
NextToken?: string;
MaxRecords?: number;
}
export interface DescribeLaunchConfigurationsParams {
LaunchConfigurationNames?: string[];
NextToken?: string;
MaxRecords?: number;
}
export interface DescribeLifecycleHooksParams {
AutoScalingGroupName: string;
LifecycleHookNames?: string[];
}
export interface DescribeLoadBalancersParams {
AutoScalingGroupName: string;
NextToken?: string;
MaxRecords?: number;
}
export interface DescribeLoadBalancerTargetGroupsParams {
AutoScalingGroupName: string;
NextToken?: string;
MaxRecords?: number;
}
export interface DescribeNotificationConfigurationsParams {
AutoScalingGroupName?: string;
NextToken?: string;
MaxRecords?: number;
}
export interface DescribePoliciesParams {
AutoScalingGroupName?: string;
PolicyNames?: string[];
PolicyTypes?: string[];
NextToken?: string;
MaxRecords?: number;
}
export interface DescribeScalingActivitiesParams {
AutoScalingGroupName?: string;
ActivityIds?: string[];
NextToken?: string;
MaxRecords?: number;
}
export interface DescribeScheduledActionsParams {
AutoScalingGroupName?: string;
ScheduledActionNames?: string[];
StartTime?: Date;
EndTime?: Date;
NextToken?: string;
MaxRecords?: number;
}
export interface DescribeTagsParams {
Filters?: Filter[];
NextToken?: string;
MaxRecords?: number;
}
export interface DetachInstancesParams {
AutoScalingGroupName: string;
ShouldDecrementDesiredCapacity: boolean;
InstanceIds?: string[];
}
export interface DetachLoadBalancersParams {
AutoScalingGroupName: string;
LoadBalancerNames: string;
}
export interface DetachLoadBalancerTargetGroupsParams {
AutoScalingGroupName: string;
TargetGroupARNs: string[];
}
export interface DisableMetricsCollectionParams {
AutoScalingGroupName: string;
Metrics?: string[];
}
export interface EnableMetricsCollectionParams {
AutoScalingGroupName: string;
Granularity: string;
Metrics?: string[];
}
export interface EnterStandbyParams {
AutoScalingGroupName: string;
ShouldDecrementDesiredCapacity: boolean;
InstanceIds?: string[];
}
export interface ExecutePolicyParams {
PolicyName: string;
AutoScalingGroupName?: string;
HonorCooldown?: boolean;
MetricValue?: number;
BreachThreshold?: number;
}
export interface ExitStandbyParams {
AutoScalingGroupName: string;
InstanceIds?: string[];
}
export interface PutLifecycleHookParams {
AutoScalingGroupName: string;
LifecycleHookName: string;
LifecycleTransition?: string;
RoleARN?: string;
NotificationTargetARN?: string;
NotificationMetadata?: string;
HeartbeatTimeout?: number;
DefaultResult?: string;
}
export interface PutNotificationConfigurationParams {
AutoScalingGroupName: string;
NotificationTypes: string[];
TopicARN: string;
}
export interface PutScalingPolicyParams {
AutoScalingGroupName: string;
AdjustmentType: string;
PolicyName: string;
PolicyType?: string;
MinAdjustmentStep?: number;
MinAdjustmentMagnitude?: number;
ScalingAdjustment?: number;
Cooldown?: number;
MetricAggregationType?: string;
StepAdjustments?: StepAdjustment[];
EstimatedInstanceWarmup: number;
}
export interface PutScheduledUpdateGroupActionParams {
AutoScalingGroupName: string;
ScheduledActionName: string;
Time?: Date;
StartTime?: Date;
EndTime?: Date;
Recurrence?: string;
MinSize?: number;
MaxSize?: number;
DesiredCapacity?: number;
}
export interface RecordLifecycleActionHeartbeatParams {
AutoScalingGroupName: string;
LifecycleHookName: string;
LifecycleActionToken?: string;
InstanceId?: string;
}
export interface ResumeProcessesParams {
AutoScalingGroupName: string;
ScalingProcesses?: string[];
}
export interface SetDesiredCapacityParams {
AutoScalingGroupName: string;
DesiredCapacity: number;
HonorCooldown?: boolean;
}
export interface SetInstanceHealthParams {
HealthStatus: string;
InstanceId: string;
ShouldRespectGracePeriod?: boolean;
}
export interface SetInstanceProtectionParams {
AutoScalingGroupName: string;
InstanceIds: string[];
ProtectedFromScaleIn: boolean;
}
export interface SuspendProcessesParams {
AutoScalingGroupName: string;
ScalingProcesses?: string[];
}
export interface TerminateInstanceInAutoScalingGroupParams {
InstanceId: string;
ShouldDecrementDesiredCapacity: boolean;
}
export interface UpdateAutoScalingGroupParams {
AutoScalingGroupName: string;
LaunchConfigurationName: string;
MinSize: number;
MaxSize: number;
DesiredCapacity: number;
DefaultCooldown: number;
AvailabilityZones: string[];
HealthCheckType: string;
HealthCheckGracePeriod: number;
PlacementGroup: string;
VPCZoneIdentifier: string;
TerminationPolicies: string[];
NewInstancesProtectedFromScaleIn?: boolean;
}
}
export module SQS {
export interface SqsOptions {
+91
View File
@@ -0,0 +1,91 @@
/// <reference path="axe-core.d.ts" />
var context:any = document
var $fixture:any = {}
// axe.a11yCheck config
axe.a11yCheck(context, {}, (results) => {
// axe's results object
console.log(results.passes.length)
console.log(results.violations.length)
});
// axe.a11yCheck include/exclude
axe.a11yCheck({include: [['#id1'], ['#id2']]}, {}, (results) => {
console.log(results)
})
axe.a11yCheck({exclude: [$fixture[0]]}, {}, (results) => {
console.log(results)
})
var tagConfigRunOnly: axe.RunOnly = {
type: 'tag',
values: ['wcag2a']
}
var tagConfig = {
runOnly: tagConfigRunOnly
}
axe.a11yCheck(context, tagConfig, (results) => {
console.log(results)
})
var includeExcludeTagsRunOnly: axe.RunOnly = {
type: 'tags',
value: {
include: ['wcag2a', 'wcag2aa'],
exclude: ['experimental']
}
}
var includeExcludeTagsConfig = {
runOnly: includeExcludeTagsRunOnly
}
axe.a11yCheck(context, includeExcludeTagsConfig, (results) => {
console.log(results)
})
var someRulesConfig = {
rules: {
"color-contrast": {enabled: 'false'},
"heading-order": {enabled: 'true'}
}
}
axe.a11yCheck(context, someRulesConfig, (results) => {
console.log(results)
})
// axe.configure
var spec: axe.Spec = {
branding: {
brand: 'foo',
application: 'bar'
},
reporter: 'v1',
checks: [{
id: 'custom-check',
evaluate: function() {
return true
}
}],
rules: [{
id: 'custom-rule',
any: ['custom-check']
}]
}
axe.configure(spec)
axe.reset()
axe.getRules(['wcag2aa'])
typeof axe.getRules() === 'object'
// Plugins
var pluginSrc: axe.AxePlugin = {
id: 'doStuff',
run: (data:any, callback:Function) => {
callback()
},
commands: [{
id: 'run-doStuff',
callback: (data:any, callback:Function) => {
axe.plugins['doStuff'].run(data, callback)
}
}]
}
axe.registerPlugin(pluginSrc)
axe.cleanup()
+159
View File
@@ -0,0 +1,159 @@
// Type definitions for axe-core 2.0.5
// Project: https://github.com/dequelabs/axe-core
// Definitions by: Marcy Sutton <https://github.com/marcysutton>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace axe {
export type ImpactValue = "minor" | "moderate" | "serious" | "critical";
export type TagValue = "wcag2a" | "wcag2aa" | "section508" | "best-practice";
export type ReporterVersion = "v1" | "v2";
export type RunOnlyType = "rule" | "rules" | "tag" | "tags";
export interface ElementContext {
node?: Object,
selector?: string,
include?: any[],
exclude?: any[]
}
export interface RunOnly {
type: RunOnlyType,
value?: {
include?: string[],
exclude?: string[]
}
values?: TagValue[]
}
export interface AxeResults {
url: string,
timestamp: string,
passes: Pass[],
violations: Violation[]
}
export interface Pass {
description: string,
help: string,
helpUrl: string,
id: string,
impact: ImpactValue,
tags: TagValue[],
nodes: NodeResult[]
}
export interface Violation {
description: string,
help: string,
helpUrl: string,
id: string,
impact: ImpactValue,
tags: TagValue[],
nodes: NodeResult[]
}
export interface NodeResult {
html: string,
impact: ImpactValue,
target: string[],
any: CheckResult[],
all: CheckResult[],
none: CheckResult[]
}
export interface CheckResult {
id: string,
impact: string,
message: string,
data: any,
relatedNodes?: RelatedNode[]
}
export interface RelatedNode {
target: string[],
html: string
}
export interface Spec {
branding?: {
brand: string,
application: string
},
reporter?: ReporterVersion,
checks?: Check[],
rules?: Rule[]
}
export interface Check {
id: string,
evaluate: Function,
after?: Function,
options?: any,
matches?: string,
enabled?: boolean
}
export interface Rule {
id: string,
selector?: string,
excludeHidden?: boolean,
enabled?: boolean,
pageLevel?: boolean,
any?: string[],
all?: string[],
none?: string[],
tags?: string[],
matches?: string
}
export interface AxePlugin {
id: string,
run(...args:any[]): any,
commands: {
id: string,
callback(...args:any[]): void
}[],
cleanup?(callback:Function): void
}
export let plugins: any
/**
* Starts analysis on the current document and its subframes
*
* @param {Object} context The `Context` specification object @see Context
* @param {Array} options Options passed into rules or checks, temporarily modifyint them.
* @param {Function} callback The function to invoke when analysis is complete.
* @returns {Object} results The aXe results object
*/
export function a11yCheck(context: ElementContext, options: {runOnly?: RunOnly, rules?: Object}, callback: (results:AxeResults) => void): AxeResults
/**
* Method for configuring the data format used by aXe. Helpful for adding new
* rules, which must be registered with the library to execute.
* @param {Spec} Spec Object with valid `branding`, `reporter`, `checks` and `rules` data
*/
export function configure(spec: Spec): void
/**
* Searches and returns rules that contain a tag in the list of tags.
* @param {Array} tags Optional array of tags
* @return {Array} Array of rules
*/
export function getRules(tags?: string[]): Object[]
/**
* Restores the default axe configuration
*/
export function reset(): void
/**
* Function to register a plugin configuration in document and its subframes
* @param {Object} plugin A plugin configuration object
*/
export function registerPlugin(plugin: AxePlugin): void
/**
* Function to clean up plugin configuration in document and its subframes
*/
export function cleanup(): void
}
// axe is also available as a module
declare module "axe-core" {
export = axe;
}
+46 -8
View File
@@ -8,7 +8,7 @@ import queries = require('azure-mobile-apps/src/query');
var app = express(),
mobileApp = mobileApps();
// various configuration permutations
// various configuration permutations
mobileApps({
debug: true,
data: {
@@ -17,7 +17,8 @@ mobileApps({
user: '',
database: '',
password: ''
}
},
webhook: { url: 'http://localhost/' }
});
mobileApps({
@@ -29,7 +30,7 @@ mobileApps({
// it would be nice to integrate with winston
mobileApps({ logging: { level: 'silly', transports: [{}] } })
// various custom middleware syntaxes
// various custom middleware syntaxes
mobileApp.use(function (req: any, res: any, next: any) { next(); });
mobileApp.use([function () {}, function () {}]);
mobileApp.use(function () {}, function () {});
@@ -43,6 +44,9 @@ mobileApp.tables.import('tables');
mobileApp.api.add('api', { authorize: true, get: function () {}, delete: function () {} });
mobileApp.api.import('api');
// ensure the mobile app instance can be correctly mounted as an express router
app.use(mobileApp);
// Express.Table, instantiated from the mobile app
var table = mobileApp.table()
table.use(function (req: Express.Request, res: Express.Response, next: any) {
@@ -61,21 +65,45 @@ table.read(function (context: Azure.MobileApps.Context) {
table.insert(function (context: Azure.MobileApps.Context) {
context.query.id = 'anotherId';
context.query.single = true;
context.item.userId = context.user.id;
context.item.userId = context.user.id;
context.push.send('tag', {}, function (error, result) {});
context.push.gcm.send('tag', {}, function (error, result) {});
context.push.apns.send('tag', { payload: { } }, function (error, result) {});
context.push.wns.sendToastText01('tag', '', { headers: { } }, function (error, result) {});
context.next(new Error());
context.next('An error occurred');
});
table.read.use(function () {});
table.read.use([function () {}, function () {}]);
table.read.use(function () {}, function () {});
table.use(function () {}).use(function () {}).read(function () {}).use(function () {})
table.use(function () {}).use(function () {}).read(function () {}).use(function () {});
table.access = undefined;
table.access = 'authenticated';
table.read.access = 'anonymous';
table.update.access = 'disabled';
table.delete.access = 'authenticated';
table.insert.access = 'authenticated';
table.filters = [function (query, context) { }];
table.transforms = [function (item, context) { }];
table.hooks = [function (results, context) { }];
table.perUser = true;
table.recordsExpire = { milliseconds: 1, seconds: 1, minutes: 1, hours: 1, days: 1, weeks: 1, months: 1, years: 1 };
table.webhook = { url: 'http://localhost/' }
table.webhook = true;
// Express.Table, instantiated from the static require('azure-mobile-apps').table()
// This is going to be interesting if we ever support more than one provider
var table2 = mobileApps.table();
table2.read(function (context: Azure.MobileApps.Context) {})
table2.read(function (context: Azure.MobileApps.Context) {});
// ApiDefinition, from the static require('azure-mobile-apps').api()
var api2 = mobileApps.api({
get: function (req, res, next) { }
});
api2.post = function (req, res, next) {};
// Logger
logger.silly('test', 'message');
@@ -83,5 +111,15 @@ logger.error('Something happened', new Error());
mobileApps.logger.debug('a debug message')
// Query
queries.create('table').where({ x: 10 }).select('col1,col2');
mobileApps.query.create('table');
queries.create('table').where({ x: 10 }).select('col1,col2').includeDeleted().includeTotalCount();
mobileApps.query.create('table');
// Custom SQL query
mobileApp.api.add('query', { authorize: true, get: (req, res, next) => {
req.azureMobile.data.execute({
sql: "SELECT * FROM TODOITEM WHERE COMPLETE = :complete",
parameters: [
{ name: 'complete', value: 1 }
]
}).then(x => {});
}, delete: function () {} });
+62 -15
View File
@@ -1,4 +1,4 @@
// Type definitions for azure-mobile-apps v2.0.0-beta3
// Type definitions for azure-mobile-apps v2.1.7
// Project: https://github.com/Azure/azure-mobile-apps-node/
// Definitions by: Microsoft Azure <https://github.com/Azure/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -10,6 +10,7 @@ declare module "azure-mobile-apps" {
interface AzureMobileApps {
(configuration?: Azure.MobileApps.Configuration): Azure.MobileApps.Platforms.Express.MobileApp;
table(): Azure.MobileApps.Platforms.Express.Table;
api(definition?: Azure.MobileApps.ApiDefinition): Azure.MobileApps.ApiDefinition;
logger: Azure.MobileApps.Logger;
query: Azure.MobileApps.Query;
}
@@ -31,7 +32,7 @@ declare namespace Azure.MobileApps {
// the additional Platforms namespace is required to avoid collisions with the main Express namespace
export module Platforms {
export module Express {
interface MobileApp {
interface MobileApp extends Middleware {
configuration: Configuration;
tables: Tables;
table(): Table;
@@ -45,14 +46,7 @@ declare namespace Azure.MobileApps {
import(fileOrFolder: string): void;
}
interface Table {
authorize?: boolean;
autoIncrement?: boolean;
dynamicSchema?: boolean;
name: string;
columns?: any;
schema: string;
interface Table extends TableDefinition {
use(...middleware: Middleware[]): Table;
use(middleware: Middleware[]): Table;
read: TableOperation;
@@ -66,6 +60,7 @@ declare namespace Azure.MobileApps {
(operationHandler: (context: Context) => void): Table;
use(...middleware: Middleware[]): Table;
use(middleware: Middleware[]): Table;
access?: AccessType;
}
interface Tables {
@@ -132,6 +127,7 @@ declare namespace Azure.MobileApps {
auth?: Configuration.Auth;
cors?: Configuration.Cors;
notifications?: Configuration.Notifications;
webhook?: Webhook;
}
export module Configuration {
@@ -148,6 +144,7 @@ declare namespace Azure.MobileApps {
options?: { encrypt: boolean };
schema?: string;
dynamicSchema?: boolean;
filename?: string;
}
interface Auth {
@@ -163,8 +160,9 @@ declare namespace Azure.MobileApps {
interface LoggingTransport { }
interface Cors {
exposeHeaders: string;
maxAge?: number;
origins: string[];
hostnames: string[];
}
interface Notifications {
@@ -184,7 +182,8 @@ declare namespace Azure.MobileApps {
}
interface QueryJs {
includeTotalCount?: boolean;
includeTotalCount(): QueryJs;
includeDeleted(): QueryJs;
orderBy(properties: string): QueryJs;
orderByDescending(properties: string): QueryJs;
select(properties: string): QueryJs;
@@ -209,27 +208,75 @@ declare namespace Azure.MobileApps {
// general
var nh: Azure.ServiceBus.NotificationHubService;
interface Context {
query: QueryJs;
id: string | number;
item: any;
req: Express.Request;
res: Express.Response;
data: (table: TableDefinition) => Data.Table;
data: ContextData;
tables: (tableName: string) => Data.Table;
user: User;
push: typeof nh;
logger: Logger;
execute(): Thenable<any>;
next(error: string|Error): any;
}
interface ContextData {
(table: TableDefinition): Data.Table;
execute(q: SqlQueryDefinition): Thenable<any>;
}
interface SqlQueryDefinition {
sql: string;
parameters?: SqlParameterDefinition[];
}
interface SqlParameterDefinition {
name: string;
value: any;
}
interface TableDefinition {
access?: AccessType;
authorize?: boolean;
autoIncrement?: boolean;
dynamicSchema?: boolean;
name?: string;
columns?: any;
databaseTableName?: string;
dynamicSchema?: boolean;
maxTop?: number;
name?: string;
pageSize?: number;
schema?: string;
softDelete?: boolean;
userIdColumn?: string;
filters?: [(query: QueryJs, context: Context) => void | QueryJs];
transforms?: [(item: any, context: Context) => void | any];
hooks?: [(results: any, context: Context) => void];
perUser?: boolean;
recordsExpire?: Duration;
webhook?: Webhook | boolean;
}
type AccessType = 'anonymous' | 'authenticated' | 'disabled';
interface Duration {
milliseconds?: number;
seconds?: number;
minutes?: number;
hours?: number;
days?: number;
weeks?: number;
months?: number;
years?: number;
}
interface Webhook {
url: string;
}
interface ApiDefinition {
@@ -17,7 +17,7 @@ declare namespace Microsoft.WindowsAzure {
login(provider: string, token: string): asyncPromise;
login(provider: string, callback: (error: any, user: User) => void ): void;
login(provider: string): asyncPromise;
logout(): void;
logout(): asyncPromise;
getTable(tableName: string): MobileServiceTable;
withFilter(serviceFilter: (request: any, next: (request: any, callback: (error: any, response: any) => void) => void, callback: (error: any, response: any) => void) => void): MobileServiceClient;
/**
+1 -1
View File
@@ -346,7 +346,7 @@ declare module "babel-traverse" {
getData(key: string, def?: any): any;
buildCodeFrameError(msg: string, Error: Error): Error;
buildCodeFrameError<TError extends Error>(msg: string, Error?: new (msg: string) => TError): TError;
traverse(visitor: Visitor, state?: any): void;
+38 -30
View File
@@ -329,32 +329,32 @@ var CORE_PARSER_TESTS: ParserTest[] = [
}
},
// {
// description: "Comment with non-default character",
// input: 'a,b,c\n!Comment goes here\nd,e,f',
// config: { comments: '!' },
// expected: {
// data: [['a', 'b', 'c'], ['d', 'e', 'f']],
// errors: []
// }
// description: "Comment with non-default character",
// input: 'a,b,c\n!Comment goes here\nd,e,f',
// config: { comments: '!' },
// expected: {
// data: [['a', 'b', 'c'], ['d', 'e', 'f']],
// errors: []
// }
// },
// {
// description: "Bad comments value specified",
// notes: "Should silently disable comment parsing",
// input: 'a,b,c\n5comment\nd,e,f',
// config: { comments: 5 },
// expected: {
// data: [['a', 'b', 'c'], ['5comment'], ['d', 'e', 'f']],
// errors: []
// }
// description: "Bad comments value specified",
// notes: "Should silently disable comment parsing",
// input: 'a,b,c\n5comment\nd,e,f',
// config: { comments: 5 },
// expected: {
// data: [['a', 'b', 'c'], ['5comment'], ['d', 'e', 'f']],
// errors: []
// }
// },
// {
// description: "Multi-character comment string",
// input: 'a,b,c\n=N(Comment)\nd,e,f',
// config: { comments: "=N(" },
// expected: {
// data: [['a', 'b', 'c'], ['d', 'e', 'f']],
// errors: []
// }
// description: "Multi-character comment string",
// input: 'a,b,c\n=N(Comment)\nd,e,f',
// config: { comments: "=N(" },
// expected: {
// data: [['a', 'b', 'c'], ['d', 'e', 'f']],
// errors: []
// }
// },
{
description: "Input with only a commented line",
@@ -419,13 +419,13 @@ var CORE_PARSER_TESTS: ParserTest[] = [
}
},
// {
// description: "Fast mode with comments",
// input: '// Commented line\na,b,c',
// config: { fastMode: true, comments: "//" },
// expected: {
// data: [['a', 'b', 'c']],
// errors: []
// }
// description: "Fast mode with comments",
// input: '// Commented line\na,b,c',
// config: { fastMode: true, comments: "//" },
// expected: {
// data: [['a', 'b', 'c']],
// errors: []
// }
// },
{
description: "Fast mode with preview",
@@ -1091,7 +1091,7 @@ function compare(actualData: any[], actualErrors: any[], expected: ParserTestExp
}
}
if (passed) // final check will catch any other differences
if (passed) // final check will catch any other differences
passed = JSON.stringify(actual) == JSON.stringify(expected);
// We pass back an object right now, even though it only contains
@@ -1228,3 +1228,11 @@ var parser = new Baby.Parser({})
parser.getCharIndex();
parser.abort();
parser.parse("");
/**
* Parse Files
*/
Baby.parseFiles('example.csv')
Baby.parseFiles('example.csv', {encoding: 'utf-8'})
Baby.parseFiles(['example1.csv', 'example2.txt'])
Baby.parseFiles(['example1.csv', 'example2.txt'], {encoding: 'utf-8'})
+10
View File
@@ -9,6 +9,11 @@ declare namespace BabyParse {
* Parse a csv string or a csv file
*/
parse(csvString: string, config?: ParseConfig): ParseResult;
/**
* Parse single file or multiple files
*/
parseFiles(input: string | string[] | FileObject | FileObject[], config?: ParseConfig): ParseResult;
/**
* Unparses javascript data objects and returns a csv string
@@ -86,6 +91,11 @@ declare namespace BabyParse {
data: string | Array<any>;
}
interface FileObject {
file: string
config?: ParseConfig
}
interface ParseError {
type: string; // A generalization of the error
code: string; // Standardized error code
+88
View File
@@ -0,0 +1,88 @@
/// <reference path="backlog-js.d.ts" />
import * as backlogjs from 'backlog-js';
const host = 'example.backlog.jp';
const apiKey = 'apiKey';
const clientId = 'clientId';
const clientSecret = 'clientSecret';
const redirectUri = 'redirectUri';
const state = 'state';
const code = 'code';
const refreshToken = 'refreshToken';
const configure = { host, apiKey }
const credentials = { clientId, clientSecret }
const oauth2 = new backlogjs.OAuth2(credentials);
oauth2.getAuthorizationURL({ host, redirectUri, state });
oauth2.getAccessToken({ host, code, redirectUri }).then(data => {}).catch(err => {});
oauth2.refreshAccessToken({ host, refreshToken }).then(data => {}).catch(err => {});
const backlog = new backlogjs.Backlog(configure);
backlog.getSpace().then(data => { }).catch(err => { });
backlog.getSpaceActivities({
activityTypeId: [
backlogjs.Option.ActivityType.IssueCreated,
backlogjs.Option.ActivityType.IssueUpdated
],
minId: 1,
maxId: 2,
count: 3,
order: "asc"
}).then(data => { }).catch(err => { });
backlog.getSpaceDiskUsage().then(data => { }).catch(err => { });
backlog.getSpaceIcon().then(data => { }).catch(err => { });
backlog.postSpaceAttachment(new FormData()).then(data => { }).catch(err => { });
backlog.getUsers().then(data => { }).catch(err => { });
backlog.getUser(1).then(data => { }).catch(err => { });
backlog.postUser({
userId: 'string',
password: 'string',
name: 'string',
mailAddress: 'string',
roleType: backlogjs.Option.User.RoleType.Admin
}).then(data => { }).catch(err => { });
backlog.patchUser(1, {
password: 'string',
name: 'string',
mailAddress: 'string',
roleType: backlogjs.Option.User.RoleType.Admin
}).then(data => { }).catch(err => { });
backlog.deleteUser(1).then(data => { }).catch(err => { });
backlog.getMyself().then(data => { }).catch(err => { });
backlog.getUserActivities(1, {
activityTypeId: [
backlogjs.Option.ActivityType.IssueCreated,
backlogjs.Option.ActivityType.IssueUpdated
],
minId: 1,
maxId: 2,
count: 3,
order: "asc"
}).then(data => { }).catch(err => { });
backlog.getUserStars(1, {
minId: 1,
maxId: 2,
count: 3,
order: "asc"
}).then(data => { }).catch(err => { });
backlog.getUserStarsCount(1, {
since: 'YYYY-MM-DD',
until: 'YYYY-MM-DD'
}).then(data => { }).catch(err => { });
backlog.getRecentlyViewedIssues({
order: 'asc',
offset: 1,
count: 2
}).then(data => { }).catch(err => { });
backlog.getRecentlyViewedProjects({
order: 'asc',
offset: 1,
count: 2
}).then(data => { }).catch(err => { });
backlog.getRecentlyViewedWikis({
order: 'asc',
offset: 1,
count: 2
}).then(data => { }).catch(err => { });
backlog.getUserIcon(1).then(data => {}).catch(err => {});
+695
View File
@@ -0,0 +1,695 @@
// Type definitions for backlog-js 0.9.0
// Project: https://github.com/nulab/backlog-js
// Definitions by: Yuichi Watanabe <https://github.com/vvatanabe>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../isomorphic-fetch/isomorphic-fetch.d.ts" />
/// <reference path="../node_modules/typescript/lib/lib.es6.d.ts" />
declare module 'backlog-js' {
class Request {
private configure;
constructor(configure: {
host: string;
apiKey?: string;
accessToken?: string;
timeout?: number;
});
get<T>(path: string, params?: any): Promise<T>;
post<T>(path: string, params?: any): Promise<T>;
put<T>(path: string, params: any): Promise<T>;
patch<T>(path: string, params: any): Promise<T>;
delete<T>(path: string, params?: any): Promise<T>;
request(options: {
method: string;
path: string;
params?: Params | FormData;
}): Promise<IResponse>;
checkStatus(response: IResponse): Promise<IResponse>;
parseJSON<T>(response: IResponse): Promise<T>;
private toFormData(params);
private toQueryString(params);
webAppBaseURL: string;
restBaseURL: string;
}
type Params = {
[index: string]: number | string | number[] | string[];
};
export class Backlog extends Request {
constructor(configure: {
host: string;
apiKey?: string;
accessToken?: string;
timeout?: number;
});
getSpace(): Promise<any>;
getSpaceActivities(params: Option.Space.GetActivitiesParams): Promise<any>;
getSpaceNotification(): Promise<any>;
putSpaceNotification(params: Option.Space.PutSpaceNotificationParams): Promise<any>;
getSpaceDiskUsage(): Promise<any>;
getSpaceIcon(): Promise<Entity.File.FileData>;
postSpaceAttachment(form: FormData): Promise<IResponse>;
getUsers(): Promise<any>;
getUser(userId: number): Promise<any>;
postUser(params: Option.User.PostUserParams): Promise<any>;
patchUser(userId: number, params: Option.User.PatchUserParams): Promise<any>;
deleteUser(userId: number): Promise<any>;
getMyself(): Promise<any>;
getUserActivities(userId: number, params: Option.User.GetUserActivitiesParams): Promise<any>;
getUserStars(userId: number, params: Option.User.GetUserStarsParams): Promise<any>;
getUserStarsCount(userId: number, params: Option.User.GetUserStarsCountParams): Promise<any>;
getRecentlyViewedIssues(params: Option.User.GetRecentlyViewedParams): Promise<any>;
getRecentlyViewedProjects(params: Option.User.GetRecentlyViewedParams): Promise<any>;
getRecentlyViewedWikis(params: Option.User.GetRecentlyViewedParams): Promise<any>;
getUserIcon(userId: number): Promise<Entity.File.FileData>;
getGroups(params: Option.Group.GetGroupsParams): Promise<any>;
postGroups(params: Option.Group.PostGroupsParams): Promise<any>;
getGroup(groupId: number): Promise<any>;
patchGroup(groupId: number, params: Option.Group.PatchGroupParams): Promise<any>;
deleteGroup(groupId: number): Promise<any>;
getStatuses(): Promise<any>;
getResolutions(): Promise<any>;
getPriorities(): Promise<any>;
postProject(params: Option.Project.PostProjectParams): Promise<any>;
getProjects(params?: Option.Project.GetProjectsParams): Promise<any>;
getProject(projectIdOrKey: string): Promise<any>;
patchProject(projectIdOrKey: string, params: Option.Project.PatchProjectParams): Promise<any>;
deleteProject(projectIdOrKey: string): Promise<any>;
getProjectActivities(projectIdOrKey: string, params: Option.Space.GetActivitiesParams): Promise<any>;
getProjectUsers(projectIdOrKey: string): Promise<any>;
deleteProjectUsers(projectIdOrKey: string, params: Option.Project.DeleteProjectUsersParams): Promise<any>;
postProjectAdministrators(projectIdOrKey: string, params: Option.Project.PostProjectAdministrators): Promise<any>;
getProjectAdministrators(projectIdOrKey: string): Promise<any>;
deleteProjectAdministrators(projectIdOrKey: string, params: Option.Project.DeleteProjectAdministrators): Promise<any>;
getIssueTypes(projectIdOrKey: string): Promise<any>;
postIssueType(projectIdOrKey: string, params: Option.Project.PostIssueTypeParams): Promise<any>;
patchIssueType(projectIdOrKey: string, id: number, params: Option.Project.PatchIssueTypeParams): Promise<any>;
deleteIssueType(projectIdOrKey: string, id: number, params: Option.Project.DeleteIssueTypeParams): Promise<any>;
getCategories(projectIdOrKey: string): Promise<any>;
postCategories(projectIdOrKey: string, params: Option.Project.PostCategoriesParams): Promise<any>;
patchCategories(projectIdOrKey: string, id: number, params: Option.Project.PatchCategoriesParams): Promise<any>;
deleteCategories(projectIdOrKey: string, id: number): Promise<any>;
getVersions(projectIdOrKey: string): Promise<any>;
postVersions(projectIdOrKey: string, params: Option.Project.PostVersionsParams): Promise<any>;
patchVersions(projectIdOrKey: string, id: number, params: Option.Project.PatchVersionsParams): Promise<any>;
deleteVersions(projectIdOrKey: string, id: number): Promise<any>;
getCustomFields(projectIdOrKey: string): Promise<any>;
postCustomField(projectIdOrKey: string, params: Option.Project.PostCustomFieldParams | Option.Project.PostCustomFieldWithNumericParams | Option.Project.PostCustomFieldWithDateParams | Option.Project.PostCustomFieldWithListParams): Promise<any>;
patchCustomField(projectIdOrKey: string, id: number, params: Option.Project.PatchCustomFieldParams | Option.Project.PatchCustomFieldWithNumericParams | Option.Project.PatchCustomFieldWithDateParams | Option.Project.PatchCustomFieldWithListParams): Promise<any>;
deleteCustomField(projectIdOrKey: string, id: number): Promise<any>;
postCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise<any>;
patchCustomFieldItem(projectIdOrKey: string, id: number, itemId: number, params: Option.Project.PatchCustomFieldItemParams): Promise<any>;
deleteCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise<any>;
getSharedFiles(projectIdOrKey: string, path: string, params: Option.Project.GetSharedFilesParams): Promise<any>;
getProjectsDiskUsage(projectIdOrKey: string): Promise<any>;
getWebhooks(projectIdOrKey: string): Promise<any>;
postWebhook(projectIdOrKey: string, params: Option.Project.PostWebhookParams): Promise<any>;
getWebhook(projectIdOrKey: string, webhookId: string): Promise<any>;
patchWebhook(projectIdOrKey: string, webhookId: string, params: Option.Project.PatchWebhookParams): Promise<any>;
deleteWebhook(projectIdOrKey: string, webhookId: string): Promise<any>;
postIssue(params: Option.Issue.PostIssueParams): Promise<any>;
patchIssue(issueIdOrKey: string, params: Option.Issue.PatchIssueParams): Promise<any>;
getIssues(params?: Option.Issue.GetIssuesParams): Promise<any>;
getIssue(issueIdOrKey: string): Promise<any>;
getIssuesCount(params?: Option.Issue.GetIssuesParams): Promise<any>;
deleteIssuesCount(issueIdOrKey: string): Promise<any>;
getIssueComments(issueIdOrKey: string, params: Option.Issue.GetIssueCommentsParams): Promise<any>;
postIssueComments(issueIdOrKey: string, params: Option.Issue.PostIssueCommentsParams): Promise<any>;
getIssueCommentsCount(issueIdOrKey: string): Promise<any>;
getIssueComment(issueIdOrKey: string, commentId: number): Promise<any>;
patchIssueComment(issueIdOrKey: string, commentId: number, params: Option.Issue.PatchIssueCommentParams): Promise<any>;
getIssueCommentNotifications(issueIdOrKey: string, commentId: number): Promise<any>;
postIssueCommentNotifications(issueIdOrKey: string, commentId: number, prams: Option.Issue.IssueCommentNotifications): Promise<any>;
getIssueAttachments(issueIdOrKey: string): Promise<any>;
deleteIssueAttachment(issueIdOrKey: string, attachmentId: string): Promise<any>;
getIssueSharedFiles(issueIdOrKey: string): Promise<any>;
linkIssueSharedFiles(issueIdOrKey: string, params: Option.Issue.LinkIssueSharedFilesParams): Promise<any>;
unlinkIssueSharedFile(issueIdOrKey: string, id: number): Promise<any>;
getWikis(projectIdOrKey: number): Promise<any>;
getWikisCount(projectIdOrKey: number): Promise<any>;
getWikisTags(projectIdOrKey: number): Promise<any>;
postWiki(params: Option.Wiki.PostWikiParams): Promise<any>;
getWiki(wikiId: number): Promise<any>;
patchWiki(wikiId: number, params: Option.Wiki.PatchWikiParams): Promise<any>;
deleteWiki(wikiId: number, mailNotify: boolean): Promise<any>;
getWikisAttachments(wikiId: number): Promise<any>;
postWikisAttachments(wikiId: number, attachmentId: number[]): Promise<any>;
deleteWikisAttachments(wikiId: number, attachmentId: number): Promise<any>;
getWikisSharedFiles(wikiId: number): Promise<any>;
linkWikisSharedFiles(wikiId: number, fileId: number[]): Promise<any>;
unlinkWikisSharedFiles(wikiId: number, id: number): Promise<any>;
getWikisHistory(wikiId: number, params: Option.Wiki.GetWikisHistoryParams): Promise<any>;
getWikisStars(wikiId: number): Promise<any>;
postStar(params: Option.Project.PostStarParams): Promise<any>;
getNotifications(params: Option.Notification.GetNotificationsParams): Promise<any>;
getNotificationsCount(params: Option.Notification.GetNotificationsCountParams): Promise<any>;
resetNotificationsMarkAsRead(): Promise<any>;
markAsReadNotification(id: number): Promise<any>;
getGitRepositories(projectIdOrKey: string): Promise<any>;
getGitRepository(projectIdOrKey: string, repoIdOrName: string): Promise<any>;
getPullRequests(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise<any>;
getPullRequestsCount(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise<any>;
postPullRequest(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.PostPullRequestParams): Promise<any>;
getPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number): Promise<any>;
patchPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PatchPullRequestParams): Promise<any>;
getPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.GetPullRequestCommentsParams): Promise<any>;
postPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PostPullRequestCommentsParams): Promise<any>;
getPullRequestCommentsCount(projectIdOrKey: string, repoIdOrName: string, number: number): Promise<any>;
patchPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, commentId: number, params: Option.PullRequest.PatchPullRequestCommentsParams): Promise<any>;
getPullRequestAttachments(projectIdOrKey: string, repoIdOrName: string, number: number): Promise<any>;
deletePullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise<any>;
getProjectIcon(projectIdOrKey: string): Promise<Entity.File.FileData>;
getSharedFile(projectIdOrKey: string, sharedFileId: number): Promise<Entity.File.FileData>;
getIssueAttachment(issueIdOrKey: string, attachmentId: number): Promise<Entity.File.FileData>;
getWikiAttachment(wikiId: number, attachmentId: number): Promise<Entity.File.FileData>;
getPullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise<Entity.File.FileData>;
private download(path);
private upload(path, params);
private parseFileData(response);
}
export class OAuth2 {
private credentials;
private timeout;
constructor(credentials: Option.OAuth2.Credentials, timeout?: number);
getAuthorizationURL(options: {
host: string;
redirectUri?: string;
state?: string;
}): string;
getAccessToken(options: {
host: string;
code: string;
redirectUri?: string;
}): Promise<Entity.OAuth2.AccessToken>;
refreshAccessToken(options: {
host: string;
refreshToken: string;
}): Promise<Entity.OAuth2.AccessToken>;
}
import { PassThrough } from 'stream';
export namespace Entity {
export namespace File {
export type FileData = NodeFileData | BrowserFileData;
export interface NodeFileData {
body: PassThrough;
url: string;
filename: string;
}
export interface BrowserFileData {
body: any;
url: string;
blob?: () => Promise<Blob>;
}
}
export namespace OAuth2 {
export interface AccessToken {
access_token: string;
token_type: string;
expires_in: number;
refresh_token: string;
}
}
}
export namespace Option {
export type Order = "asc" | "desc";
export enum ActivityType {
Undefined = -1,
IssueCreated = 1,
IssueUpdated = 2,
IssueCommented = 3,
IssueDeleted = 4,
WikiCreated = 5,
WikiUpdated = 6,
WikiDeleted = 7,
FileAdded = 8,
FileUpdated = 9,
FileDeleted = 10,
SvnCommitted = 11,
GitPushed = 12,
GitRepositoryCreated = 13,
IssueMultiUpdated = 14,
ProjectUserAdded = 15,
ProjectUserRemoved = 16,
NotifyAdded = 17,
PullRequestAdded = 18,
PullRequestUpdated = 19,
PullRequestCommented = 20,
PullRequestMerged = 21,
}
export namespace Notification {
export interface GetNotificationsParams {
minId?: number;
maxId?: number;
count?: number;
order?: Order;
}
export interface GetNotificationsCountParams {
alreadyRead: boolean;
resourceAlreadyRead: boolean;
}
}
export namespace Space {
export interface GetActivitiesParams {
activityTypeId?: ActivityType[];
minId?: number;
maxId?: number;
count?: number;
order?: Order;
}
export interface PutSpaceNotificationParams {
content: string;
}
}
export namespace User {
export interface PostUserParams {
userId: string;
password: string;
name: string;
mailAddress: string;
roleType: RoleType;
}
export interface PatchUserParams {
password?: string;
name?: string;
mailAddress?: string;
roleType?: RoleType;
}
export enum RoleType {
Admin = 1,
User = 2,
Reporter = 3,
Viewer = 4,
GuestReporter = 5,
GuestViewer = 6,
}
export interface GetUserActivitiesParams {
activityTypeId?: ActivityType[];
minId?: number;
maxId?: number;
count?: number;
order?: Order;
}
export interface GetUserStarsParams {
minId?: number;
maxId?: number;
count?: number;
order?: Order;
}
export interface GetUserStarsCountParams {
since?: string;
until?: string;
}
export interface GetRecentlyViewedParams {
order?: Order;
offset?: number;
count?: number;
}
}
export namespace Group {
export interface GetGroupsParams {
order?: Order;
offset?: number;
count?: number;
}
export interface PostGroupsParams {
name: string;
members?: string[];
}
export interface PatchGroupParams {
name?: string;
members?: string[];
}
}
export namespace Project {
export type TextFormattingRule = "backlog" | "markdown";
export interface PostProjectParams {
name: string;
key: string;
chartEnabled: boolean;
projectLeaderCanEditProjectLeader?: boolean;
subtaskingEnabled: boolean;
textFormattingRule: TextFormattingRule;
}
export interface PatchProjectParams {
name?: string;
key?: string;
chartEnabled?: boolean;
subtaskingEnabled?: boolean;
projectLeaderCanEditProjectLeader?: boolean;
textFormattingRule?: TextFormattingRule;
archived?: boolean;
}
export interface GetProjectsParams {
archived?: boolean;
all?: boolean;
}
export interface DeleteProjectUsersParams {
userId: number;
}
export interface PostProjectAdministrators {
userId: number;
}
export interface DeleteProjectAdministrators {
userId: number;
}
export type IssueTypeColor = "#e30000" | "#990000" | "#934981" | "#814fbc" | "#2779ca" | "#007e9a" | "#7ea800" | "#ff9200" | "#ff3265" | "#666665";
export interface PostIssueTypeParams {
name: string;
color: IssueTypeColor;
}
export interface PatchIssueTypeParams {
name?: string;
color?: IssueTypeColor;
}
export interface DeleteIssueTypeParams {
substituteIssueTypeId: number;
}
export interface PostCategoriesParams {
name: string;
}
export interface PatchCategoriesParams {
name: string;
}
export interface PostVersionsParams {
name: string;
description: string;
startDate: string;
releaseDueDate: string;
}
export interface PatchVersionsParams {
name: string;
description?: string;
startDate?: string;
releaseDueDate?: string;
archived?: boolean;
}
export interface PostCustomFieldParams {
typeId: FieldType;
name: string;
applicableIssueTypes?: number[];
description?: string;
required?: boolean;
}
export interface PostCustomFieldWithNumericParams extends PostCustomFieldParams {
min?: number;
max?: number;
initialValue?: number;
unit?: string;
}
export interface PostCustomFieldWithDateParams extends PostCustomFieldParams {
min?: string;
max?: string;
initialValueType?: number;
initialDate?: string;
initialShift?: number;
}
export interface PostCustomFieldWithListParams extends PostCustomFieldParams {
items?: string[];
allowInput?: boolean;
allowAddItem?: boolean;
}
export interface PatchCustomFieldParams {
name?: string;
applicableIssueTypes?: number[];
description?: string;
required?: boolean;
}
export interface PatchCustomFieldWithNumericParams extends PatchCustomFieldParams {
min?: number;
max?: number;
initialValue?: number;
unit?: string;
}
export interface PatchCustomFieldWithDateParams extends PatchCustomFieldParams {
min?: string;
max?: string;
initialValueType?: number;
initialDate?: string;
initialShift?: number;
}
export interface PatchCustomFieldWithListParams extends PatchCustomFieldParams {
items?: string[];
allowInput?: boolean;
allowAddItem?: boolean;
}
export interface PostCustomFieldItemParams {
name: string;
}
export interface PatchCustomFieldItemParams {
name: string;
}
export interface GetSharedFilesParams {
order?: Order;
offset?: number;
count?: number;
}
export interface PostWebhookParams {
name?: string;
description?: string;
hookUrl?: string;
allEvent?: boolean;
activityTypeIds?: number[];
}
export interface PatchWebhookParams {
name?: string;
description?: string;
hookUrl?: string;
allEvent?: boolean;
activityTypeIds?: number[];
}
export enum FieldType {
Text = 1,
TextArea = 2,
Numeric = 3,
Date = 4,
SingleList = 5,
MultipleList = 6,
CheckBox = 7,
Radio = 8,
}
export interface PostStarParams {
issueId?: number;
commentId?: number;
wikiId?: number;
pullRequestId?: number;
pullRequestCommentId?: number;
}
}
export namespace Issue {
export interface PostIssueParams {
projectId: number;
summary: string;
priorityId: number;
issueTypeId: number;
parentIssueId?: number;
description?: string;
startDate?: string;
dueDate?: string;
estimatedHours?: number;
actualHours?: number;
categoryId?: number[];
versionId?: number[];
milestoneId?: number[];
assigneeId?: number;
notifiedUserId?: number[];
attachmentId?: number[];
[customField_: string]: any;
}
export interface PatchIssueParams {
summary?: string;
parentIssueId?: number;
description?: string;
statusId?: number;
resolutionId?: number;
startDate?: string;
dueDate?: string;
estimatedHours?: number;
actualHours?: number;
issueTypeId?: number;
categoryId?: number[];
versionId?: number[];
milestoneId?: number[];
priorityId?: number;
assigneeId?: number;
notifiedUserId?: number[];
attachmentId?: number[];
comment?: string;
[customField_: string]: any;
}
export interface GetIssuesParams {
projectId?: number[];
issueTypeId?: number[];
categoryId?: number[];
versionId?: number[];
milestoneId?: number[];
statusId?: number[];
priorityId?: number[];
assigneeId?: number[];
createdUserId?: number[];
resolutionId?: number[];
parentChild?: ParentChildType;
attachment?: boolean;
sharedFile?: boolean;
sort?: SortKey;
order?: Order;
offset?: number;
count?: number;
createdSince?: string;
createdUntil?: string;
updatedSince?: string;
updatedUntil?: string;
startDateSince?: string;
startDateUntil?: string;
dueDateSince?: string;
dueDateUntil?: string;
id?: number[];
parentIssueId?: number[];
keyword: string;
[customField_: string]: any;
}
export enum ParentChildType {
All = 0,
NotChild = 1,
Child = 2,
NotChildNotParent = 3,
Parent = 4,
}
export type SortKey = "issueType" | "category" | "version" | "milestone" | "summary" | "status" | "priority" | "attachment" | "sharedFile" | "created" | "createdUser" | "updated" | "updatedUser" | "assignee" | "startDate" | "dueDate" | "estimatedHours" | "actualHours" | "childIssue";
export interface GetIssueCommentsParams {
minId?: number;
maxId?: number;
count?: number;
order?: Order;
}
export interface PostIssueCommentsParams {
content: string;
notifiedUserId?: number[];
attachmentId?: number[];
}
export interface PatchIssueCommentParams {
content: string;
}
export interface IssueCommentNotifications {
notifiedUserId: number[];
}
export interface LinkIssueSharedFilesParams {
fileId: number[];
}
}
export namespace PullRequest {
export interface GetPullRequestsParams {
statusId?: number[];
assigneeId?: number[];
issueId?: number[];
createdUserId?: number[];
offset?: number;
count?: number;
}
export interface PostPullRequestParams {
summary: string;
description: string;
base: string;
branch: string;
issueId?: number;
assigneeId?: number;
notifiedUserId?: number[];
attachmentId?: number[];
}
export interface PatchPullRequestParams {
summary?: string;
description?: string;
issueId?: number;
assigneeId?: number;
notifiedUserId?: number[];
comment?: string[];
}
export interface GetPullRequestCommentsParams {
minId?: number;
maxId?: number;
count?: number;
order?: Order;
}
export interface PostPullRequestCommentsParams {
content: string;
notifiedUserId?: number[];
}
export interface PatchPullRequestCommentsParams {
content: string;
}
}
export namespace Wiki {
export interface PostWikiParams {
projectId: number;
name: string;
content: string;
mailNotify?: boolean;
}
export interface PatchWikiParams {
name?: string;
content?: string;
mailNotify?: boolean;
}
export interface GetWikisHistoryParams {
minId?: number;
maxId?: number;
count?: number;
order?: Order;
}
}
export namespace OAuth2 {
export interface Credentials {
clientId: string;
clientSecret: string;
}
}
}
export namespace Error {
export class BacklogError extends global.Error {
private _name;
private _url;
private _status;
private _body;
private _response;
constructor(name: BacklogErrorNameType, response: IResponse, body?: {
errors: BacklogErrorMessage[];
});
name: BacklogErrorNameType;
url: string;
status: number;
body: {
errors: BacklogErrorMessage[];
};
response: IResponse;
}
export class BacklogApiError extends BacklogError {
constructor(response: IResponse, body?: {
errors: BacklogErrorMessage[];
});
}
export class BacklogAuthError extends BacklogError {
constructor(response: IResponse, body?: {
errors: BacklogErrorMessage[];
});
}
export class UnexpectedError extends BacklogError {
constructor(response: IResponse);
}
export interface BacklogErrorMessage {
message: string;
code: number;
errorInfo: string;
moreInfo: string;
}
export type BacklogErrorNameType = 'BacklogApiError' | 'BacklogAuthError' | 'UnexpectedError';
}
}
+24
View File
@@ -0,0 +1,24 @@
/// <reference path="./base16.d.ts" />
import * as base16 from 'base16';
const colorScheme: base16.ColorScheme = base16.solarized
const scheme: string = colorScheme.scheme
const author: string = colorScheme.author
const base00: string = colorScheme.base00
const base01: string = colorScheme.base01
const base02: string = colorScheme.base02
const base03: string = colorScheme.base03
const base04: string = colorScheme.base04
const base05: string = colorScheme.base05
const base06: string = colorScheme.base06
const base07: string = colorScheme.base07
const base08: string = colorScheme.base08
const base09: string = colorScheme.base09
const base0A: string = colorScheme.base0A
const base0B: string = colorScheme.base0B
const base0C: string = colorScheme.base0C
const base0D: string = colorScheme.base0D
const base0E: string = colorScheme.base0E
const base0F: string = colorScheme.base0F
+70
View File
@@ -0,0 +1,70 @@
// Type definitions for base16-js 1.0.0
// Project: https://github.com/gaearon/base16-js
// Definitions by: Alec Hill <https://github.com/alechill>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'base16' {
/**
* Type describing a syntax highlighting scheme as a JS object, as used in redux dev tools
* Based on https://github.com/chriskempson/base16
*/
export interface ColorScheme {
scheme: string
author: string
base00: string
base01: string
base02: string
base03: string
base04: string
base05: string
base06: string
base07: string
base08: string
base09: string
base0A: string
base0B: string
base0C: string
base0D: string
base0E: string
base0F: string
}
// predefined schemes...
export var threezerotwofour: ColorScheme
export var apathy: ColorScheme
export var ashes: ColorScheme
export var atelierDune: ColorScheme
export var atelierForest: ColorScheme
export var atelierHeath: ColorScheme
export var atelierLakeside: ColorScheme
export var atelierSeaside: ColorScheme
export var bespin: ColorScheme
export var brewer: ColorScheme
export var bright: ColorScheme
export var chalk: ColorScheme
export var codeschool: ColorScheme
export var colors: ColorScheme
export var eighties: ColorScheme
export var embers: ColorScheme
export var flat: ColorScheme
export var google: ColorScheme
export var grayscale: ColorScheme
export var greenscreen: ColorScheme
export var harmonic: ColorScheme
export var hopscotch: ColorScheme
export var isotope: ColorScheme
export var marrakesh: ColorScheme
export var monokai: ColorScheme
export var ocean: ColorScheme
export var paraiso: ColorScheme
export var pop: ColorScheme
export var railscasts: ColorScheme
export var shapeshifter: ColorScheme
export var solarized: ColorScheme
export var summerfruit: ColorScheme
export var tomorrow: ColorScheme
export var tube: ColorScheme
export var twilight: ColorScheme
}
+10
View File
@@ -0,0 +1,10 @@
/// <reference path="bit-array.d.ts" />
import BitArray = require("bit-array");
const a = new BitArray(32);
a.set(0, true);
a.set(31, true);
a.toString(); // "10000000000000000000000000000001"
a.get(1); // false
a.get(31); // true
+1
View File
@@ -0,0 +1 @@
--noImplicitAny --module commonjs
+105
View File
@@ -0,0 +1,105 @@
// Type definitions for bit-array v0.2.2
// Project: https://github.com/bramstein/bit-array
// Definitions by: Mudkip <https://github.com/mudkipme>
// Definitions: https://github.com/mudkipme/DefinitelyTyped
declare module "bit-array" {
class BitArray {
/**
* Creates a new empty BitArray with the given length or initialises the BitArray with the given hex representation.
*/
constructor(size: number, hex?: string);
/**
* Returns the total number of bits in this BitArray.
*/
size(): number;
/**
* Sets the bit at index to a value (boolean.)
*/
set(index: number, value: boolean): BitArray;
/**
* Toggles the bit at index. If the bit is on, it is turned off. Likewise, if the bit is off it is turned on.
*/
toggle(index: number): BitArray;
/**
* Returns the value of the bit at index (boolean.)
*/
get(index: number): boolean;
/**
* Resets the BitArray so that it is empty and can be re-used.
*/
reset(): BitArray;
/**
* Returns a copy of this BitArray.
*/
copy(): BitArray;
/**
* Returns true if this BitArray equals another. Two BitArrays are considered
* equal if both have the same length and bit pattern.
*/
equals(x: BitArray): boolean;
/**
* Returns the JSON representation of this BitArray.
*/
toJSON(): string;
/**
* Returns a string representation of the BitArray with bits
* in mathemetical order.
*/
toBinaryString(): string;
/**
* Returns a hexadecimal string representation of the BitArray
* with bits in logical order.
*/
toHexString(): string;
/**
* Returns a string representation of the BitArray with bits
* in logical order.
*/
toString(): string;
/**
* Convert the BitArray to an Array of boolean values (slow).
*/
toArray(): boolean[];
/**
* Returns the total number of bits set to one in this BitArray.
*/
count(): number;
/**
* Inverts this BitArray.
*/
not(): BitArray;
/**
* Bitwise OR on the values of this BitArray using BitArray x.
*/
or(x: BitArray): BitArray;
/**
* Bitwise AND on the values of this BitArray using BitArray x.
*/
and(x: BitArray): BitArray;
/**
* Bitwise XOR on the values of this BitArray using BitArray x.
*/
xor(x: BitArray): BitArray;
}
export = BitArray;
}
+773
View File
@@ -0,0 +1,773 @@
///<reference path="blessed.d.ts" />
import * as blessed from 'blessed';
let screen: blessed.Widgets.Screen = null;
// https://github.com/chjj/blessed/blob/master/test/widget-autopad.js
screen = blessed.screen({
dump: __dirname + '/logs/autopad.log',
smartCSR: true,
autoPadding: true,
warnings: true
});
var box1 = blessed.box({
parent: screen,
top: 'center',
left: 'center',
width: 20,
height: 10,
border: 'line'
});
var box2 = blessed.box({
parent: box1,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line'
});
screen.key('q', function() {
return screen.destroy();
});
screen.render();
// https://github.com/chjj/blessed/blob/master/test/widget-bigtext.js
screen = blessed.screen({
dump: __dirname + '/logs/bigtext.log',
smartCSR: true,
warnings: true
});
var box = blessed.bigtext({
parent: screen,
content: 'Hello',
shrink: true,
width: '80%',
// height: '80%',
height: 'shrink',
// width: 'shrink',
border: 'line',
fch: ' ',
ch: '\u2592',
style: {
fg: 'red',
bg: 'blue',
bold: false
}
});
screen.key('q', function() {
return screen.destroy();
});
screen.render();
// https://github.com/chjj/blessed/blob/master/test/widget-csr.js
screen = blessed.screen({
dump: __dirname + '/logs/csr.log',
smartCSR: true,
warnings: true
});
var lorem = require('fs').readFileSync(__dirname + '/git.diff', 'utf8');
var cleanSides = screen.cleanSides;
function expectClean(value: any) {
screen.cleanSides = function(el: blessed.widget.Element) {
var ret = cleanSides.apply(this, arguments);
if (ret !== value) {
throw new Error('Failed. Expected '
+ value + ' from cleanSides. Got '
+ ret + '.');
}
return ret;
};
}
var btext = blessed.box({
parent: screen,
left: 'center',
top: 'center',
width: '80%',
height: '80%',
style: {
bg: 'green'
},
border: 'line',
content: 'CSR should still work.'
});
let _oscroll = btext.scroll;
btext.scroll = function(offset, always) {
expectClean(true);
return _oscroll(offset, always);
};
var text = blessed.scrollabletext({
parent: screen,
content: lorem,
border: 'line',
left: 'center',
top: 'center',
draggable: true,
width: '50%',
height: '50%',
mouse: true,
keys: true,
vi: true
});
_oscroll = text.scroll;
text.scroll = function(offset, always) {
var el = this;
var value = true;
if (el.left < 0) value = true;
if (el.top < 0) value = false;
if (el.left + el.width > screen.width) value = true;
if (el.top + el.height > screen.height) value = false;
expectClean(value);
return _oscroll(offset, always);
};
text.focus();
screen.key('q', function() {
return screen.destroy();
});
screen.render();
// https://github.com/chjj/blessed/blob/master/test/widget-dock-noborder.js
screen = blessed.screen({
dump: __dirname + '/logs/dock.log',
smartCSR: true,
dockBorders: true,
warnings: true
});
blessed.box({
parent: screen,
left: -1,
top: -1,
width: '50%+1',
height: '50%+1',
border: 'line',
content: 'Foo'
});
blessed.box({
parent: screen,
left: '50%-1',
top: -1,
width: '50%+3',
height: '50%+1',
content: 'Bar',
border: 'line'
});
blessed.box({
parent: screen,
left: -1,
top: '50%-1',
width: '50%+1',
height: '50%+3',
border: 'line',
content: 'Foo'
});
blessed.listtable({
parent: screen,
left: '50%-1',
top: '50%-1',
width: '50%+3',
height: '50%+3',
border: 'line',
align: 'center',
tags: true,
keys: true,
vi: true,
mouse: true,
style: {
header: {
fg: 'blue',
bold: true
},
cell: {
fg: 'magenta',
selected: {
bg: 'blue'
}
}
},
data: [
[ 'Animals', 'Foods', 'Times', 'Numbers' ],
[ 'Elephant', 'Apple', '1:00am', 'One' ],
[ 'Bird', 'Orange', '2:15pm', 'Two' ],
[ 'T-Rex', 'Taco', '8:45am', 'Three' ],
[ 'Mouse', 'Cheese', '9:05am', 'Four' ]
]
}).focus();
screen.key('q', function() {
return screen.destroy();
});
screen.render();
// https://raw.githubusercontent.com/chjj/blessed/master/example/simple-form.js
var form = blessed.form({
parent: screen,
keys: true,
left: 0,
top: 0,
width: 30,
height: 4,
bg: 'green',
content: 'Submit or cancel?'
});
var submit = blessed.button({
parent: form,
mouse: true,
keys: true,
padding: {
left: 1,
right: 1
},
left: 10,
top: 2,
shrink: true,
name: 'submit',
content: 'submit',
style: {
bg: 'blue',
focus: {
bg: 'red'
},
hover: {
bg: 'red'
}
}
});
var cancel = blessed.button({
parent: form,
mouse: true,
keys: true,
padding: {
left: 1,
right: 1
},
left: 20,
top: 2,
shrink: true,
name: 'cancel',
content: 'cancel',
style: {
bg: 'blue',
focus: {
bg: 'red'
},
hover: {
bg: 'red'
}
}
});
// https://github.com/chjj/blessed/blob/master/test/widget-layout.js
screen = blessed.screen({
dump: __dirname + '/logs/layout.log',
smartCSR: true,
autoPadding: true,
warnings: true
});
var layout = blessed.layout({
parent: screen,
top: 'center',
left: 'center',
width: '50%',
height: '50%',
border: 'line',
layout: process.argv[2] === 'grid' ? 'grid' : 'inline',
style: {
bg: 'red',
border: {
fg: 'blue'
}
}
});
var box1 = blessed.box({
parent: layout,
top: 'center',
left: 'center',
width: 20,
height: 10,
border: 'line',
content: '1'
});
var box2 = blessed.box({
parent: layout,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line',
content: '2'
});
var box3 = blessed.box({
parent: layout,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line',
content: '3'
});
var box4 = blessed.box({
parent: layout,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line',
content: '4'
});
var box5 = blessed.box({
parent: layout,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line',
content: '5'
});
var box6 = blessed.box({
parent: layout,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line',
content: '6'
});
var box7 = blessed.box({
parent: layout,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line',
content: '7'
});
var box8 = blessed.box({
parent: layout,
top: 'center',
left: 'center',
width: 20,
height: 10,
border: 'line',
content: '8'
});
var box9 = blessed.box({
parent: layout,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line',
content: '9'
});
var box10 = blessed.box({
parent: layout,
top: 'center',
left: 'center',
width: 20,
height: 10,
border: 'line',
content: '10'
});
var box11 = blessed.box({
parent: layout,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line',
content: '11'
});
var box12 = blessed.box({
parent: layout,
top: 'center',
left: 'center',
width: 20,
height: 10,
border: 'line',
content: '12'
});
if (process.argv[2] !== 'grid') {
for (var i = 0; i < 10; i++) {
blessed.box({
parent: layout,
// width: i % 2 === 0 ? 10 : 20,
// height: i % 2 === 0 ? 5 : 10,
width: Math.random() > 0.5 ? 10 : 20,
height: Math.random() > 0.5 ? 5 : 10,
border: 'line',
content: (i + 1 + 12) + ''
});
}
}
screen.key('q', function() {
return screen.destroy();
});
screen.render();
// https://github.com/chjj/blessed/blob/master/test/widget-form.js
screen = blessed.screen({
dump: __dirname + '/logs/form.log',
warnings: true
});
type FormData = {
radio1: boolean;
radio2: boolean;
text: string;
check: boolean;
};
var form2 = blessed.form<FormData>({
parent: screen,
mouse: true,
keys: true,
vi: true,
left: 0,
top: 0,
width: '100%',
//height: 12,
style: {
bg: 'green',
border: {
inverse: true
},
scrollbar: {
inverse: true
}
},
content: 'foobar',
scrollable: true,
scrollbar: {
ch: ' '
}
//alwaysScroll: true
});
form2.on('submit', (data) => {
output.setContent(JSON.stringify(data, null, 2));
screen.render();
});
form2.key('d', function() {
form2.scroll(1, true);
screen.render();
});
form2.key('u', function() {
form2.scroll(-1, true);
screen.render();
});
var set = blessed.radioset({
parent: form2,
left: 1,
top: 1,
shrink: true,
//padding: 1,
//content: 'f',
style: {
bg: 'magenta'
}
});
var radio1 = blessed.radiobutton({
parent: set,
mouse: true,
keys: true,
shrink: true,
style: {
bg: 'magenta'
},
height: 1,
left: 0,
top: 0,
name: 'radio1',
content: 'radio1'
});
var radio2 = blessed.radiobutton({
parent: set,
mouse: true,
keys: true,
shrink: true,
style: {
bg: 'magenta'
},
height: 1,
left: 15,
top: 0,
name: 'radio2',
content: 'radio2'
});
var text2 = blessed.textbox({
parent: form2,
mouse: true,
keys: true,
style: {
bg: 'blue'
},
height: 1,
width: 20,
left: 1,
top: 3,
name: 'text'
});
text2.on('focus', function() {
text2.readInput();
});
var check = blessed.checkbox({
parent: form2,
mouse: true,
keys: true,
shrink: true,
style: {
bg: 'magenta'
},
height: 1,
left: 28,
top: 1,
name: 'check',
content: 'check'
});
var check2 = blessed.checkbox({
parent: form2,
mouse: true,
keys: true,
shrink: true,
style: {
bg: 'magenta'
},
height: 1,
left: 28,
top: 14,
name: 'foooooooo2',
content: 'foooooooo2'
});
var submit = blessed.button({
parent: form2,
mouse: true,
keys: true,
shrink: true,
padding: {
left: 1,
right: 1
},
left: 29,
top: 3,
name: 'submit',
content: 'submit',
style: {
bg: 'blue',
focus: {
bg: 'red'
}
}
});
submit.on('press', function() {
form2.submit();
});
var box1 = blessed.box({
parent: form2,
left: 1,
top: 10,
height: 10,
width: 10,
content: 'one',
style: {
bg: 'cyan'
}
});
var box2 = blessed.box({
parent: box1,
left: 1,
top: 2,
height: 8,
width: 9,
content: 'two',
style: {
bg: 'magenta'
}
});
var box3 = blessed.box({
parent: box2,
left: 1,
top: 2,
height: 6,
width: 8,
content: 'three',
style: {
bg: 'yellow'
}
});
var box4 = blessed.box({
parent: box3,
left: 1,
top: 2,
height: 4,
width: 7,
content: 'four',
style: {
bg: 'blue'
}
});
var output = blessed.scrollabletext({
parent: form2,
mouse: true,
keys: true,
left: 0,
top: 20,
height: 5,
right: 0,
style: {
bg: 'red'
},
content: 'foobar'
});
var bottom = blessed.line({
parent: form2,
type: 'line',
orientation: 'horizontal',
left: 0,
right: 0,
top: 50,
style: {
fg: 'blue'
}
});
screen.key('q', function() {
return screen.destroy();
});
form2.focus();
form2.submit();
screen.render();
// https://github.com/chjj/blessed/blob/master/test/widget-table.js
screen = blessed.screen({
dump: __dirname + '/logs/table.log',
autoPadding: false,
fullUnicode: true,
warnings: true
});
var DU = '杜';
var JUAN = '鹃';
var table = blessed.table({
//parent: screen,
top: 'center',
left: 'center',
data: null,
border: 'line',
align: 'center',
tags: true,
//width: '80%',
width: 'shrink',
style: {
border: {
fg: 'red'
},
header: {
fg: 'blue',
bold: true
},
cell: {
fg: 'magenta'
}
}
});
var data1 = [
[ 'Animals', 'Foods', 'Times' ],
[ 'Elephant', 'Apple', '1:00am' ],
[ 'Bird', 'Orange', '2:15pm' ],
[ 'T-Rex', 'Taco', '8:45am' ],
[ 'Mouse', 'Cheese', '9:05am' ]
];
data1[1][0] = '{red-fg}' + data1[1][0] + '{/red-fg}';
data1[2][0] += ' (' + DU + JUAN + ')';
var data2 = [
[ 'Animals', 'Foods', 'Times', 'Numbers' ],
[ 'Elephant', 'Apple', '1:00am', 'One' ],
[ 'Bird', 'Orange', '2:15pm', 'Two' ],
[ 'T-Rex', 'Taco', '8:45am', 'Three' ],
[ 'Mouse', 'Cheese', '9:05am', 'Four' ]
];
data2[1][0] = '{red-fg}' + data2[1][0] + '{/red-fg}';
data2[2][0] += ' (' + DU + JUAN + ')';
screen.key('q', function() {
return screen.destroy();
});
table.setData(data2);
screen.append(table);
screen.render();
setTimeout(function() {
table.setData(data1);
screen.render();
}, 3000);
+2812 -1247
View File
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -82,6 +82,7 @@ var voidProm: Promise<void>;
var fooProm: Promise<Foo>;
var barProm: Promise<Bar>;
var barOrVoidProm: Promise<Bar | void>;
var fooOrBarProm: Promise<Foo|Bar>;
var bazProm: Promise<Baz>;
@@ -221,12 +222,12 @@ barProm = fooProm.then((value: Foo) => {
}, (reason: any) => {
return barProm;
});
barProm = fooProm.then((value: Foo) => {
barOrVoidProm = fooProm.then((value: Foo) => {
return bar;
}, (reason: any) => {
return;
});
barProm = fooProm.then((value: Foo) => {
barOrVoidProm = fooProm.then((value: Foo) => {
return bar;
}, (reason: any) => {
return voidProm;
+11 -2
View File
@@ -47,8 +47,10 @@ class Bluebird<R> implements Bluebird.Thenable<R>, Bluebird.Inspection<R> {
/**
* Promises/A+ `.then()`. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise.
*/
then<U>(onFulfill: (value: R) => U | Bluebird.Thenable<U>, onReject?: (error: any) => U | Bluebird.Thenable<U>): Bluebird<U>;
then<U>(onFulfill: (value: R) => U | Bluebird.Thenable<U>, onReject?: (error: any) => void | Bluebird.Thenable<void>): Bluebird<U>;
then<U1, U2>(onFulfill: (value: R) => U1 | Bluebird.Thenable<U1>, onReject: (error: any) => U2 | Bluebird.Thenable<U2>): Bluebird<U1 | U2>;
then<U>(onFulfill: (value: R) => U | Bluebird.Thenable<U>, onReject: (error: any) => U | Bluebird.Thenable<U>): Bluebird<U>;
then<U>(onFulfill: (value: R) => U | Bluebird.Thenable<U>): Bluebird<U>;
then(): Bluebird<R>;
/**
* This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler.
@@ -315,6 +317,13 @@ class Bluebird<R> implements Bluebird.Thenable<R>, Bluebird.Inspection<R> {
*/
cancel(): void;
/**
* Basically sugar for doing: somePromise.catch(function(){});
*
* Which is needed in case error handlers are attached asynchronously to the promise later, which would otherwise result in premature unhandled rejection reporting.
*/
suppressUnhandledRejections(): void;
/**
* Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise.
*
+6
View File
@@ -71,6 +71,12 @@ class Tag extends bookshelf.Model<Tag> {
get tableName() { return 'tags'; }
}
User.where<User>('id', 1).fetch({withRelated: ['posts.tags']}).then(function(user) {
console.log(user.related('posts').toJSON());
}).catch(function(err) {
console.error(err);
});
new User().where('id', 1).fetch({withRelated: ['posts.tags']})
.then(user => {
const posts = user.related<Post>('posts');
+2
View File
@@ -93,6 +93,8 @@ declare module 'bookshelf' {
static fetchAll<T extends Model<any>>() : Promise<Collection<T>>;
/** @deprecated should use `new` objects instead. */
static forge<T>(attributes? : any, options? : ModelOptions) : T;
static where<T>(properties: { [key: string]: any }): T;
static where<T>(key: string, operatorOrValue: string | number | boolean, valueIfOperator?: string | number | boolean): T;
belongsTo<R extends Model<any>>(target : {new(...args : any[]) : R}, foreignKey? : string) : R;
belongsToMany<R extends Model<any>>(target : {new(...args : any[]) : R}, table? : string, foreignKey? : string, otherKey? : string) : Collection<R>;
+1 -1
View File
@@ -9,7 +9,7 @@
interface BootboxBaseOptions {
title?: string | Element;
callback?: (result: boolean | string) => any;
onEscape?: () => any | boolean;
onEscape?: (() => any) | boolean;
show?: boolean;
backdrop?: boolean;
closeButton?: boolean;
+5 -2
View File
@@ -36,7 +36,10 @@ interface NotifySettings {
from?: string;
align?: string;
};
offset?: number;
offset?: number | {
x?: number;
y?: number;
};
spacing?: number;
z_index?: number;
delay?: number;
@@ -59,4 +62,4 @@ interface NotifyReturn {
$ele: JQueryStatic;
close: () => void;
update: (command: string, update: any) => void;
}
}
+10
View File
@@ -7,3 +7,13 @@ Bowser.test(['msie']) === true;
Bowser.a === Bowser.c;
Bowser.osversion > 10;
Bowser.osversion === '10.1A';
bowser.msedge === true;
bowser.test(['msie']) === true;
bowser.a === bowser.c;
bowser.osversion > 10;
bowser.osversion === '10.1A';
bowser.compareVersions(['9.0', '10']);
bowser() === <BowserModule.IBowserDetection>{android: true, x: true};
bowser.check({msie: "11"}, window.navigator.userAgent);
bowser.isUnsupportedBrowser({msie: "10"}, window.navigator.userAgent);
+71 -19
View File
@@ -3,52 +3,104 @@
// Definitions by: Paulo Cesar <https://github.com/pocesar>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare var bowser: BowserModule.IBowser;
declare module 'bowser' {
var def: BowserModule.IBowser;
export = def;
export = bowser;
}
declare namespace BowserModule {
export interface IBowserUA {
msie: boolean;
export interface IBowserOS {
mac: boolean;
/**other than Windows Phone */
windows: boolean;
windowsphone: boolean;
/**other than android, chromeos, webos, tizen, and sailfish */
linux: boolean;
chromeos: boolean;
android: boolean;
/** also sets one of iphone/ipad/ipod */
ios: boolean;
blackberry: boolean;
firefoxos: boolean;
/** may also set touchpad */
webos: boolean;
bada: boolean;
tizen: boolean;
sailfish: boolean;
}
export interface IBowserVersions {
chrome: boolean;
webkit: boolean;
phantom: boolean;
opera: boolean;
firefox: boolean;
msie: boolean;
msedge: boolean;
safari: boolean;
android: boolean;
ios: boolean;
webos: boolean;
msedge: boolean;
seamonkey: boolean;
firefox: boolean;
yandexbrowser: boolean;
opera: boolean;
phantom: boolean;
blackberry: boolean;
tablet: boolean;
mobile: boolean;
webos: boolean;
silk: boolean;
bada: boolean;
tizen: boolean;
windowsphone: boolean;
firefoxos: boolean;
gecko: boolean;
seamonkey: boolean;
sailfish: boolean;
chromeBook: boolean;
ucbrowser: boolean;
qupzilla: boolean;
vivaldi: boolean;
sleipnir: boolean;
kMeleon: boolean;
}
export interface IBowserEngines {
/** IE <= 11 */
msie: boolean;
/**Chrome 0-27, Android <4.4, iOs, BB, etc. */
webkit: boolean;
/**Chrome >=28, Android >=4.4, Opera, etc. */
blink: boolean;
/**Firefox, etc. */
gecko: boolean;
/** IE > 11 */
msedge: boolean;
/** If a tablet device is detected, the flag tablet is set instead of mobile. */
tablet: boolean;
/** All detected mobile OSes are additionally flagged mobile, unless it's a tablet */
mobile: boolean;
}
export interface IBowserGrade {
/** Grade A browser */
a: boolean;
/** Grade C browser */
c: boolean;
/** Grade X browser */
x: boolean;
/**A human readable name for this browser. E.g. 'Chrome', '' */
name: string;
/**Version number for the browser. E.g. '32.0' */
version: string|number;
osversion: string|number;
}
export interface IBowser extends IBowserUA {
export interface IBowserDetection extends IBowserGrade, IBowserEngines, IBowserOS, IBowserVersions { }
export interface IBowserMinVersions {
// { msie: "11", "firefox": "4" }
[index: string]: string;
}
export interface IBowser extends IBowserDetection {
(): IBowserDetection;
test(browserList: string[]): boolean;
_detect(ua: string): IBowser;
compareVersions(versions: string[]): number;
check(minVersions: IBowserMinVersions, strictMode?: boolean|string, ua?: string): Boolean;
isUnsupportedBrowser(minVersions: IBowserMinVersions, strictMode?: boolean|string, ua?: string): boolean;
}
}
+432
View File
@@ -0,0 +1,432 @@
/// <reference path="braintree-web.d.ts" />
let version: string = braintree.VERSION;
let clientToken: string = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiI0YjlhYzVmYmI4ZTNkYzQzMmFkZjJhNzBlNjZlMWNjY2M5ODRkYzE4ZTM4YmY4NjYzZTM5NjM3NWZjYmQzY2U5fGNyZWF0ZWRfYXQ9MjAxNi0wOS0wOFQwNTowMzo0MC4xNjk1NTUwMzUrMDAwMFx1MDAyNm1lcmNoYW50X2lkPTM0OHBrOWNnZjNiZ3l3MmJcdTAwMjZwdWJsaWNfa2V5PTJuMjQ3ZHY4OWJxOXZtcHIiLCJjb25maWdVcmwiOiJodHRwczovL2FwaS5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tOjQ0My9tZXJjaGFudHMvMzQ4cGs5Y2dmM2JneXcyYi9jbGllbnRfYXBpL3YxL2NvbmZpZ3VyYXRpb24iLCJjaGFsbGVuZ2VzIjpbXSwiZW52aXJvbm1lbnQiOiJzYW5kYm94IiwiY2xpZW50QXBpVXJsIjoiaHR0cHM6Ly9hcGkuc2FuZGJveC5icmFpbnRyZWVnYXRld2F5LmNvbTo0NDMvbWVyY2hhbnRzLzM0OHBrOWNnZjNiZ3l3MmIvY2xpZW50X2FwaSIsImFzc2V0c1VybCI6Imh0dHBzOi8vYXNzZXRzLmJyYWludHJlZWdhdGV3YXkuY29tIiwiYXV0aFVybCI6Imh0dHBzOi8vYXV0aC52ZW5tby5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tIiwiYW5hbHl0aWNzIjp7InVybCI6Imh0dHBzOi8vY2xpZW50LWFuYWx5dGljcy5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tLzM0OHBrOWNnZjNiZ3l3MmIifSwidGhyZWVEU2VjdXJlRW5hYmxlZCI6dHJ1ZSwicGF5cGFsRW5hYmxlZCI6dHJ1ZSwicGF5cGFsIjp7ImRpc3BsYXlOYW1lIjoiQWNtZSBXaWRnZXRzLCBMdGQuIChTYW5kYm94KSIsImNsaWVudElkIjpudWxsLCJwcml2YWN5VXJsIjoiaHR0cDovL2V4YW1wbGUuY29tL3BwIiwidXNlckFncmVlbWVudFVybCI6Imh0dHA6Ly9leGFtcGxlLmNvbS90b3MiLCJiYXNlVXJsIjoiaHR0cHM6Ly9hc3NldHMuYnJhaW50cmVlZ2F0ZXdheS5jb20iLCJhc3NldHNVcmwiOiJodHRwczovL2NoZWNrb3V0LnBheXBhbC5jb20iLCJkaXJlY3RCYXNlVXJsIjpudWxsLCJhbGxvd0h0dHAiOnRydWUsImVudmlyb25tZW50Tm9OZXR3b3JrIjp0cnVlLCJlbnZpcm9ubWVudCI6Im9mZmxpbmUiLCJ1bnZldHRlZE1lcmNoYW50IjpmYWxzZSwiYnJhaW50cmVlQ2xpZW50SWQiOiJtYXN0ZXJjbGllbnQzIiwiYmlsbGluZ0FncmVlbWVudHNFbmFibGVkIjp0cnVlLCJtZXJjaGFudEFjY291bnRJZCI6ImFjbWV3aWRnZXRzbHRkc2FuZGJveCIsImN1cnJlbmN5SXNvQ29kZSI6IlVTRCJ9LCJjb2luYmFzZUVuYWJsZWQiOmZhbHNlLCJtZXJjaGFudElkIjoiMzQ4cGs5Y2dmM2JneXcyYiIsInZlbm1vIjoib2ZmIn0=";
braintree.client.create({
authorization: clientToken
}, function (error: BraintreeError, clientInstance: any) {
var form: HTMLFormElement = document.getElementById('my-form-id') as HTMLFormElement;
var data: { creditCard: BraintreeWeb.CreditCardInfo } = {
creditCard: {
number: form['cc-number'].value,
cvv: form['cc-cvv'].value,
expirationDate: form['cc-date'].value,
billingAddress: {
postalCode: form['cc-postal'].value
}
}
};
clientInstance.request({
endpoint: 'payment_methods/credit_cards',
method: 'post',
data: data
}, function (requestErr: BraintreeError, response: { creditCards: any[]; }) {
if (requestErr) { throw new Error(requestErr.message); }
console.log('Got nonce:', response.creditCards[0].nonce);
});
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '16pt',
'color': '#3A3A3A'
},
'.number': {
'font-family': 'monospace'
},
'.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number'
},
cvv: {
selector: '#cvv'
},
expirationDate: {
selector: '#expiration-date'
}
}
}, function (hostedFieldsErr?: BraintreeError, hostedFieldsInstance?: any) {
if (hostedFieldsErr) {
// Handle error in Hosted Fields creation
console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`);
return;
}
let form = new HTMLFormElement();
form.addEventListener('submit', function (event: Event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr: BraintreeError, payload: BraintreeWeb.HostedFieldsTokenizePayload) {
if (tokenizeErr) {
// Handle error in Hosted Fields tokenization
switch (tokenizeErr.code) {
case 'HOSTED_FIELDS_FIELDS_EMPTY':
console.error('All fields are empty! Please fill out the form.');
break;
case 'HOSTED_FIELDS_FIELDS_INVALID':
console.error('Some fields are invalid:', tokenizeErr.details.invalidFieldKeys);
break;
case 'HOSTED_FIELDS_FAILED_TOKENIZATION':
console.error('Tokenization failed server side. Is the card valid?');
break;
case 'HOSTED_FIELDS_TOKENIZATION_NETWORK_ERROR':
console.error('Network error occurred when tokenizing.');
break;
default:
console.error('Something bad happened!', tokenizeErr);
}
return;
}
// Put `payload.nonce` into the `payment-method-nonce` input, and then
// submit the form. Alternatively, you could send the nonce to your server
// with AJAX.
(document.querySelector('input[name="payment-method-nonce"]') as HTMLInputElement).value = payload.nonce;
form.submit();
});
}, false);
hostedFieldsInstance.on('focus', function (event: BraintreeWeb.HostedFieldsStateObject) {
console.log(event.emittedBy, 'has been focused');
});
hostedFieldsInstance.teardown(function (teardownErr: BraintreeError) {
if (teardownErr) {
console.error('Could not tear down Hosted Fields!');
} else {
console.info('Hosted Fields has been torn down!');
}
});
hostedFieldsInstance.tokenize({
vault: true
}, function (tokenizeErr: BraintreeError, payload: BraintreeWeb.HostedFieldsTokenizePayload) {
if (tokenizeErr) {
console.error(tokenizeErr);
} else {
console.log('Got nonce:', payload.nonce);
}
});
hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: BraintreeError) {
if (addClassErr) {
console.error(addClassErr);
}
});
hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: BraintreeError) {
if (addClassErr) {
console.error(addClassErr);
return;
}
// some time later...
hostedFieldsInstance.removeClass('number', 'custom-class');
});
hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr: BraintreeError) {
if (placeholderErr) {
console.error(placeholderErr);
}
});
hostedFieldsInstance.on('cardTypeChange', function (event: BraintreeWeb.HostedFieldsStateObject) {
// Update the placeholder value if there is only one possible card type
if (event.cards.length === 1) {
braintree.hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr: BraintreeError) {
if (placeholderErr) {
// Handle errors, such as invalid field name
console.error(placeholderErr);
}
});
}
});
hostedFieldsInstance.clear('number', function (clearErr: BraintreeError) {
if (clearErr) {
console.error(clearErr);
}
});
hostedFieldsInstance.clear('number');
hostedFieldsInstance.clear('cvv');
hostedFieldsInstance.clear('expirationDate');
var state = braintree.hostedFields.getState();
var formValid = Object.keys(state.fields).every(function (key) {
return state.fields[key].isValid;
});
});
braintree.applePay.create({ client: clientInstance }, function (createErr?: BraintreeError, applePayInstance?: any) {
if (createErr) {
// Handle error in client creation
console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`);
return;
}
let request = {
countryCode: 'US',
currencyCode: 'USD',
supportedNetworks: ['visa', 'masterCard'],
merchantCapabilities: ['supports3DS'],
total: { label: 'Your Label', amount: '10.00' },
};
var paymentRequest = braintree.applePay.createPaymentRequest(request);
console.log(paymentRequest);
// { total: { }, countryCode: 'US', currencyCode: 'USD', merchantCapabilities: [ ], supportedNetworks: [ ] }
});
braintree.applePay.create({ client: clientInstance }, function (createErr, applePayInstance) {
let request = {
countryCode: 'US',
currencyCode: 'USD',
supportedNetworks: ['visa', 'masterCard'],
merchantCapabilities: ['supports3DS'],
total: { label: 'Your Label', amount: '10.00' },
};
var session = new ApplePaySession(1, request);
session.onvalidatemerchant = function (event: { validationURL: string }) {
braintree.applePay.performValidation({
validationURL: event.validationURL
}, function (err, validationData) {
if (err) {
console.error(err);
session.abort();
return;
}
session.completeMerchantValidation(validationData);
});
};
});
braintree.applePay.create({ client: clientInstance }, function (createErr, applePayInstance) {
let request = {
countryCode: 'US',
currencyCode: 'USD',
supportedNetworks: ['visa', 'masterCard'],
merchantCapabilities: ['supports3DS'],
total: { label: 'Your Label', amount: '10.00' },
};
var session = new ApplePaySession(1, request);
session.onpaymentauthorized = function (event) {
braintree.applePay.tokenize({
token: event.payment.token
}, function (err, tokenizedPayload) {
if (err) {
session.completePayment(ApplePayStatusCodes.STATUS_FAILURE);
return;
}
session.completePayment(ApplePayStatusCodes.STATUS_SUCCESS);
// Send the tokenizedPayload to your server.
});
};
});
braintree.paypal.create({
client: clientInstance
}, function (createErr, paypalInstance) {
if (createErr) {
if (createErr.code === 'PAYPAL_BROWSER_NOT_SUPPORTED') {
console.error('This browser is not supported.');
} else {
console.error('Error!', createErr);
}
}
let button = new HTMLButtonElement();
button.addEventListener('click', function () {
// Disable the button so that we don't attempt to open multiple popups.
button.setAttribute('disabled', 'disabled');
// Because PayPal tokenization opens a popup, this must be called
// as a result of a user action, such as a button click.
paypalInstance.tokenize({
flow: 'vault' // Required
// Any other tokenization options
}, function (tokenizeErr: BraintreeError, payload: BraintreeWeb.PayPalTokenizePayload) {
button.removeAttribute('disabled');
if (tokenizeErr) {
// Handle tokenization errors or premature flow closure
switch (tokenizeErr.code) {
case 'PAYPAL_POPUP_CLOSED':
console.error('Customer closed PayPal popup.');
break;
case 'PAYPAL_ACCOUNT_TOKENIZATION_FAILED':
console.error('PayPal tokenization failed. See details:', tokenizeErr.details);
break;
case 'PAYPAL_FLOW_FAILED':
console.error('Unable to initialize PayPal flow. Are your options correct?', tokenizeErr.details);
break;
default:
console.error('Error!', tokenizeErr);
}
} else {
// Submit payload.nonce to your server
}
});
});
});
braintree.unionpay.create({ client: clientInstance }, function (createErr, unionpayInstance) {
if (createErr) {
console.error(createErr);
return;
}
unionpayInstance.fetchCapabilities({
card: {
number: '4111111111111111'
}
}, function (fetchErr: BraintreeError, cardCapabilities: BraintreeWeb.UnionPayFetchCapabilitiesPayload) {
if (fetchErr) {
console.error(fetchErr);
return;
}
if (cardCapabilities.isUnionPay) {
if (cardCapabilities.unionPay && !cardCapabilities.unionPay.isSupported) {
// Braintree cannot process this UnionPay card.
// Ask the user for a different card.
return;
}
if (cardCapabilities.isDebit) {
// CVV and expiration date are not required
} else {
// CVV and expiration date are required
}
// Show mobile phone number field for enrollment
}
});
unionpayInstance.enroll({
card: {
number: '4111111111111111',
expirationMonth: '12',
expirationYear: '2038'
},
mobile: {
countryCode: '62',
number: '111111111111'
}
}, function (enrollErr: BraintreeError, response: BraintreeWeb.UnionPayEnrollPayload) {
if (enrollErr) {
console.error(enrollErr);
return;
}
if (response.smsCodeRequired) {
// If smsCodeRequired, wait for SMS auth code from customer
// Then use response.enrollmentId during {@link UnionPay#tokenize}
} else {
// SMS code is not required from the user.
// {@link UnionPay#tokenize} can be called immediately
}
});
let enrollResponse: {
enrollmentId: string
};
unionpayInstance.tokenize({
card: {
number: '4111111111111111',
expirationMonth: '12',
expirationYear: '2038',
cvv: '123'
},
enrollmentId: enrollResponse.enrollmentId, // Returned from enroll
smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted
}, function (tokenizeErr: BraintreeError, response: BraintreeWeb.UnionPayTokenizePayload) {
if (tokenizeErr) {
console.error(tokenizeErr);
return;
}
// Send response.nonce to your server
});
unionpayInstance.teardown(function (teardownErr: BraintreeError) {
if (teardownErr) {
console.error('Could not tear down UnionPay.');
} else {
console.log('UnionPay has been torn down.');
}
});
});
});
let existingNonce = "fake-valid-nonce";
let submitNonceToServer: (nonce: string) => void;
braintree.threeDSecure.verifyCard({
nonce: existingNonce,
amount: 123.45,
addFrame: function (err, iframe) {
// Set up your UI and add the iframe.
let my3DSContainer = document.createElement('div');
my3DSContainer.appendChild(iframe);
document.body.appendChild(my3DSContainer);
},
removeFrame: function () {
let my3DSContainer = document.createElement('div');
// Remove UI that you added in addFrame.
document.body.removeChild(my3DSContainer);
}
}, function (err: BraintreeError, payload: BraintreeWeb.ThreeDSecureVerifyPayload) {
if (err) {
console.error(err);
return;
}
if (payload.liabilityShifted) {
// Liablity has shifted
submitNonceToServer(payload.nonce);
} else if (payload.liabilityShiftPossible) {
// Liablity may still be shifted
// Decide if you want to submit the nonce
} else {
// Liablity has not shifted and will not shift
// Decide if you want to submit the nonce
}
});
braintree.threeDSecure.cancelVerifyCard(function (err: BraintreeError, verifyPayload: BraintreeWeb.ThreeDSecureVerifyPayload) {
if (err) {
// Handle error
console.log(err.message); // No verification payload available
return;
}
verifyPayload.nonce; // The nonce returned from the 3ds lookup call
verifyPayload.liabilityShifted; // boolean
verifyPayload.liabilityShiftPossible; // boolean
});
+1738
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -288,11 +288,11 @@ declare module "browser-sync" {
middleware?: MiddlewareHandler;
ws: boolean;
reqHeaders: (config: any) => Hash<any>;
proxyRes: (res: http.ServerResponse, req: http.ServerRequest, next: Function) => any;
proxyRes: (res: http.ServerResponse, req: http.IncomingMessage, next: Function) => any;
}
interface MiddlewareHandler {
(req: http.ServerRequest, res: http.ServerResponse, next: Function): any;
(req: http.IncomingMessage, res: http.ServerResponse, next: Function): any;
}
interface PerRouteMiddleware {
+1 -1
View File
@@ -104,7 +104,7 @@ declare module 'bufferstream/postbuffer' {
http client buffer
*/
constructor(req: http.ServerRequest);
constructor(req: http.IncomingMessage);
/*
set a callback to get all post data from a http server request
*/
+36
View File
@@ -0,0 +1,36 @@
/// <reference path="bunnymq.d.ts"/>
import * as bunnymq from "bunnymq";
// Basic usage
var instance = bunnymq({ host: 'amqp://localhost' });
// Publisher
instance.producer.produce('queue:name', 'Hello World!');
// Subscriber
instance.consumer.consume('queue:name', message => { });
// RPC Support
instance.producer.produce('queue:name', { message: 'content' }, { rpc: true })
.then(function (consumerResponse) {
console.log(consumerResponse);
});
// Routing keys
instance.producer.produce('queue:name', { message: 'content' }, { routingKey: 'my-routing-key' });
// Config
var custom = bunnymq({
host: 'amqp://localhost',
//number of fetched messages at once on the channel
prefetch: 5,
//requeue put back message into the broker if consumer crashes/trigger exception
requeue: true,
//time between two reconnect (ms)
timeout: 1000,
consumerSuffix: '',
//generate a hostname so we can track this connection on the broker (rabbitmq management plugin)
hostname: "",
//the transport to use to debug. if provided, bunnymq will show some logs
transport: new Object()
});
+120
View File
@@ -0,0 +1,120 @@
// Type definitions for node-bunnymq 2.2.1
// Project: https://github.com/dial-once/node-bunnymq
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "bunnymq" {
namespace bunnymq {
export type ConsumerCallback = (message: Object) => void;
/**
* Consumer.
* @interface
*/
export interface Consumer {
/**
* Handle messages from a named queue.
* @param {string} queue A named queue.
* @param {ConsumerCallback} callback A callback.
*/
consume(queue: string, callback: ConsumerCallback): void;
}
/**
* bunnymq instance.
* @interface
*/
export interface Instance {
/**
* Consumer.
* @type {Consumer}
*/
consumer: Consumer;
/**
* Producer.
* @type {Producer}
*/
producer: Producer;
}
/**
* Options.
* @interface
*/
export interface Options {
/**
* Consumer suffix.
* @type {string}
*/
consumerSuffix?: string;
/**
* Host.
* @type {string}
*/
host?: string;
/**
* Hostname.
* @type {string}
*/
hostname?: string;
/**
* Number of fetched messages at once on the channel.
* @type {number}
*/
prefetch?: number;
/**
* Requeue put back message into the broker if consumer crashes/trigger exception.
* @type {boolean}
*/
requeue?: boolean;
/**
* Time between two reconnect (in milliseconds).
* @type {number}
*/
timeout?: number;
/**
* Transport.
* @type {any}
*/
transport?: any;
}
/**
* Producer.
* @inteface
*/
export interface Producer {
/**
* Send messages to a named queue.
* @param {string} queue A named queue.
* @param {Object} message A message.
* @return {Object} The consumer response.
*/
produce(queue: string, message: Object, options?: ProducerOptions): PromiseLike<Object>;
}
/**
* Options for producer.
* @interface
*/
export interface ProducerOptions {
routingKey?: string;
rpc?: boolean;
}
}
/**
* Constructor.
* @param {Options} [options] Options.
* @return {Instance} A instance of bunnymq.
*/
function bunnymq(options?: bunnymq.Options): bunnymq.Instance;
export = bunnymq;
}
+41
View File
@@ -0,0 +1,41 @@
/// <reference path="bunyan-config.d.ts"/>
import * as bunyan from "bunyan";
import bunyanConfig = require("bunyan-config");
var jsonConfig = {
name: "myLogger",
streams: [{
stream: "stdout"
}, {
stream: { name: "stderr" }
}, {
type: "raw",
stream: {
name: "bunyan-logstash",
params: {
host: "localhost",
port: 5005
}
}
}, {
type: "raw",
stream: {
name: "bunyan-redis",
params: {
host: "localhost",
port: 6379
}
}
}], serializers: {
req: "bunyan:stdSerializers.req",
fromNodeModules: "someNodeModule",
fromNodeModulesWithProps: "someNodeModule:a.b.c",
custom: "./lib/customSerializers:custom",
another: "./lib/anotherSerializer",
absolutePath: "/path/to/serializer:xyz"
}
};
var config = bunyanConfig(jsonConfig);
var logger = require("bunyan").createLogger(bunyanConfig);
+31
View File
@@ -0,0 +1,31 @@
// Type definitions for bunyan-config 0.2.0
// Project: https://github.com/LSEducation/bunyan-config
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../bunyan/bunyan.d.ts"/>
declare module "bunyan-config" {
import * as bunyan from "bunyan";
/**
* Configuration.
* @interface
*/
interface Configuration {
name: string;
streams?: bunyan.Stream[];
level?: string | number;
stream?: NodeJS.WritableStream;
serializers?: {};
src?: boolean;
}
/**
* Constructor.
* @param {Configuration} [jsonConfig] A JSON configuration.
* @return {LoggerOptions} A logger options.
*/
function bunyanConfig(jsonConfig?: Configuration): bunyan.LoggerOptions;
export = bunyanConfig;
}
+39
View File
@@ -0,0 +1,39 @@
/// <reference path="busboy.d.ts"/>
/// <reference path="../node/node.d.ts" />
import * as Busboy from 'busboy';
import * as http from 'http';
import * as util from 'util';
function serverFn(req: http.IncomingMessage, res: http.ServerResponse) {
if (req.method === 'POST') {
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
file.on('data', function(data: Buffer) {
console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
});
file.on('end', function() {
console.log('File [' + fieldname + '] Finished');
});
});
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
console.log('Field [' + fieldname + ']: value: ' + util.inspect(val));
});
busboy.on('finish', function() {
console.log('Done parsing form!');
res.writeHead(303, { Connection: 'close', Location: '/' });
res.end();
});
req.pipe(busboy);
} else if (req.method === 'GET') {
res.writeHead(200, { Connection: 'close' });
res.end('<html><head></head><body>\
<form method="POST" enctype="multipart/form-data">\
<input type="text" name="textfield"><br />\
<input type="file" name="filefield"><br />\
<input type="submit">\
</form>\
</body></html>');
}
}
+60
View File
@@ -0,0 +1,60 @@
// Type definitions for busboy v0.2.13
// Project: https://www.npmjs.com/package/busboy
// Definitions by: Jacob Baskin <https://github.com/jacobbaskin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare namespace busboy {
interface Options {
headers: any;
}
interface BusboyConfig {
headers?: any;
highWaterMark?: number;
fileHwm?: number;
defCharset?: string;
preservePath?: boolean;
limits?: {
fieldNameSize?: number;
fieldSize?: number;
fields?: number;
fileSize?: number;
files?: number;
parts?: number;
headerPairs?: number;
};
}
interface Busboy extends NodeJS.WritableStream {
on(event: 'field',
listener: (
fieldname: string,
val: any,
fieldnameTruncated: boolean,
valTruncated: boolean,
encoding: string,
mimetype: string) => void): this;
on(event: 'file',
listener: (
fieldname: string,
file: NodeJS.ReadableStream,
filename: string,
encoding: string,
mimetype: string) => void): this;
on(event: 'finish', callback: () => void): this;
on(event: 'partsLimit', callback: () => void): this;
on(event: 'filesLimit', callback: () => void): this;
on(event: 'fieldsLimit', callback: () => void): this;
on(event: string, listener: Function): this;
}
interface BusboyConstructor {
new (options: BusboyConfig): Busboy;
}
}
declare module 'busboy' {
const temp: busboy.BusboyConstructor;
export = temp;
}
Vendored
+5 -5
View File
@@ -385,10 +385,10 @@ declare namespace c3 {
* - d is the data where mouse cursor moves out. In this callback, this will be the Chart object.
*/
onmouseout?: (d: any, element?: any) => void;
// onselected?: any;
// onunselected?: any;
// ondragstart?: any;
// ondragend?: any;
onselected?: (d: any, element?: any) => void;
onunselected?: (d: any, element?: any) => void;
}
interface Axis {
@@ -681,7 +681,7 @@ declare namespace c3 {
* Specified function receives name, ratio, id and index of the data point to show. ratio will be undefined if the chart is not donut/pie/gauge.
* If undefined returned, the row of that value will be skipped.
*/
value?: (name: string, ratio: number, id: string, index: number) => string;
value?: (value: any, ratio: number, id: string, index: number) => string;
};
/**
* Set custom position for the tooltip. This option can be used to modify the tooltip position by returning object that has top and left.
+1 -1
View File
@@ -28,7 +28,7 @@ declare module 'cache-manager' {
module cacheManager {
function caching(ICongig: StoreConfig): Cache;
function caching(IConfig: StoreConfig): Cache;
function multiCaching(Caches: Cache[]): Cache;
}
+22
View File
@@ -0,0 +1,22 @@
/// <reference path="canvas-gauges.d.ts" />
import {
LinearGaugeOptions,
RadialGaugeOptions,
LinearGauge,
RadialGauge
} from 'canvas-gauges';
let linearOptions: LinearGaugeOptions = {
renderTo: document.createElement('canvas'),
fontNumbersStyle: 'italic'
};
let radialOptions: RadialGaugeOptions = {
renderTo: 'gauge-id',
fontNumbersWeight: 'bold'
};
new LinearGauge(linearOptions);
new RadialGauge(radialOptions);
console.log(document.gauges.length);
+278
View File
@@ -0,0 +1,278 @@
// Type definitions for canvas-gauges
// Project: https://github.com/Mikhus/canvas-gauges
// Definitions by: Mikhus <https://github.com/Mikhus>
// Definitions: https://github.com/Mikhus/DefinitelyTyped
declare namespace CanvasGauges {
export type FontStyle = 'normal' | 'italic' | 'oblique';
export type FontWeight = 'normal' | 'bold' | 'bolder' | 'lighter' |
'100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900';
export type RenderTarget = string|HTMLElement;
export interface AnimationRule {
(percent: number): number;
}
export interface Highlight {
from: number,
to: number,
color: string
}
export type MajorTicks = string[]|number[];
export interface GenericOptions {
renderTo: RenderTarget,
width?: number,
height?: number,
minValue?: number,
maxValue?: number,
value?: number,
units?: string|boolean,
majorTicks?: MajorTicks,
minorTicks?: number,
strokeTicks?: boolean,
animatedValue?: boolean,
animateOnInit?: boolean,
title?: string|boolean,
borders?: boolean,
valueInt?: number,
valueDec?: number,
majorTicksInt?: number,
majorTicksDec?: number,
animation?: boolean,
animationDuration?: number,
animationRule?: string|AnimationRule,
colorPlate?: string,
colorMajorTicks?: string,
colorMinorTicks?: string,
colorTitle?: string,
colorUnits?: string,
colorNumbers?: string,
colorNeedle?: string,
colorNeedleEnd?: string,
colorValueText?: string,
colorValueTextShadow?: string,
colorBorderShadow?: string,
colorBorderOuter?: string,
colorBorderOuterEnd?: string,
colorBorderMiddle?: string,
colorBorderMiddleEnd?: string,
colorBorderInner?: string,
colorBorderInnerEnd?: string,
colorValueBoxRect?: string,
colorValueBoxRectEnd?: string,
colorValueBoxBackground?: string,
colorValueBoxShadow?: string,
colorNeedleShadowUp?: string,
colorNeedleShadowDown?: string,
needle?: boolean,
needleShadow?: boolean,
needleType?: string,
needleStart?: number,
needleEnd?: number,
needleWidth?: number,
borderOuterWidth?: number,
borderMiddleWidth?: number,
borderInnerWidth?: number,
borderShadowWidth?: number,
valueBox?: boolean,
valueBoxWidth?: number,
valueBoxStroke?: number,
valueText?: string,
valueTextShadow?: boolean,
valueBoxBorderRadius?: number,
highlights?: Highlight[],
highlightsWidth?: number,
fontNumbers?: string,
fontTitle?: string,
fontUnits?: string,
fontValue?: string,
fontTitleSize?: number,
fontValueSize?: number,
fontUnitsSize?: number,
fontNumbersSize?: number,
fontTitleStyle?: FontStyle,
fontValueStyle?: FontStyle,
fontUnitsStyle?: FontStyle,
fontNumbersStyle?: FontStyle,
fontTitleWeight?: FontWeight,
fontValueWeight?: FontWeight,
fontUnitsWeight?: FontWeight,
fontNumbersWeight?: FontWeight
}
export interface RadialGaugeOptions extends GenericOptions {
ticksAngle?: number,
startAngle?: number,
colorNeedleCircleOuter?: string,
colorNeedleCircleOuterEnd?: string,
colorNeedleCircleInner?: string,
colorNeedleCircleInnerEnd?: string,
needleCircleSize?: number,
needleCircleInner?: boolean,
needleCircleOuter?: boolean,
animationTarget?: string
}
export interface LinearGaugeOptions extends GenericOptions {
borderRadius?: number,
barBeginCircle?: number,
barWidth?: number,
barStrokeWidth?: number,
barProgress?: boolean,
colorBar?: string,
colorBarEnd?: string,
colorBarStroke?: string,
colorBarProgress?: string,
colorBarProgressEnd?: string,
tickSide?: string,
needleSide?: string,
numberSide?: string,
ticksWidth?: number,
ticksWidthMinor?: number,
ticksPadding?: number,
barLength?: number
}
export interface DrawEventCallback {
(percent: number): any;
}
export interface EndEventCallback {
(): any;
}
export interface rules {
linear: AnimationRule,
quad: AnimationRule,
dequad: AnimationRule,
quint: AnimationRule,
dequint: AnimationRule,
cycle: AnimationRule,
decycle: AnimationRule,
bounce: AnimationRule,
debounce: AnimationRule,
elastic: AnimationRule,
delastic: AnimationRule
}
export class Animation {
public duration: number;
public rule: string|AnimationRule;
public draw: DrawEventCallback;
public end: EndEventCallback;
public static rules: rules;
constructor(rule?: string|AnimationRule, duration?: number,
draw?: DrawEventCallback, end?: EndEventCallback);
public animate(draw?: DrawEventCallback, end?: EndEventCallback): any;
public destroy(): any;
}
export class SmartCanvas {
public element: HTMLCanvasElement;
public elementClone: HTMLCanvasElement;
public context: CanvasRenderingContext2D;
public contextClone: CanvasRenderingContext2D;
public drawWidth: number;
public drawHeight: number;
public drawX: number;
public drawY: number;
public minSide: number;
public width: number;
public height: number;
constructor(element: HTMLCanvasElement,
width?: number,
height?: number);
public init(): any;
public onRedraw(): any;
public destroy(): any;
public commit(): SmartCanvas;
public redraw(): SmartCanvas;
public pixelRatio: number;
public static redraw(): any;
public static collection: Array<SmartCanvas>;
}
export class DomObserver {
public Type: BaseGauge;
public mutationsObserved: boolean;
public isObservable: boolean;
public options: GenericOptions;
public element: string;
public type: string;
constructor(options: GenericOptions,
element: string,
type: string);
public isValidNode(node: Node|HTMLElement): boolean;
public traverse(): any;
public observe(records: MutationRecord[]): any;
public process(node: Node|HTMLElement): BaseGauge;
public static parse(value: any): any;
public static toDashed(camelCase: string): string;
public static toAttributeName(str: string): string;
static domReady(handler: Function): any;
}
export abstract class BaseGauge {
public type: BaseGauge;
public options: GenericOptions;
public canvas: SmartCanvas;
public animation: Animation;
public value: number;
constructor(options: GenericOptions);
public update(options: GenericOptions): BaseGauge;
public destroy(): any;
public abstract draw(): BaseGauge;
public static initialize(type: string, options: GenericOptions): any;
}
export class RadialGauge extends BaseGauge {
public type: RadialGauge;
public options: RadialGaugeOptions;
constructor(options: RadialGaugeOptions);
public draw(): RadialGauge;
}
export class LinearGauge extends BaseGauge {
public type: LinearGauge;
public options: LinearGaugeOptions;
constructor(options: LinearGaugeOptions);
public draw(): LinearGauge;
}
export interface Collection extends Array<BaseGauge> {
get: (id: number | string) => BaseGauge;
}
}
declare module 'canvas-gauges' {
export = CanvasGauges;
}
interface Document {
gauges: CanvasGauges.Collection;
}
interface Window {
BaseGauge: CanvasGauges.BaseGauge;
RadialGauge: CanvasGauges.RadialGauge;
LinearGauge: CanvasGauges.LinearGauge;
}
+495
View File
@@ -0,0 +1,495 @@
// Type definitions for Cash
// Project: https://github.com/kenwheeler/cash
// Definitions by: Ashok Vishwakarma <https://github.com/akvlko>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* OffsetType
* return type for cash.offset(), cash.position()
*/
interface OffsetType {
top: number;
left: number;
}
/**
* CashStatic
* Static declaration for CashJs accessible directly using Cash object or $
*/
interface CashStatic {
/**
* isArray
* Check if the argument is an array.
* @type method
* @argument any
* @return boolean
*/
isArray(n: any): boolean;
/**
* isFunction
* Check if the argument is a function.
* @type method
* @argument any
* @return boolean
*/
isFunction(n: any): boolean;
/**
* isNumeric
* Check if the argument is numeric.
* @type method
* @type method
* @argument any
* @return boolean
*/
isNumeric(n: any): boolean;
/**
* isString
* Check if the argument is a string.
* @type method
* @argument str any
* @return boolean
*/
isString(str: any): boolean;
/**
* extend
* Extends target object with properties from the source object. If no target is provided, cash itself will be extended.
* @type method
* @argument target any, source any
*/
extend(target: any, source: any): any;
/**
* matches
* Checks a selector against an element, returning a boolean value for match.
* @type method
* @argument element Cash, selector string
* @return boolean
*/
matches(element: Cash, selector: string): boolean;
/**
* parseHTML
* Returns a collection from an HTML string.
* @type method
* @argument htmlString string
* @return Cash
*/
parseHTML(htmlString: string): Cash;
/**
* each
* Iterates through a collection and calls the callback method on each.
* @type method
* @argument collection Array, callback Function
* @return Array
*/
each(collection: Array<any>, callback: Function): Array<any>;
/**
* fn: use to extend cash for plugin development
* @type property
*/
fn: any;
/**
* selector declaration for Cash to use $(<argument>)
*/
(selector: string, context?: Element|Cash): Cash;
(element: Element): Cash;
(elementArray: Element[]): Cash;
}
/**
* Cash
* Interface for CashJs
* Refer https://github.com/kenwheeler/cash for documentation and uses of the methods and properties
*/
interface Cash {
/**
* add
* Returns a new collection with the element(s) added to the end.
*/
add(selector: string|Cash|Element, context?: Element): Cash;
/**
* addClass
* Adds the className argument to collection elements.
*/
addClass(c: string): Cash;
/**
* after
* Inserts content or elements after the collection.
*/
after(selector: Element|String): Cash;
/**
* append
* Appends the target element to the each element in the collection.
*/
append(content: string|Element|Cash): Cash;
/**
* appendTo
* Adds the elements in a collection to the target element(s).
*/
appendTo(parent: string|Element|Cash): Cash;
/**
* attr
* Without attrValue, returns the attribute value of the first element in the collection.
* With attrValue, sets the attribute value of each element of the collection.
*/
attr(name: string): any;
attr(name: string, value: string): Cash;
/**
* before
* Inserts content or elements before the collection.
*/
before(selector: string|Element): Cash;
/**
* children
* Without a selector specified, returns a collection of child elements.
* With a selector, returns child elements that match the selector.
*/
children(selector?: string): Cash;
/**
* closest
* Returns the closest matching selector up the DOM tree.
*/
closest(selector?: string): Cash;
/**
* clone
* Returns a clone of the collection.
*/
clone(): Cash;
/**
* css
* Returns a CSS property value when just property is supplied.
* Sets a CSS property when property and value are supplied, and set multiple properties when an object is supplied.
* Properties will be autoprefixed if needed for the user's browser.
*/
css(prop: any): any;
css(prop: string, value: any): Cash;
/**
* data
* Link some data (string, object, array, etc.) to an element when both key and value are supplied.
* If only a key is supplied, returns the linked data and falls back to data attribute value if no data is already linked.
* Multiple data can be set when an object is supplied.
*/
data(name: any): any;
data(name: string, value: any): Cash;
/**
* each
* Iterates over a collection with callback(value, index, array).
*/
each(callback: Function): Cash;
/**
* empty
* Empties an elements interior markup.
*/
empty(): Cash;
/**
* eq
* Returns a collection with the element at index.
*/
eq(index: number): Cash;
/**
* extend
* Adds properties to the cash collection prototype.
*/
extend(target: any): any;
/**
* filter
* Returns the collection that results from applying the filter method.
*/
filter(selector: Function): Cash;
/**
* find
* Returns selector match descendants from the first element in the collection.
*/
find(selector: string): Cash;
/**
* first
* Returns the first element in the collection.
*/
first(): Cash;
/**
* get
* Returns the element at the index.
*/
get(index: number): HTMLElement;
/**
* has
* Returns boolean result of the selector argument against the collection.
*/
has(selector: string): boolean;
/**
* hasClass
* Returns the boolean result of checking if the first element in the collection has the className attribute.
*/
hasClass(c: string): boolean;
/**
* height
* Returns the height of the element.
*/
height(): number;
/**
* html
* Returns the HTML text of the first element in the collection, sets the HTML if provided.
*/
html(): string;
html(content: string): Cash;
/**
* index
* Returns the index of the element in its parent if an element or selector isn't provided.
* Returns index within element or selector if it is.
*/
index(elem?: Element): number;
/**
* innerHeight
* Returns the height of the element + padding.
*/
innerHeight(): number;
/**
* innerWidth
* Returns the width of the element + padding.
*/
innerWidth(): number;
/**
* insertAfter
* Inserts collection after specified element.
*/
insertAfter(selector: string|Element|Cash): Cash;
/**
* insertBefore
* Inserts collection before specified element.
*/
insertBefore(selector: string|Element|Cash): Cash;
/**
* is
* Returns whether the provided selector, element or collection matches any element in the collection.
*/
is(selector: string|Element|Cash): boolean;
/**
* last
* Returns last element in the collection.
*/
last(): Cash;
/**
* next
* Returns next sibling.
*/
next(): Cash;
/**
* not
* Filters collection by false match on selector.
*/
not(selector: string|Element|Cash): Cash;
/**
* off
* Removes event listener from collection elements.
*/
off(eventName: string, callback: Function): Cash;
/**
* offset
* Get the coordinates of the first element in a collection relative to the document.
*/
offset(): OffsetType;
/**
* offsetParent
* Get the first element's ancestor that's positioned.
*/
offsetParent(): OffsetType;
/**
* on
* Adds event listener to collection elements. Event is delegated if delegate is supplied.
*/
on(eventName: string|Array<string>, delegate: any, callback?: Function, runOnce?: boolean): Cash;
/**
* one
* Adds event listener to collection elements that only triggers once for each element.
* Event is delegated if delegate is supplied.
*/
one(eventName: string|Array<string>, delegate: any, callback?: Function, runOnce?: boolean): Cash;
/**
* outerHeight
* Returns the outer height of the element. Includes margins if margin is set to true.
*/
outerHeight(flag?: boolean): number;
/**
* outerWidth
* Returns the outer width of the element. Includes margins if margin is set to true.
*/
outerWidth(flag?: boolean): number;
/**
* parent
* Returns parent element.
*/
parent(): Cash;
/**
* parents
* Returns collection of elements who are parents of element. Optionally filtering by selector.
*/
parents(selector?: string): Cash;
/**
* position
* Get the coordinates of the first element in a collection relative to its offsetParent.
*/
position(): OffsetType;
/**
* prepend
* Prepends element to the each element in collection.
*/
prepend(content: string): Cash;
/**
* prependTo
* Prepends elements in a collection to the target element(s).
*/
prependTo(parent: string|Element|Cash): Cash;
/**
* prev
* Returns the previous adjacent element.
*/
prev(): Cash;
/**
* prop
* Returns a property value when just property is supplied.
* Sets a property when property and value are supplied, and sets multiple properties when an object is supplied.
*/
prop(name: string): any;
prop(name: string, value: string): Cash;
/**
* ready
* Calls callback method on DOMContentLoaded.
*/
ready(fn: Function): void;
/**
* remove
* Removes collection elements from the DOM.
*/
remove(): Cash;
/**
* removeAttr
* Removes attribute from collection elements.
*/
removeAttr(name: string): Cash;
/**
* removeClass
* Removes className from collection elements.
* Accepts space-separated classNames for removing multiple classes.
* Providing no arguments will remove all classes.
*/
removeClass(c?: string): Cash;
/**
* removeData
* Removes linked data and data-attributes from collection elements.
*/
removeData(key: string): Cash;
/**
* removeProp
* Removes property from collection elements.
*/
removeProp(name: string): Cash;
/**
* serialize
* When called on a form, serializes and returns form data.
*/
serialize(): string;
/**
* siblings
* Returns a collection of sibling elements.
*/
siblings(): Cash;
/**
* text
* Returns the inner text of the first element in the collection, sets the text if textContent is provided.
*/
text(): string;
text(content?: string): Cash;
/**
* toggleClass
* Adds or removes className from collection elements based on if the element already has the class.
* Accepts space-separated classNames for toggling multiple classes, and an optional force boolean to ensure classes are added (true) or removed (false).
*/
toggleClass(c: string, state?: boolean): Cash;
/**
* trigger
* Triggers supplied event on elements in collection. Data can be passed along as the second parameter.
*/
trigger(eventName: string, data?: any): Cash;
/**
* val
* Returns an inputs value. If value is supplied, sets all inputs in collection's value to the value argument.
*/
val(): any;
val(value?: string): Cash;
/**
* width
* Returns the width of the element.
*/
width(): number;
}
declare module "cash" {
export = CashStatic;
}
declare var cash: CashStatic;
+20
View File
@@ -18,9 +18,19 @@ function test_somethingSyntax() {
array.should.include.something.with.property('b', 2);
array.should.not.include.something.with.property('b', 3);
chai.expect(array).to.include.something();
chai.expect(array).to.include.something.that.deep.equals({ b: 2 });
chai.expect(array).to.include.something.that.not.deep.equals({ b: 2 });
chai.expect(array).not.to.include.something.that.deep.equals({ c: 3 });
chai.expect(array).to.include.something.that.not.deep.equals({ c: 3 });
chai.expect(array).to.include.something.with.property('b', 2);
chai.expect(array).not.to.include.something.with.property('b', 3);
var array2 = [{ a: 'b' }, { a: 'b' }];
array2.should.include.something.that.have.property("a");
array2.should.include.something.that.have.property("a").not.equal("d");
chai.expect(array2).to.include.something.that.have.property("a");
chai.expect(array2).to.include.something.that.have.property("a").not.equal("d");
}
function test_somethingVariantsSyntax() {
@@ -35,6 +45,16 @@ function test_somethingVariantsSyntax() {
array.should.include.one.that.deep.equals({ b: 2 });
array.should.include.some();
array.should.include.some.that.deep.equal({ b: 2 });
chai.expect(array).to.include.a.thing();
chai.expect(array).to.include.a.thing.that.deep.equals({ b: 2 });
chai.expect(array).to.include.an.item();
chai.expect(array).to.include.an.item.that.deep.equals({ b: 2 });
chai.expect(array).to.include.one.that.deep.equals({ b: 2 });
chai.expect(array).to.include.some();
chai.expect(array).to.include.some.that.deep.equal({ b: 2 });
chai.expect(array).to.contain.a.thing();
chai.expect(array).to.contain.a.thing.with.property('a', 1);
}
function test_allSyntax() {
+9
View File
@@ -23,6 +23,15 @@ declare namespace Chai {
any: Anything;
}
interface Include {
(item: any): any;
a: Item;
an: Item;
one: Something;
some: Something;
something: Something;
}
interface Anything extends Assertion {
(): any;
that: Assertion;
+8
View File
@@ -114,8 +114,16 @@ declare namespace Chance {
capitalize(str: string): string;
mixin(desc: MixinDescriptor): any;
pad(num: number, width: number, padChar?: string): string;
/**
* @deprecated Use pickone
*/
pick<T>(arr: T[]): T;
pickone<T>(arr: T[]): T;
/**
* @deprecated Use pickset
*/
pick<T>(arr: T[], count: number): T[];
pickset<T>(arr: T[], count: number): T[];
set: Setter;
shuffle<T>(arr: T[]): T[];
+124
View File
@@ -0,0 +1,124 @@
/// <reference path="change-emitter.d.ts"/>
import { createChangeEmitter, ChangeEmitterOf0 } from "change-emitter";
function usage() {
// https://github.com/acdlite/change-emitter#usage
const emitter = createChangeEmitter()
// Called `listen` instead of `subscribe` to avoid confusion with observable spec
const unlisten = emitter.listen((...args) => {
console.log(args)
})
emitter.emit(1, 2, 3) // logs `[1, 2, 3]`
unlisten()
emitter.emit(4, 5, 6) // doesn't log
}
function largerExample() {
// https://github.com/acdlite/change-emitter#larger-example
const createStore = (reducer: Function, initialState: any) => {
let state = initialState
const emitter = createChangeEmitter()
function dispatch(action: any) {
state = reducer(state, action)
emitter.emit()
return action
}
function getState() {
return state
}
return {
dispatch,
getState,
subscribe: emitter.listen
}
}
}
function untypedEmitter() {
const { emit, listen } = createChangeEmitter();
const unlisten0 = listen(() => {/* do something */});
const unlisten1 = listen(value => {/* do something with value */});
const unlisten2 = listen((value1, value2) => {/* do something with values */});
const unlistenArgs = listen((...args: any[]) => {/* do something with values */});
emit();
emit("hello");
emit("hello", "world");
emit(1, 2, 3, 4, 5);
unlisten0();
unlisten1();
unlisten2();
unlistenArgs();
}
function emitterOf0Args() {
const { emit, listen }: ChangeEmitterOf0 = createChangeEmitter();
const unlisten = listen(() => { });
// const unlisten = listen(value => {}); // SYNTAX ERROR
emit();
// emit("hello"); // SYNTAX ERROR
unlisten();
}
function emitterOf1Args() {
const { emit, listen } = createChangeEmitter<string>();
const unlisten = listen(value => { value.length });
emit("hello");
unlisten();
}
function emitterOf2Args() {
const { emit, listen } = createChangeEmitter<string, boolean>();
const unlisten = listen((value, success) => { value.length > 0 === success });
emit("hello", true);
unlisten();
}
function emitterOf3Args() {
const { emit, listen } = createChangeEmitter<string, boolean, number>();
const unlisten = listen((value, success, count) => { value.length > count === success });
emit("hello", true, 3);
unlisten();
}
function emitterOf4Args() {
const { emit, listen } = createChangeEmitter<string, boolean, number, Date>();
const unlisten = listen((v1, v2, v3, v4) => { });
emit("hello", true, 3, new Date());
unlisten();
}
function emitterOf5Args() {
const { emit, listen } = createChangeEmitter<string, boolean, number, Date, string>();
const unlisten = listen((v1, v2, v3, v4, v5) => { });
emit("hello", true, 3, new Date(), "world");
unlisten();
}
+58
View File
@@ -0,0 +1,58 @@
// Type definitions for change-emitter v0.1.2
// Project: https://github.com/acdlite/change-emitter
// Definitions by: Iskander Sierra <https://github.com/iskandersierra>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'change-emitter' {
type Unlisten = () => void;
type Listener = (...args: any[]) => void;
type ListenerOf0 = () => void;
type ListenerOf1<T> = (value: T) => void;
type ListenerOf2<T1, T2> = (value1: T1, value2: T2) => void;
type ListenerOf3<T1, T2, T3> = (value1: T1, value2: T2, value3: T3) => void;
type ListenerOf4<T1, T2, T3, T4> = (value1: T1, value2: T2, value3: T3, value4: T4) => void;
type ListenerOf5<T1, T2, T3, T4, T5> = (value1: T1, value2: T2, value3: T3, value4: T4, value5: T5) => void;
interface ChangeEmitter {
listen(listener: Listener): Unlisten;
emit(...args: any[]): void;
}
interface ChangeEmitterOf1<T> {
listen(listener: ListenerOf1<T>): Unlisten;
emit(value: T): void;
}
interface ChangeEmitterOf0 {
listen(listener: ListenerOf0): Unlisten;
emit(): void;
}
interface ChangeEmitterOf2<T1, T2> {
listen(listener: ListenerOf2<T1, T2>): Unlisten;
emit(value1: T1, value2: T2): void;
}
interface ChangeEmitterOf3<T1, T2, T3> {
listen(listener: ListenerOf3<T1, T2, T3>): Unlisten;
emit(value1: T1, value2: T2, value3: T3): void;
}
interface ChangeEmitterOf4<T1, T2, T3, T4> {
listen(listener: ListenerOf4<T1, T2, T3, T4>): Unlisten;
emit(value1: T1, value2: T2, value3: T3, value4: T4): void;
}
interface ChangeEmitterOf5<T1, T2, T3, T4, T5> {
listen(listener: ListenerOf5<T1, T2, T3, T4, T5>): Unlisten;
emit(value1: T1, value2: T2, value3: T3, value4: T4, value5: T5): void;
}
export function createChangeEmitter(): ChangeEmitter;
export function createChangeEmitter<T>(): ChangeEmitterOf1<T>;
export function createChangeEmitter<T1, T2>(): ChangeEmitterOf2<T1, T2>;
export function createChangeEmitter<T1, T2, T3>(): ChangeEmitterOf3<T1, T2, T3>;
export function createChangeEmitter<T1, T2, T3, T4>(): ChangeEmitterOf4<T1, T2, T3, T4>;
export function createChangeEmitter<T1, T2, T3, T4, T5>(): ChangeEmitterOf5<T1, T2, T3, T4, T5>;
}
+1 -1
View File
@@ -73,7 +73,7 @@ interface ChartOptions {
onClick?: (any?: any) => any;
title?: ChartTitleOptions;
legend?: ChartLegendOptions;
tooltip?: ChartTooltipOptions;
tooltips?: ChartTooltipOptions;
hover?: ChartHoverOptions;
animation?: ChartAnimationOptions;
elements?: ChartElementsOptions;
+63
View File
@@ -0,0 +1,63 @@
/// <reference path="cheap-ruler.d.ts"/>
import * as cheapRuler from 'cheap-ruler'
// -- Fixtures --
const bbox = [30.5, 50.5, 31, 51]
const point1 = [30.5, 50.5]
const point2 = [30.51, 50.49]
const unit = 'miles'
const lineString = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"coordinates": [
[-77.031669, 38.878605],
[-77.029609, 38.881946],
[-77.020339, 38.884084],
[-77.025661, 38.885821],
[-77.021884, 38.889563],
[-77.019824, 38.892368]
]
}
}
const line = lineString.geometry.coordinates
const polygon = [[
[-67.031, 50.458], [-67.031, 50.534], [-66.929, 50.534],
[-66.929, 50.458], [-67.031, 50.458]
]]
const points = [
[-67.031, 50.458], [-67.031, 50.534],
[-66.929, 50.534], [-66.929, 50.458]
]
// -- Test initiators --
cheapRuler(35.05)
cheapRuler(35.05, 'miles')
cheapRuler(35.05, unit)
cheapRuler.fromTile(1567, 12)
cheapRuler.fromTile(1567, 12, 'miles')
cheapRuler.fromTile(1567, 12, unit)
// -- Test units --
cheapRuler.units
cheapRuler.units.miles
cheapRuler.units.kilometers
50 * cheapRuler.units.yards / cheapRuler.units.meters
// -- Test cheapRuler --
const ruler = cheapRuler(35.05)
ruler.distance(point1, point2)
ruler.bearing(point1, point2)
ruler.destination(point1, 0.1, 90)
ruler.lineDistance(points)
ruler.area(polygon)
ruler.along(line, 2.5)
ruler.pointOnLine(line, point1).point
ruler.lineSlice(point1, point2, line)
ruler.lineSliceAlong(10, 20, line)
ruler.bufferPoint(point1, 0.01)
ruler.bufferBBox(bbox, 0.2)
ruler.insideBBox(point1, bbox)
+216
View File
@@ -0,0 +1,216 @@
// Type definitions for cheap-ruler 2.4.1
// Project: https://github.com/mapbox/cheap-ruler
// Definitions by: Denis Carriere <https://github.com/DenisCarriere>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "cheap-ruler" {
type BBox = [number, number, number, number] | number[]
type Point = [number, number] | number[]
type Line = Array<Point>
type Points = Array<Point>
type Polygon = Array<Array<Point>>
interface TemplateUnits {
kilometers: number
miles: number
nauticalmiles: number
meters: number
metres: number
yards: number
feet: number
inches: number
}
interface InterfacePointOnLine {
point: Point
index: number
t: number
}
class CheapRuler {
/**
* Given two points of the form [longitude, latitude], returns the distance.
*
* @param {Point} a point [longitude, latitude]
* @param {Point} b point [longitude, latitude]
* @returns {number} distance
* @example
* var distance = ruler.distance([30.5, 50.5], [30.51, 50.49]);
* //=distance
*/
distance(a: Point, b: Point): number;
/**
* Returns the bearing between two points in angles.
*
* @param {Point} a point [longitude, latitude]
* @param {Point} b point [longitude, latitude]
* @returns {number} bearing
* @example
* var bearing = ruler.bearing([30.5, 50.5], [30.51, 50.49]);
* //=bearing
*/
bearing(a: Point, b: Point): number;
/**
* Returns a new point given distance and bearing from the starting point.
*
* @param {Point} p point [longitude, latitude]
* @param {number} dist distance
* @param {number} bearing
* @returns {Point} point [longitude, latitude]
* @example
* var point = ruler.destination([30.5, 50.5], 0.1, 90);
* //=point
*/
destination(p: Point, dist: number, bearing: number): Point;
/**
* Given a line (an array of points), returns the total line distance.
*
* @param {Points} points [longitude, latitude]
* @returns {number} total line distance
* @example
* var length = ruler.lineDistance([
* [-67.031, 50.458], [-67.031, 50.534],
* [-66.929, 50.534], [-66.929, 50.458]
* ]);
* //=length
*/
lineDistance(points: Points): number;
/**
* Given a polygon (an array of rings, where each ring is an array of points), returns the area.
*
* @param {Polygon} polygon
* @returns {number} area value in the specified units (square kilometers by default)
* @example
* var area = ruler.area([[
* [-67.031, 50.458], [-67.031, 50.534], [-66.929, 50.534],
* [-66.929, 50.458], [-67.031, 50.458]
* ]]);
* //=area
*/
area(polygon: Polygon): number;
/**
* Returns the point at a specified distance along the line.
*
* @param {Line} line
* @param {number} dist distance
* @returns {Point} point [longitude, latitude]
* @example
* var point = ruler.along(line, 2.5);
* //=point
*/
along(line: Line, dist: number): Point
/**
* Returns an object of the form {point, index} where point is closest point on the line from the given point, and index is the start index of the segment with the closest point.
*
* @pointOnLine
* @param {Line} line
* @param {Point} p point [longitude, latitude]
* @returns {Object} {point, index}
* @example
* var point = ruler.pointOnLine(line, [-67.04, 50.5]).point;
* //=point
*/
pointOnLine(line: Line, p: Point): InterfacePointOnLine
/**
* Returns a part of the given line between the start and the stop points (or their closest points on the line).
*
* @param {Point} start point [longitude, latitude]
* @param {Point} stop point [longitude, latitude]
* @param {Line} line
* @returns {Line} line part of a line
* @example
* var line2 = ruler.lineSlice([-67.04, 50.5], [-67.05, 50.56], line1);
* //=line2
*/
lineSlice(start: Point, stop: Point, line: Line): Line
/**
* Returns a part of the given line between the start and the stop points indicated by distance along the line.
*
* @param {number} start distance
* @param {number} stop distance
* @param {Line} line
* @returns {Line} line part of a line
* @example
* var line2 = ruler.lineSliceAlong(10, 20, line1);
* //=line2
*/
lineSliceAlong(start: number, stop: number, line: Line): Line
/**
* Given a point, returns a bounding box object ([w, s, e, n]) created from the given point buffered by a given distance.
*
* @param {Point} p point [longitude, latitude]
* @param {number} buffer
* @returns {BBox} box object ([w, s, e, n])
* @example
* var bbox = ruler.bufferPoint([30.5, 50.5], 0.01);
* //=bbox
*/
bufferPoint(p: Point, buffer: number): BBox
/**
* Given a bounding box, returns the box buffered by a given distance.
*
* @param {BBox} box object ([w, s, e, n])
* @param {number} buffer
* @returns {BBox} box object ([w, s, e, n])
* @example
* var bbox = ruler.bufferBBox([30.5, 50.5, 31, 51], 0.2);
* //=bbox
*/
bufferBBox(bbox: BBox, buffer: number): BBox
/**
* Returns true if the given point is inside in the given bounding box, otherwise false.
*
* @param {Point} p point [longitude, latitude]
* @param {Point} box object ([w, s, e, n])
* @returns {boolean}
* @example
* var inside = ruler.insideBBox([30.5, 50.5], [30, 50, 31, 51]);
* //=inside
*/
insideBBox(p: Point, bbox: BBox): boolean
}
/**
* A collection of very fast approximations to common geodesic measurements. Useful for performance-sensitive code that measures things on a city scale.
*
* @param {number} lat latitude
* @param {string} [units='kilometers']
* @returns {CheapRuler}
* @example
* var ruler = cheapRuler(35.05, 'miles');
* //=ruler
*/
function cheapRuler(lat: number, units?: string): CheapRuler;
namespace cheapRuler {
/**
* Multipliers for converting between units.
*
* @example
* // convert 50 meters to yards
* 50 * cheapRuler.units.yards / cheapRuler.units.meters;
*/
const units: TemplateUnits
/**
* Creates a ruler object from tile coordinates (y and z). Convenient in tile-reduce scripts.
*
* @param {number} y
* @param {number} z
* @param {string} [units='kilometers']
* @returns {CheapRuler}
* @example
* var ruler = cheapRuler.fromTile(1567, 12);
* //=ruler
*/
function fromTile(y: number, z: number, units?: string): CheapRuler;
}
export = cheapRuler
}
+6
View File
@@ -20,6 +20,12 @@ cheerio(html);
cheerio('ul', html);
cheerio('li', 'ul', html);
const $fromElement = cheerio.load($("ul").get(0));
if ($fromElement("ul > li").length !== 3) {
throw new Error("Expecting 3 elements when passing `CheerioElement` to `load()`");
}
$ = cheerio.load(html, {
normalizeWhitespace: true,
xmlMode: true
+1
View File
@@ -259,6 +259,7 @@ interface CheerioElement {
interface CheerioAPI extends CheerioSelector {
load(html: string, options?: CheerioOptionsInterface): CheerioStatic;
load(element: CheerioElement, options?: CheerioOptionsInterface): CheerioStatic;
}
declare var cheerio:CheerioAPI;
+19
View File
@@ -300,3 +300,22 @@ function test_adding_widget() {
});
}
}
function test_focusManager() {
var textarea = document.createElement('textarea');
var instance = CKEDITOR.replace(textarea);
var element = CKEDITOR.document.getById('myElement');
instance.focusManager.focus();
instance.focusManager.focus(element);
instance.focusManager.lock();
instance.focusManager.unlock();
instance.focusManager.blur();
instance.focusManager.blur(true);
instance.focusManager.add(element, true);
instance.focusManager.remove(element);
var focusManager = new CKEDITOR.focusManager(instance);
var object: CKEDITOR.dom.domObject = focusManager.currentActive;
var bool: boolean = focusManager.hasFocus;
}
+12 -1
View File
@@ -544,8 +544,19 @@ declare namespace CKEDITOR {
}
interface focusManager {
class focusManager {
// Properties
currentActive: dom.domObject;
hasFocus: boolean;
// Methods
constructor(editor: editor);
focus(currentActive?: dom.element): void;
lock(): void;
unlock(): void;
blur(noDelay?: boolean): void;
add(element: dom.element, isCapture: boolean): void;
remove(element: dom.element): void;
}
interface keystrokeHandler {
+8
View File
@@ -3,9 +3,17 @@
import colors = require("colors");
colors.enabled = true;
console.log(colors.black.underline('test'));
console.log(colors.rainbow.black.blue.gray('test'));
console.log(colors.random.reset.bgWhite.dim('test'));
console.log(colors.random.reset.bgWhite.strip('test'));
console.log('test'.black.underline);
console.log('test'.rainbow.black.blue.gray);
console.log('test'.random.reset.bgWhite.dim);
console.log('test'.random.reset.bgWhite.dim.stripColors);
colors.enabled = false;
console.log(colors.black.underline('test'));
+11
View File
@@ -7,6 +7,9 @@ declare module "colors" {
interface Color {
(text: string): string;
strip: Color;
stripColors: Color;
black: Color;
red: Color;
green: Color;
@@ -47,6 +50,11 @@ declare module "colors" {
namespace e {
export function setTheme(theme:any): void;
export var enabled: boolean;
export var strip: Color;
export var stripColors: Color;
export var black: Color;
export var red: Color;
export var green: Color;
@@ -88,6 +96,9 @@ declare module "colors" {
}
interface String {
strip: string;
stripColors: string;
black: string;
red: string;
green: string;
+5
View File
@@ -0,0 +1,5 @@
/// <reference path="./concaveman.d.ts" />
import * as concaveman from 'concaveman';
var points = [[10, 20], [30, 12.5]];
var polygon = concaveman(points);
+24
View File
@@ -0,0 +1,24 @@
// Type definitions for concaveman 1.1.0
// Project: https://github.com/mapbox/concaveman
// Definitions by: Denis Carriere <https://github.com/DenisCarriere>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "concaveman" {
/**
* A very fast 2D concave hull algorithm in JavaScript (generates a general outline of a point set).
*
* @name concaveman
* @param {Array<Array<number>>} points is an array of [x, y] points.
* @param {number} [concavity=2] is a relative measure of concavity. 1 results in a relatively detailed shape, Infinity results in a convex hull. You can use values lower than 1, but they can produce pretty crazy shapes.
* @param {number} [lengthThreshold=0] when a segment length is under this threshold, it stops being considered for further detalization. Higher values result in simpler shapes.
* @return {Array<Array<number>>}
* @example
* var points = [[10, 20], [30, 12.5], ...];
* var polygon = concaveman(points);
*
* //=hull
*/
function concaveman(points: number[][], concavity?: number, lengthThreshold?: number): number[][];
namespace concaveman {}
export = concaveman;
}

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