Merge remote-tracking branch 'upstream/master'

* upstream/master: (309 commits)
  parameterize angular/IChangesObject
  add missing options property in schema type fixes #11399
  Changed the stuff asked
  Fixed problem with es6
  Refactoring
  Added electron-devtools-installer
  adds faker version to definition file
  adds faker.lorem.word() as documented here: https://github.com/Marak/faker.js/blob/master/Readme.md#api-methods
  adding algoliasearch-client-js definitions
  Update polymer array splice typings. (#11390)
  Rename "refressh" in  CreateDocumentParams
  angularjs: Refine typings for directive and component definitions
  fixes from code review
  Fixes to the typings so that they are used better
  add i18next-xhr-backend definitions
  Cancel type annotation on function
  Correct types of http version
  It should use boolean, not Boolean
  It should use boolean, not Boolean
  Update react-native.d.ts
  ...
This commit is contained in:
James Bracy
2016-09-22 13:08:15 -07:00
222 changed files with 40357 additions and 12415 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)
@@ -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
+3
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;
+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;
}
}
}
+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;
}
}
+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,
+32 -10
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;
+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 {
+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>
+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'},
+84 -95
View File
@@ -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,22 +1702,33 @@ 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
* place to put initialization code for your controller.
*/
$onInit?(): void;
/**
* 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
@@ -1766,14 +1751,14 @@ declare namespace angular {
*/
$postLink?(): void;
}
interface IOnChangesObject {
[property: string]: IChangesObject;
[property: string]: IChangesObject<any>;
}
interface IChangesObject {
currentValue: any;
previousValue: any;
interface IChangesObject<T> {
currentValue: T;
previousValue: T;
isFirstChange(): boolean;
}
@@ -1813,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
@@ -1826,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
@@ -1837,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};
}
/**
@@ -1855,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)
///////////////////////////////////////////////////////////////////////////
+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;
+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};
@@ -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
+697 -1
View File
@@ -49,6 +49,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 +163,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 +223,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 +360,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;
@@ -236,6 +370,11 @@ declare module "aws-sdk" {
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 {
@@ -424,6 +563,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 {
@@ -593,6 +940,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 {
+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
}
+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
+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;
}
+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.ServerRequest, 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
+1 -1
View File
@@ -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;
}
+20
View File
@@ -0,0 +1,20 @@
/// <reference path="canvas-gauges.d.ts" />
import {
LinearGaugeOptions,
RadialGaugeOptions,
LinearGauge,
RadialGauge
} from 'canvas-gauges';
let linearOptions: LinearGaugeOptions = {
renderTo: document.createElement('canvas')
};
let radialOptions: RadialGaugeOptions = {
renderTo: 'gauge-id'
};
new LinearGauge(linearOptions);
new RadialGauge(radialOptions);
console.log(document.gauges.length);
+263
View File
@@ -0,0 +1,263 @@
// 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 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,
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,
valueBoxStroke?: number,
valueText?: string,
valueTextShadow?: boolean,
valueBoxBorderRadius?: number,
highlights?: Highlight[],
fontNumbers?: string,
fontTitle?: string,
fontUnits?: string,
fontValue?: string,
fontTitleSize?: number,
fontValueSize?: number,
fontUnitsSize?: number,
fontNumbersSize?: number
}
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;
}
+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;
+2
View File
@@ -8,9 +8,11 @@ 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;
+9
View File
@@ -7,6 +7,9 @@ declare module "colors" {
interface Color {
(text: string): string;
strip: Color;
stripColors: Color;
black: Color;
red: Color;
green: Color;
@@ -49,6 +52,9 @@ declare module "colors" {
export var enabled: boolean;
export var strip: Color;
export var stripColors: Color;
export var black: Color;
export var red: Color;
export var green: Color;
@@ -90,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;
}
+2 -2
View File
@@ -1889,7 +1889,7 @@ declare module "core-js/fn/number/max-safe-integer" {
var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER;
export = MAX_SAFE_INTEGER;
}
declare module "core-js/fn/number/min-safe-interger" {
declare module "core-js/fn/number/min-safe-integer" {
var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER;
export = MIN_SAFE_INTEGER;
}
@@ -2668,7 +2668,7 @@ declare module "core-js/library/fn/number/max-safe-integer" {
var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER;
export = MAX_SAFE_INTEGER;
}
declare module "core-js/library/fn/number/min-safe-interger" {
declare module "core-js/library/fn/number/min-safe-integer" {
var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER;
export = MIN_SAFE_INTEGER;
}
+8
View File
@@ -159,6 +159,14 @@ declare module 'couchbase' {
* Creates a manager allowing the management of a Couchbase cluster.
*/
manager(): ClusterManager;
/**
* Creates a manager allowing the management of a Couchbase cluster using credentials.
* @param username The username for your cluster.
* @param password The password for your cluster.
*/
manager(username: string, password: string): ClusterManager;
/**
* Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this.
+16
View File
@@ -0,0 +1,16 @@
/// <reference path="date-fns.d.ts" />
import {addDays, closestIndexTo, differenceInCalendarWeeks, max, isDate} from 'date-fns';
import * as addHours from 'date-fns/add_hours';
function test() {
addDays(new Date(), 5);
closestIndexTo(new Date(), [new Date(), new Date()]);
addHours(new Date(), 5);
differenceInCalendarWeeks(new Date(), new Date());
differenceInCalendarWeeks(new Date(), new Date(), {weekStartsOn: 1});
max(new Date(), new Date());
isDate({});
}
+1195
View File
File diff suppressed because it is too large Load Diff
+13
View File
@@ -5,6 +5,13 @@
declare module "diff-match-patch" {
type Diff = [number, string];
export class Patch {
diffs: Diff[];
start1: number;
start2: number;
length1: number;
length2: number;
}
export class diff_match_patch {
static new (): diff_match_patch;
@@ -31,6 +38,12 @@ declare module "diff-match-patch" {
diff_levenshtein(diffs: Diff[]): number;
diff_toDelta(diffs: Diff[]): string;
diff_fromDelta(text1: string, delta: string): Diff[];
patch_make(text1: any, text2?: string): Patch[];
patch_deepCopy(patches: Patch[]): Patch[];
patch_apply(patches: Patch[], text: string): [string, boolean[]];
patch_fromText(text: string): Patch[];
patch_toText(patches: Patch[]): string;
}
export var DIFF_DELETE: number;
+6 -6
View File
@@ -95,8 +95,8 @@ interface DropzoneOptions {
uploadprogress?(file:DropzoneFile, progress:number, bytesSent:number):void;
totaluploadprogress?(totalProgress:number, totalBytes:number, totalBytesSent:number):void;
sending?(file:DropzoneFile, xhr:XMLHttpRequest, formData:{}):void;
sendingmultiple?(files:DropzoneFile[], xhr:XMLHttpRequest, formData:{}):void;
sending?(file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData):void;
sendingmultiple?(files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData):void;
success?(file: DropzoneFile, response: Object|string): void;
successmultiple?(files:DropzoneFile[], responseText:string):void;
@@ -206,8 +206,8 @@ declare class Dropzone {
on(eventName:"uploadprogress", callback:(file:DropzoneFile, progress:number, bytesSent:number) => any):void;
on(eventName:"totaluploadprogress", callback:(totalProgress:number, totalBytes:number, totalBytesSent:number) => any):void;
on(eventName:"sending", callback:(file:DropzoneFile, xhr:XMLHttpRequest, formData:{}) => any):void;
on(eventName:"sendingmultiple", callback:(files:DropzoneFile[], xhr:XMLHttpRequest, formData:{}) => any):void;
on(eventName:"sending", callback:(file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData) => any):void;
on(eventName:"sendingmultiple", callback:(files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData) => any):void;
on(eventName:"success", callback:(file:DropzoneFile) => any):void;
on(eventName:"successmultiple", callback:(files:DropzoneFile[]) => any):void;
@@ -246,8 +246,8 @@ declare class Dropzone {
emit(eventName:"uploadprogress", file:DropzoneFile, progress:number, bytesSent:number):void;
emit(eventName:"totaluploadprogress", totalProgress:number, totalBytes:number, totalBytesSent:number):void;
emit(eventName:"sending", file:DropzoneFile, xhr:XMLHttpRequest, formData:{}):void;
emit(eventName:"sendingmultiple", files:DropzoneFile[], xhr:XMLHttpRequest, formData:{}):void;
emit(eventName:"sending", file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData):void;
emit(eventName:"sendingmultiple", files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData):void;
emit(eventName:"success", file:DropzoneFile):void;
emit(eventName:"successmultiple", files:DropzoneFile[]):void;
+6 -1
View File
@@ -690,6 +690,11 @@ declare module 'plugins/dialog' {
* @param {object} context The composition context.
*/
compositionComplete(child: HTMLElement, parent: HTMLElement, context: composition.CompositionContext): void;
/**
* Opacity of the blockout. The default is 0.6.
*/
blockoutOpacity?: number;
}
interface Dialog {
@@ -728,7 +733,7 @@ declare module 'plugins/dialog' {
* @param {string} [name] The name of the context to retrieve.
* @returns {DialogContext} True context.
*/
export function getContext(name: string): DialogContext;
export function getContext(name?: string): DialogContext;
/**
* Adds (or replaces) a dialog context.
+9 -10
View File
@@ -14,13 +14,13 @@ declare module 'dva' {
use: (hooks:Object)=>void,
/** dva bootstrap */
start: (selector?:Object)=>void,
start: (selector?:String|HTMLElement)=>void,
/** dva add model */
model: (model:Object)=>void,
/** dva setting router */
router: (router:Object)=>void,
router: (router:Object)=>Object|JSX.Element,
};
}
@@ -34,7 +34,7 @@ declare module 'dva/router' {
history?: Object
}
export class Router extends React.Component<RouterProps, {}> {
render(): JSX.Element
render():JSX.Element
}
@@ -43,15 +43,14 @@ declare module 'dva/router' {
component?: React.ReactNode
}
export class Route extends React.Component<RouteProps, {}> {
render(): JSX.Element
render():JSX.Element
}
}
/**
* https://github.com/reactjs/react-router-redux
*/
declare module 'dva/routerRedux' {
export default Object;
/**
* https://github.com/reactjs/react-router-redux
*/
export class routerRedux {}
}
/**
+2
View File
@@ -650,6 +650,7 @@ declare namespace createjs {
autoReset: boolean;
static buildDate: string;
currentFrame: number;
totalFrames: number;
currentLabel: string;
frameBounds: Rectangle[];
framerate: number;
@@ -662,6 +663,7 @@ declare namespace createjs {
startPosition: number;
static SYNCHED: string;
timeline: Timeline;
duration: number;
static version: string;
// methods
+40
View File
@@ -45,4 +45,44 @@ client.create({
index: 'index',
type: 'type'
}, (err, repsonse, status) => {
});
client.cluster.getSettings({
masterTimeout: 100
}, (err, response) => {
});
client.cluster.health({
masterTimeout: 100
}, (err, response) => {
});
client.cluster.pendingTasks({
ignore: 1
}, (err, response) => {
});
client.cluster.putSettings({
ignore: 1
}, (err, response) => {
});
client.cluster.putSettings({
ignore: 1
}, (err, response) => {
});
client.cluster.reroute({
ignore: 1
}, (err, response) => {
});
client.cluster.state({
ignore: 1
}, (err, response) => {
});
client.cluster.stats({
ignore: 1
}, (err, response) => {
});
+105 -8
View File
@@ -1,26 +1,28 @@
// Type definitions for elasticsearch
// Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html
// Definitions by: Casper Skydt <https://github.com/CasperSkydt/DefinitelyTyped>
// Definitions by: Casper Skydt <https://github.com/CasperSkydt>, Blake Smith <https://github.com/bfsmith>, Dave Dunkin <https://github.com/ddunkin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module Elasticsearch {
export class Client {
constructor(params: ConfigOptions);
indices: Indices;
cluster: Cluster;
cat: Cat;
bulk(params: BulkIndexDocumentsParams): PromiseLike<any>;
bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void;
create(params: CreateDocumentParams): PromiseLike<any>;
create(params: CreateDocumentParams, callback: (err: any, response: any, status: any) => void): void;
delete(params: DeleteDocumentParams): PromiseLike<any>;
delete(params: DeleteDocumentParams, callback: (error: any, response: any) => void): void;
get(params: GetParams, callback: (error: any, response: any) => void): void;
get<T>(params: GetParams, callback: (error: any, response: GetResponse<T>) => void): void;
get<T>(params: GetParams): PromiseLike<GetResponse<T>>;
index<T>(params: IndexDocumentParams<T>): PromiseLike<any>;
index<T>(params: IndexDocumentParams<T>, callback: (error: any, response: any) => void): void;
mget(params: MGetParams, callback: (error: any, response: any) => void): void;
mget<T>(params: MGetParams): PromiseLike<GetResponse<T>>;
msearch(params: MSearchParams, callback: (error: any, response: any) => void): void;
msearch<T>(params: MSearchParams): PromiseLike<GetResponse<T>>;
mget<T>(params: MGetParams, callback: (error: any, response: MGetResponse<T>) => void): void;
mget<T>(params: MGetParams): PromiseLike<MGetResponse<T>>;
msearch<T>(params: MSearchParams, callback: (error: any, response: MSearchResponse<T>) => void): void;
msearch<T>(params: MSearchParams): PromiseLike<MSearchResponse<T>>;
ping(params: PingParams): PromiseLike<any>;
ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void;
scroll(params: ScrollParams): PromiseLike<any>;
@@ -107,7 +109,7 @@ declare module Elasticsearch {
export interface CreateDocumentParams extends GenericParams {
consistency?: "one" | "quorum" | "all";
parent?: string;
refressh?: boolean;
refresh?: boolean;
routing?: string;
timeout?: number | Date;
timestamp?: number | Date;
@@ -194,7 +196,8 @@ declare module Elasticsearch {
versionType?: string;
}
export interface GetResponse<T> extends GenericParams {
export interface GetResponse<T> {
_index: string;
_type: string;
_id: string;
_version: number;
@@ -230,6 +233,7 @@ declare module Elasticsearch {
scroll?: string;
search_type?: string;
fields?: string[];
from?: number;
size?: number;
sort?: string | string[] | boolean;
_source?: string | string[] | boolean;
@@ -276,6 +280,10 @@ declare module Elasticsearch {
search_type?: string;
}
export interface MSearchResponse<T> {
responses?: SearchResponse<T>[];
}
export interface MGetParams extends GenericParams {
fields?: string | string[] | Boolean;
preference?: string;
@@ -287,6 +295,10 @@ declare module Elasticsearch {
type?: string;
}
export interface MGetResponse<T> {
docs?: GetResponse<T>[];
}
export interface IndicesIndexExitsParams extends GenericParams {
index: string | string[] | boolean;
ignoreUnavailable?: boolean;
@@ -333,6 +345,91 @@ declare module Elasticsearch {
body: string | any;
index: string | string[] | boolean;
}
export interface Cat {
health(params: CatHealthOptions, callback: (error: any, response: any) => void): void;
health(params: CatHealthOptions): PromiseLike<any>
}
export interface CatHealthOptions extends GenericParams {
local?: boolean;
masterTimeout?: number | Date;
h?: string | string[] | boolean;
help?: boolean;
ts?: boolean;
v?: boolean;
}
export interface Cluster {
getSettings(params: ClusterGetSettingsOptions, callback: (error: any, response: any) => void): void;
getSettings(params: ClusterGetSettingsOptions): PromiseLike<any>;
health(params: ClusterHealthOptions, callback: (error: any, response: any) => void): void;
health(params: ClusterHealthOptions): PromiseLike<any>;
pendingTasks(params: ClusterPendingTasksOptions, callback: (error: any, response: any) => void): void;
pendingTasks(params: ClusterPendingTasksOptions): PromiseLike<any>;
putSettings(params: ClusterPutSettingsOptions, callback: (error: any, response: any) => void): void;
putSettings(params: ClusterPutSettingsOptions): PromiseLike<any>;
reroute(params: ClusterRerouteOptions, callback: (error: any, response: any) => void): void;
reroute(params: ClusterRerouteOptions): PromiseLike<any>;
state(params: ClusterStateOptions, callback: (error: any, response: any) => void): void;
state(params: ClusterStateOptions): PromiseLike<any>;
stats(params: ClusterStatsOptions, callback: (error: any, response: any) => void): void;
stats(params: ClusterStatsOptions): PromiseLike<any>;
}
export interface ClusterGetSettingsOptions extends GenericParams {
flatSettings?: boolean;
masterTimeout?: number | Date;
timeout?: number | Date;
}
export interface ClusterHealthOptions extends GenericParams {
level?: string; // cluster, indices, shards
local?: boolean;
masterTimeout?: number | Date;
waitForActiveShards?: number;
waitForNodes?: string;
waitForRelocatingShards?: number;
waitForStatus?: string; // green, yellow, red
index?: string | string[] | boolean;
}
export interface ClusterPendingTasksOptions extends GenericParams {
local?: boolean;
masterTimeout?: number | Date;
}
export interface ClusterPutSettingsOptions extends GenericParams {
flatSettings?: boolean;
masterTimeout?: number | Date;
timeout?: number | Date;
}
export interface ClusterRerouteOptions extends GenericParams {
dryRun?: boolean;
explain?: boolean;
metric?: string | string[] | boolean;
masterTimeout?: number | Date;
timeout?: number | Date;
}
export interface ClusterStateOptions extends GenericParams {
local?: boolean;
masterTimeout?: number | Date;
flatSettings?: boolean;
ignoreUnavailable?: boolean;
allowNoIndices?: boolean;
expandWildcards?: string; // open, closed, none, all (default open)
index?: string | string[] | boolean;
metric?: string | string[] | boolean;
}
export interface ClusterStatsOptions extends GenericParams {
flatSettings?: boolean;
human?: boolean;
timeout?: number | Date;
nodeId?: string | string[] | boolean;
}
}
declare module "elasticsearch" {
@@ -0,0 +1,20 @@
/// <reference path="../github-electron/github-electron.d.ts" />
/// <reference path="electron-devtools-installer.d.ts" />
import installExtension, {
EMBER_INSPECTOR, REACT_DEVELOPER_TOOLS,
BACKBONE_DEBUGGER, JQUERY_DEBUGGER,
ANGULARJS_BATARANG, VUEJS_DEVTOOLS,
REDUX_DEVTOOLS, REACT_PERF,
} from 'electron-devtools-installer';
installExtension(EMBER_INSPECTOR);
installExtension(REACT_DEVELOPER_TOOLS);
installExtension(BACKBONE_DEBUGGER);
installExtension(JQUERY_DEBUGGER);
installExtension(ANGULARJS_BATARANG);
installExtension(VUEJS_DEVTOOLS);
installExtension(REDUX_DEVTOOLS);
installExtension(REACT_PERF);
installExtension('abcdefghijkl');
@@ -0,0 +1,24 @@
// Type definitions for electron-devtools-installer v2.0.1
// Project: https://github.com/MarshallOfSound/electron-devtools-installer
// Definitions by: Robin Van den Broeck <https://github.com/gamesmaxed>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "electron-devtools-installer" {
interface ExtensionReference {
id: string,
electron: string,
}
// Default installation function
export default function (extensionReference: ExtensionReference | string, forceDownload?: boolean): Promise<string>;
// Devtools themself
export const EMBER_INSPECTOR: ExtensionReference;
export const REACT_DEVELOPER_TOOLS: ExtensionReference;
export const BACKBONE_DEBUGGER: ExtensionReference;
export const JQUERY_DEBUGGER: ExtensionReference;
export const ANGULARJS_BATARANG: ExtensionReference;
export const VUEJS_DEVTOOLS: ExtensionReference;
export const REDUX_DEVTOOLS: ExtensionReference;
export const REACT_PERF: ExtensionReference;
}
+1
View File
@@ -458,6 +458,7 @@ declare module "enzyme" {
export interface ReactWrapper<P, S> extends CommonWrapper<P, S> {
unmount(): ReactWrapper<any, any>;
mount(): ReactWrapper<any, any>;
render(): CheerioWrapper<P, S>;
/**
* Returns a wrapper of the node that matches the provided reference name.
@@ -97,6 +97,10 @@ declare module "express-serve-static-core" {
use: IRouterHandler<this> & IRouterMatcher<this>;
route(prefix: PathParams): IRoute;
/**
* Stack of configured routes
*/
stack: any[];
}
interface IRoute {
@@ -1046,6 +1050,11 @@ declare module "express-serve-static-core" {
* simply by removing them from this object.
*/
routes: any;
/**
* Used to get all registered routes in Express Application
*/
_router: any;
}
interface Express extends Application {
+96 -83
View File
@@ -1,101 +1,114 @@
/// <reference path="express.d.ts" />
/// <reference path="../node/node.d.ts" />
import * as express from 'express';
var app = express();
app.engine('jade', require('jade').__express);
app.engine('html', require('ejs').renderFile);
express.static.mime.define({
'application/fx': ['fx']
});
app.use('/static', express.static(__dirname + '/public'));
// simple logger
app.use(function(req, res, next){
console.log('%s %s', req.method, req.url);
next();
});
app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) {
console.error(err);
next(err);
});
app.get('/', function(req, res){
res.send('hello world');
});
namespace express_tests {
const router = express.Router();
var app = express();
app.engine('jade', require('jade').__express);
app.engine('html', require('ejs').renderFile);
const pathStr : string = 'test';
const pathRE : RegExp = /test/;
const path = true? pathStr : pathRE;
express.static.mime.define({
'application/fx': ['fx']
});
app.use('/static', express.static(__dirname + '/public'));
router.get(path);
router.put(path)
router.post(path);
router.delete(path);
router.get(pathStr);
router.put(pathStr)
router.post(pathStr);
router.delete(pathStr);
router.get(pathRE);
router.put(pathRE)
router.post(pathRE);
router.delete(pathRE);
router.use((req, res, next) => { next(); })
router.route('/users')
.get((req, res, next) => {
let types: string[] = req.accepts();
let type: string | boolean = req.accepts('json');
type = req.accepts(['json', 'text']);
type = req.accepts('json', 'text');
let charsets: string[] = req.acceptsCharsets();
let charset: string | boolean = req.acceptsCharsets('utf-8');
charset = req.acceptsCharsets(['utf-8', 'utf-16']);
charset = req.acceptsCharsets('utf-8', 'utf-16');
let encodings: string[] = req.acceptsEncodings();
let encoding: string | boolean = req.acceptsEncodings('gzip');
encoding = req.acceptsEncodings(['gzip', 'deflate']);
encoding = req.acceptsEncodings('gzip', 'deflate');
let languages: string[] = req.acceptsLanguages();
let language: string | boolean = req.acceptsLanguages('en');
language = req.acceptsLanguages(['en', 'ja']);
language = req.acceptsLanguages('en', 'ja');
res.send(req.query['token']);
// simple logger
app.use(function(req, res, next) {
console.log('%s %s', req.method, req.url);
next();
});
router.get('/user/:id', function(req, res, next) {
if (req.params.id == 0) next('route');
else next();
}, function(req, res, next) {
res.render('regular');
});
app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) {
console.error(err);
next(err);
});
app.use((req, res, next) => {
// hacky trick, router is just a handler
router(req, res, next);
});
app.use(router);
app.get('/', function(req, res) {
res.send('hello world');
});
app.listen(3000);
const router = express.Router();
const next: express.NextFunction = () => {};
const nextWithArgument: express.NextFunction = (err: any) => {};
/**
* The express.Application is compatible with http.createServer
*/
const pathStr: string = 'test';
const pathRE: RegExp = /test/;
const path = true ? pathStr : pathRE;
router.get(path);
router.put(path)
router.post(path);
router.delete(path);
router.get(pathStr);
router.put(pathStr)
router.post(pathStr);
router.delete(pathStr);
router.get(pathRE);
router.put(pathRE)
router.post(pathRE);
router.delete(pathRE);
router.use((req, res, next) => { next(); })
router.route('/users')
.get((req, res, next) => {
let types: string[] = req.accepts();
let type: string | boolean = req.accepts('json');
type = req.accepts(['json', 'text']);
type = req.accepts('json', 'text');
let charsets: string[] = req.acceptsCharsets();
let charset: string | boolean = req.acceptsCharsets('utf-8');
charset = req.acceptsCharsets(['utf-8', 'utf-16']);
charset = req.acceptsCharsets('utf-8', 'utf-16');
let encodings: string[] = req.acceptsEncodings();
let encoding: string | boolean = req.acceptsEncodings('gzip');
encoding = req.acceptsEncodings(['gzip', 'deflate']);
encoding = req.acceptsEncodings('gzip', 'deflate');
let languages: string[] = req.acceptsLanguages();
let language: string | boolean = req.acceptsLanguages('en');
language = req.acceptsLanguages(['en', 'ja']);
language = req.acceptsLanguages('en', 'ja');
res.send(req.query['token']);
});
router.get('/user/:id', function(req, res, next) {
if (req.params.id == 0) next('route');
else next();
}, function(req, res, next) {
res.render('regular');
});
app.use((req, res, next) => {
// hacky trick, router is just a handler
router(req, res, next);
});
app.use(router);
app.listen(3000);
const next: express.NextFunction = () => { };
}
/***************************
* *
* Test with other modules *
* *
***************************/
import * as http from 'http';
http.createServer(app);
namespace node_tests {
{
// http.createServer can take express application
const app: express.Application = express();
http.createServer(app).listen(5678);
}
}
-2
View File
@@ -333,7 +333,6 @@ declare namespace fabric {
on(eventName: {[key:string] : Function}): T;
/**
* Fires event with an optional options object
* @deprecated `fire` deprecated since 1.0.7 (use `trigger` instead)
* @param {String} eventName Event name to fire
* @param {Object} [options] Options object
*/
@@ -341,7 +340,6 @@ declare namespace fabric {
/**
* Stops event observing for a particular event handler. Calling this method
* without arguments removes all handlers for all events
* @deprecated `stopObserving` deprecated since 0.8.34 (use `off` instead)
* @param eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
* @param handler Function to be deleted from EventListeners
*/
+6
View File
@@ -14,6 +14,12 @@ FB.getLoginStatus(function(response: fb.AuthResponse) {
console.log(response.authResponse.accessToken);
});
FB.getLoginStatus(function(response: fb.AuthResponse) {
console.log(response);
console.log(response.status);
console.log(response.authResponse.accessToken);
}, true);
FB.getAuthResponse(function(response: fb.AuthResponse) {
console.log(response);
console.log(response.status);
+9 -7
View File
@@ -8,10 +8,11 @@ declare var FB: fb.FacebookStatic;
declare namespace facebook {
interface FacebookStatic {
// api: any;
// AppEvents: any;
// Canvas: any;
// Event: any;
api: any;
AppEvents: any;
Canvas: any;
Event: any;
/**
* The method FB.getAuthResponse() is a synchronous accessor for the current authResponse.
* The synchronous nature of this method is what sets it apart from the other login methods.
@@ -25,7 +26,7 @@ declare namespace facebook {
*
* @param callback function to handle the response.
*/
getLoginStatus(callback: (response: AuthResponse) => void): void;
getLoginStatus(callback: (response: AuthResponse) => void, roundtrip?: boolean ): void;
/**
* The method FB.init() is used to initialize and setup the SDK.
*
@@ -49,8 +50,9 @@ declare namespace facebook {
* @param callback function to handle the response
*/
logout(callback: (response: AuthResponse) => void): void;
// ui: any;
// XFBML: any;
ui: any;
XFBML: any;
}
interface InitParams {
+1
View File
@@ -123,6 +123,7 @@ resultStr = faker.internet.mac();
resultStr = faker.internet.password();
resultStr = faker.internet.password(0, false, '#', 'foo');
resultStr = faker.lorem.word();
resultStr = faker.lorem.words();
resultStr = faker.lorem.words(0);
resultStr = faker.lorem.sentence();
+2 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for faker
// Type definitions for faker v3.1
// Project: http://marak.com/faker.js/
// Definitions by: Bas Pennings <https://github.com/basp/>, Yuki Kokubun <https://github.com/Kuniwak>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -135,6 +135,7 @@ declare namespace Faker {
};
lorem: {
word(): string;
words(num?: number): string;
sentence(wordCount?: number, range?: number): string;
sentences(sentenceCount?: number): string;
+1 -1
View File
@@ -6,7 +6,7 @@
// Imported from: https://github.com/soywiz/typescript-node-definitions/fs-extra.d.ts via TSD fs-extra definition
///<reference path="../node/node.d.ts"/>
///<reference path="../bluebird/bluebird-2.0.d.ts"/>
///<reference path="../bluebird/bluebird.d.ts"/>
declare module "fs-extra-promise" {
import stream = require("stream");
@@ -240,6 +240,63 @@ app.setUserTasks([
}
]);
app.setUserTasks([]);
app.setJumpList([
{
type: 'custom',
name: 'Recent Projects',
items: [
{ type: 'file', path: 'C:\\Projects\\project1.proj' },
{ type: 'file', path: 'C:\\Projects\\project2.proj' }
]
},
{ // has a name so type is assumed to be "custom"
name: 'Tools',
items: [
{
type: 'task',
title: 'Tool A',
program: process.execPath,
args: '--run-tool-a',
iconPath: process.execPath,
iconIndex: 0,
description: 'Runs Tool A'
},
{
type: 'task',
title: 'Tool B',
program: process.execPath,
args: '--run-tool-b',
iconPath: process.execPath,
iconIndex: 0,
description: 'Runs Tool B'
}]
},
{
type: 'frequent'
},
{ // has no name and no type so type is assumed to be "tasks"
items: [
{
type: 'task',
title: 'New Project',
program: process.execPath,
args: '--new-project',
description: 'Create a new project.'
},
{
type: 'separator'
},
{
type: 'task',
title: 'Recover Project',
program: process.execPath,
args: '--recover-project',
description: 'Recover Project'
}]
}
]);
if (app.isUnityRunning()) {
}
if (app.isAccessibilitySupportEnabled()) {
+132 -9
View File
@@ -1,4 +1,4 @@
// Type definitions for Electron v1.3.4
// Type definitions for Electron v1.3.6
// Project: http://electron.atom.io/
// Definitions by: jedmao <https://github.com/jedmao/>, rhysd <https://rhysd.github.io>, Milan Burda <https://github.com/miniak/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -62,7 +62,7 @@ declare namespace Electron {
/**
* Emitted when Electron has finished initialization.
*/
on(event: 'ready', listener: Function): this;
on(event: 'ready', listener: (event: Event, launchInfo: Object) => void): this;
/**
* Emitted when all windows have been closed.
*
@@ -199,7 +199,7 @@ declare namespace Electron {
* All windows will be closed immediately without asking user
* and the before-quit and will-quit events will not be emitted.
*/
exit(exitCode: number): void;
exit(exitCode?: number): void;
/**
* Relaunches the app when current instance exits.
*
@@ -218,6 +218,10 @@ declare namespace Electron {
args?: string[],
execPath?: string
}): void;
/**
* @returns Whether Electron has finished initializing.
*/
isReady(): boolean;
/**
* On Linux, focuses on the first visible window.
* On macOS, makes the application the active app.
@@ -333,6 +337,19 @@ declare namespace Electron {
* Note: This API is only available on Windows.
*/
setUserTasks(tasks: Task[]): boolean;
/**
* Note: This API is only available on Windows.
*/
getJumpListSettings(): JumpListSettings;
/**
* Sets or removes a custom Jump List for the application.
*
* If categories is null the previously set custom Jump List (if any) will be replaced
* by the standard Jump List for the app (managed by Windows).
*
* Note: This API is only available on Windows.
*/
setJumpList(categories: JumpListCategory[]): SetJumpListResult;
/**
* This method makes your application a Single Instance Application instead of allowing
* multiple instances of your app to run, this will ensure that only a single instance
@@ -560,6 +577,89 @@ declare namespace Electron {
iconIndex?: number;
}
/**
* ok - Nothing went wrong.
* error - One or more errors occured, enable runtime logging to figure out the likely cause.
* invalidSeparatorError - An attempt was made to add a separator to a custom category in the Jump List.
* Separators are only allowed in the standard Tasks category.
* fileTypeRegistrationError - An attempt was made to add a file link to the Jump List
* for a file type the app isn't registered to handle.
* customCategoryAccessDeniedError - Custom categories can't be added to the Jump List
* due to user privacy or group policy settings.
*/
type SetJumpListResult = 'ok' | 'error' | 'invalidSeparatorError' | 'fileTypeRegistrationError' | 'customCategoryAccessDeniedError';
interface JumpListSettings {
/**
* The minimum number of items that will be shown in the Jump List.
*/
minItems: number;
/**
* Items that the user has explicitly removed from custom categories in the Jump List.
*/
removedItems: JumpListItem[];
}
interface JumpListCategory {
/**
* tasks - Items in this category will be placed into the standard Tasks category.
* frequent - Displays a list of files frequently opened by the app, the name of the category and its items are set by Windows.
* recent - Displays a list of files recently opened by the app, the name of the category and its items are set by Windows.
* custom - Displays tasks or file links, name must be set by the app.
*/
type?: 'tasks' | 'frequent' | 'recent' | 'custom';
/**
* Must be set if type is custom, otherwise it should be omitted.
*/
name?: string;
/**
* Array of JumpListItem objects if type is tasks or custom, otherwise it should be omitted.
*/
items?: JumpListItem[];
}
interface JumpListItem {
/**
* task - A task will launch an app with specific arguments.
* separator - Can be used to separate items in the standard Tasks category.
* file - A file link will open a file using the app that created the Jump List.
*/
type: 'task' | 'separator' | 'file';
/**
* Path of the file to open, should only be set if type is file.
*/
path?: string;
/**
* Path of the program to execute, usually you should specify process.execPath which opens the current program.
* Should only be set if type is task.
*/
program?: string;
/**
* The command line arguments when program is executed. Should only be set if type is task.
*/
args?: string;
/**
* The text to be displayed for the item in the Jump List. Should only be set if type is task.
*/
title?: string;
/**
* Description of the task (displayed in a tooltip). Should only be set if type is task.
*/
description?: string;
/**
* The absolute path to an icon to be displayed in a Jump List, which can be an arbitrary
* resource file that contains an icon (e.g. .ico, .exe, .dll).
* You can usually specify process.execPath to show the program icon.
*/
iconPath?: string;
/**
* The index of the icon in the resource file. If a resource file contains multiple icons
* this value can be used to specify the zero-based index of the icon that should be displayed
* for this task. If a resource file contains only one icon, this property should be set to zero.
*/
iconIndex?: number;
}
interface LoginItemSettings {
/**
* True if the app is set to open at login.
@@ -1271,6 +1371,12 @@ declare namespace Electron {
}
interface WebPreferences {
/**
* Whether to enable DevTools.
* If it is set to false, can not use BrowserWindow.webContents.openDevTools() to open DevTools.
* Default: true.
*/
devTools?: boolean;
/**
* Whether node integration is enabled.
* Default: true.
@@ -1861,7 +1967,7 @@ declare namespace Electron {
interface CrashReporterStartOptions {
/**
* Default: Electron
* Default: app.getName()
*/
productName?: string;
companyName: string;
@@ -3296,16 +3402,18 @@ declare namespace Electron {
interface Shell {
/**
* Show the given file in a file manager. If possible, select the file.
* @returns Whether the item was successfully shown.
*/
showItemInFolder(fullPath: string): void;
showItemInFolder(fullPath: string): boolean;
/**
* Open the given file in the desktop's default manner.
* @returns Whether the item was successfully shown.
*/
openItem(fullPath: string): void;
openItem(fullPath: string): boolean;
/**
* Open the given external protocol URL in the desktop's default manner
* (e.g., mailto: URLs in the default mail user agent).
* @returns true if an application was available to open the URL, false otherwise.
* @returns Whether an application was available to open the URL.
*/
openExternal(url: string, options?: {
/**
@@ -3316,7 +3424,7 @@ declare namespace Electron {
}): boolean;
/**
* Move the given file to trash.
* @returns boolean status for the operation.
* @returns Whether the item was successfully moved to the trash.
*/
moveItemToTrash(fullPath: string): boolean;
/**
@@ -3595,7 +3703,7 @@ declare namespace Electron {
interface WebContentsStatic {
/**
* @returns An array of all web contents. This will contain web contents for all windows,
* @returns An array of all WebContents instances. This will contain web contents for all windows,
* webviews, opened devtools, and devtools extension background pages.
*/
getAllWebContents(): WebContents[];
@@ -3603,6 +3711,10 @@ declare namespace Electron {
* @returns The web contents that is focused in this application, otherwise returns null.
*/
getFocusedWebContents(): WebContents;
/**
* Find a WebContents instance according to its ID.
*/
fromId(id: number): WebContents;
}
/**
@@ -4971,6 +5083,17 @@ declare namespace Electron {
* See webContents.sendInputEvent for detailed description of event object.
*/
sendInputEvent(event: SendInputEvent): void
/**
* Changes the zoom factor to the specified factor.
* Zoom factor is zoom percent divided by 100, so 300% = 3.0.
*/
setZoomFactor(factor: number): void;
/**
* Changes the zoom level to the specified level.
* The original size is 0 and each increment above or below represents
* zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively.
*/
setZoomLevel(level: number): void;
/**
* Shows pop-up dictionary that searches the selected word on the page.
* Note: This API is available only on macOS.
+362
View File
@@ -0,0 +1,362 @@
/// <reference path="gl-matrix-legacy.d.ts" />
// common
var result: number = glMatrix.toRadian(180);
var out: GLM.IArray;
var outVal: number;
var outStr: string;
// vec2
var vecA: GLM.IArray, vecB: GLM.IArray, matA: GLM.IArray;
var vecArray: GLM.IArray;
vecA = [1, 2];
vecB = new Float32Array([3, 4]);
out = [0, 0];
matA = [1, 2, 3, 4, 5, 6];
vecArray = [1, 2, 3, 4, 0, 0];
out = vec2.create();
out = vec2.clone(vecA);
out = vec2.fromValues(1, 2);
out = vec2.copy(out, vecA);
out = vec2.set(out, 1, 2);
out = vec2.add(out, vecA, vecB);
out = vec2.subtract(out, vecA, vecB);
out = vec2.sub(out, vecA, vecB);
out = vec2.multiply(out, vecA, vecB);
out = vec2.mul(out, vecA, vecB);
out = vec2.divide(out, vecA, vecB);
out = vec2.div(out, vecA, vecB);
out = vec2.min(out, vecA, vecB);
out = vec2.max(out, vecA, vecB);
out = vec2.scale(out, vecA, 2);
out = vec2.scaleAndAdd(out, vecA, vecB, 0.5);
outVal = vec2.distance(vecA, vecB);
outVal = vec2.dist(vecA, vecB);
outVal = vec2.squaredDistance(vecA, vecB);
outVal = vec2.sqrDist(vecA, vecB);
outVal = vec2.length(vecA);
outVal = vec2.len(vecA);
outVal = vec2.squaredLength(vecA);
outVal = vec2.sqrLen(vecA);
out = vec2.negate(out, vecA);
out = vec2.inverse(out, vecA);
out = vec2.normalize(out, vecA);
outVal = vec2.dot(vecA, vecB);
out = vec2.cross(out, vecA, vecB);
out = vec2.lerp(out, vecA, vecB, 0.5);
out = vec2.random(out);
out = vec2.random(out, 5.0);
out = vec2.transformMat2(out, vecA, matA);
out = vec2.transformMat2d(out, vecA, matA);
out = vec2.transformMat3(out, vecA, matA);
out = vec2.transformMat4(out, vecA, matA);
out = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize);
outStr = vec2.str(vecA);
// vec3
var matr: GLM.IArray;
var q: GLM.IArray;
vecA = [1, 2, 3];
vecB = new Float32Array([4, 5, 6]);
out = [0, 0, 0];
vecArray = [1, 2, 3, 4, 5, 6, 0, 0, 0];
matr = [1, 0, 0, 0, 1, 0, 0, 0, 1 ];
out = vec3.create();
out = vec3.clone(vecA);
out = vec3.fromValues(1, 2, 3);
out = vec3.copy(out, vecA);
out = vec3.set(out, 1, 2, 3);
out = vec3.add(out, vecA, vecB);
out = vec3.subtract(out, vecA, vecB);
out = vec3.sub(out, vecA, vecB);
out = vec3.multiply(out, vecA, vecB);
out = vec3.mul(out, vecA, vecB);
out = vec3.divide(out, vecA, vecB);
out = vec3.div(out, vecA, vecB);
out = vec3.min(out, vecA, vecB);
out = vec3.max(out, vecA, vecB);
out = vec3.scale(out, vecA, 2);
out = vec3.scaleAndAdd(out, vecA, vecB, 0.5);
outVal = vec3.distance(vecA, vecB);
outVal = vec3.dist(vecA, vecB);
outVal = vec3.squaredDistance(vecA, vecB);
outVal = vec3.sqrDist(vecA, vecB);
outVal = vec3.length(vecA);
outVal = vec3.len(vecA);
outVal = vec3.squaredLength(vecA);
outVal = vec3.sqrLen(vecA);
out = vec3.negate(out, vecA);
out = vec3.inverse(out, vecA);
out = vec3.normalize(out, vecA);
outVal = vec3.dot(vecA, vecB);
out = vec3.cross(out, vecA, vecB);
out = vec3.lerp(out, vecA, vecB, 0.5);
out = vec3.random(out);
out = vec3.random(out, 5.0);
out = vec3.rotateX(out, vecA, vecB, Math.PI);
out = vec3.rotateY(out, vecA, vecB, Math.PI);
out = vec3.rotateZ(out, vecA, vecB, Math.PI);
out = vec3.transformMat3(out, vecA, matr);
matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ];
out = vec3.transformMat4(out, vecA, matr);
q = [1, 2, 3, 4];
out = vec3.transformQuat(out, vecA, matr);
out = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize);
outVal = vec3.angle(vecA, vecB);
outStr = vec3.str(vecA);
// vec4
var q: GLM.IArray;
vecA = [1, 2, 3, 4];
vecB = new Float32Array([5, 6, 7, 8]);
out = [0, 0, 0, 0];
q = [1, 2, 3, 4];
out = vec4.create();
out = vec4.clone(vecA);
out = vec4.fromValues(1, 2, 3, 4);
out = vec4.copy(out, vecA);
out = vec4.set(out, 1, 2, 3, 4);
out = vec4.add(out, vecA, vecB);
out = vec4.subtract(out, vecA, vecB);
out = vec4.sub(out, vecA, vecB);
out = vec4.multiply(out, vecA, vecB);
out = vec4.mul(out, vecA, vecB);
out = vec4.divide(out, vecA, vecB);
out = vec4.div(out, vecA, vecB);
out = vec4.min(out, vecA, vecB);
out = vec4.max(out, vecA, vecB);
out = vec4.scale(out, vecA, 2);
out = vec4.scaleAndAdd(out, vecA, vecB, 0.5);
outVal = vec4.distance(vecA, vecB);
outVal = vec4.dist(vecA, vecB);
outVal = vec4.squaredDistance(vecA, vecB);
outVal = vec4.sqrDist(vecA, vecB);
outVal = vec4.length(vecA);
outVal = vec4.len(vecA);
outVal = vec4.squaredLength(vecA);
outVal = vec4.sqrLen(vecA);
out = vec4.negate(out, vecA);
out = vec4.inverse(out, vecA);
out = vec4.normalize(out, vecA);
outVal = vec4.dot(vecA, vecB);
out = vec4.lerp(out, vecA, vecB, 0.5);
out = vec4.random(out);
out = vec4.random(out, 5.0);
matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]
out = vec4.transformMat4(out, vecA, matr);
out = vec4.transformQuat(out, vecA, q);
vecArray = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0];
out = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize);
outStr = vec4.str(vecA);
// mat2
var matB: GLM.IArray, identity: GLM.IArray;
matA = [1, 2, 3, 4];
matB = new Float32Array([5, 6, 7, 8]);
out = [0, 0, 0, 0];
identity = [1, 0, 0, 1];
out = mat2.create();
out = mat2.clone(matA);
out = mat2.copy(out, matA);
out = mat2.identity(out);
out = mat2.transpose(out, matA);
out = mat2.invert(out, matA);
out = mat2.adjoint(out, matA);
outVal = mat2.determinant(matA);
out = mat2.multiply(out, matA, matB);
out = mat2.mul(out, matA, matB);
out = mat2.rotate(out, matA, Math.PI * 0.5);
vecA = [2, 3];
out = mat2.scale(out, matA, vecA);
outStr = mat2.str(matA);
outVal = mat2.frob(matA);
var L = mat2.create();
var D = mat2.create();
var U = mat2.create();
out = mat2.LDU(L, D, U, [4,3,6,3]);
// mat2d
matA = [1, 2, 3, 4, 5, 6];
matB = [7, 8, 9, 10, 11, 12];
out = [0, 0, 0, 0, 0, 0];
identity = [1, 0, 0, 1, 0, 0];
out = mat2d.create();
out = mat2d.clone(matA);
out = mat2d.copy(out, matA);
out = mat2d.identity(out);
out = mat2d.invert(out, matA);
outVal = mat2d.determinant(matA);
out = mat2d.multiply(out, matA, matB);
out = mat2d.mul(out, matA, matB);
out = mat2d.rotate(out, matA, Math.PI * 0.5);
vecA = [2, 3];
out = mat2d.scale(out, matA, vecA);
out = mat2d.translate(out, matA, vecA);
outStr = mat2d.str(matA);
outVal = mat2d.frob(matA);
// mat3
matA = [1, 0, 0, 0, 1, 0, 1, 2, 1];
matB = [1, 0, 0, 0, 1, 0, 3, 4, 1];
out = [0, 0, 0, 0, 0, 0, 0, 0, 0];
identity = [1, 0, 0, 0, 1, 0, 0, 0, 1];
out = mat3.create();
out = mat3.clone(matA);
out = mat3.copy(out, matA);
out = mat3.identity(out);
out = mat3.transpose(out, matA);
out = mat3.invert(out, matA);
out = mat3.adjoint(out, matA);
outVal = mat3.determinant(matA);
out = mat3.multiply(out, matA, matB);
out = mat3.mul(out, matA, matB);
outStr = mat3.str(matA);
outVal = mat3.frob(matA);
matA = [1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1];
out = mat3.normalFromMat4(out, matA);
q = [ 0, -0.7071067811865475, 0, 0.7071067811865475 ];
out = mat3.fromQuat(out, q);
out = mat3.normalFromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]);
out = mat3.fromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]);
out = mat3.scale(out, matA, [2,2]);
out = mat3.fromMat2d(out, [1, 2, 3, 4, 5, 6]);
out = mat3.translate(out, matA, [1, 2, 3]);
out = mat3.rotate(out, matA, Math.PI/2);
// mat4
matA = [1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
1, 2, 3, 1];
matB = [1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
4, 5, 6, 1];
out = [0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0];
identity = [1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1];
out = mat4.create();
out = mat4.clone(matA);
out = mat4.copy(out, matA);
out = mat4.identity(out);
out = mat4.transpose(out, matA);
out = mat4.invert(out, matA);
out = mat4.adjoint(out, matA);
outVal = mat4.determinant(matA);
out = mat4.multiply(out, matA, matB);
out = mat4.mul(out, matA, matB);
out = mat4.translate(out, matA, [4, 5, 6]);
out = mat4.scale(out, matA, [4, 5, 6]);
var rad = Math.PI * 0.5;
var axis = [1, 0, 0];
out = mat4.rotate(out, matA, rad, axis);
out = mat4.rotateX(out, matA, rad);
out = mat4.rotateY(out, matA, rad);
out = mat4.rotateZ(out, matA, rad);
out = mat4.frustum(out, -1, 1, -1, 1, -1, 1);
var fovy = Math.PI * 0.5;
out = mat4.perspective(out, fovy, 1, 0, 1);
out = mat4.ortho(out, -1, 1, -1, 1, -1, 1);
var eye = [0, 0, 1];
var center = [0, 0, -1];
var up = [0, 1, 0];
out = mat4.lookAt(out, eye, center, up);
outStr = mat4.str(matA);
outVal = mat4.frob(matA);
q = [0, 0, 0, 1];
out = mat4.fromRotationTranslation(out, q, [1, 2, 3]);
out = mat4.fromQuat(out, q);
q = [0, 0, 0, 1];
out = mat4.fromRotationTranslationScale(out, q, [1, 2, 3], [1, 2, 3]);
out = mat4.fromQuat(out, q);
// quat
var quatA = [1, 2, 3, 4];
var quatB = [5, 6, 7, 8];
out = [0, 0, 0, 0];
var vec = [1, 1, -1];
var id = [0, 0, 0, 1];
var deg90 = Math.PI / 2;
out = quat.create();
out = quat.clone(quatA);
out = quat.fromValues(1, 2, 3, 4);
out = quat.copy(out, quatA);
out = quat.set(out, 1, 2, 3, 4);
out = quat.identity(out);
out = quat.setAxisAngle(out, [1, 0, 0], Math.PI * 0.5);
out = quat.add(out, quatA, quatB);
out = quat.multiply(out, quatA, quatB);
out = quat.mul(out, quatA, quatB);
out = quat.scale(out, quatA, 2);
outVal = quat.length(quatA);
outVal = quat.len(quatA);
outVal = quat.squaredLength(quatA);
outVal = quat.sqrLen(quatA);
out = quat.normalize(out, quatA);
outVal = quat.dot(out, quatA, quatB);
out = quat.lerp(out, quatA, quatB, 0.5);
out = quat.slerp(out, quatA, quatB, 0.5);
out = quat.invert(out, quatA);
out = quat.conjugate(out, quatA);
outStr = quat.str(quatA);
out = quat.rotateX(out, id, deg90);
out = quat.rotateY(out, id, deg90);
out = quat.rotateZ(out, id, deg90);
matr = [ 1, 0, 0,
0, 0, -1,
0, 1, 0 ];
out = quat.fromMat3(out, matr);
var view = [-1, 0, 0];
up = [ 0, 1, 0];
var right= [ 0, 0,-1];
out = quat.setAxes([], view, right, up);
out = quat.rotationTo(out, [0, 1, 0], [1, 0, 0]);
out = quat.calculateW(out, quatA);
+2163
View File
File diff suppressed because it is too large Load Diff
+319 -334
View File
@@ -1,362 +1,347 @@
/// <reference path="gl-matrix.d.ts" />
// common
var result: number = glMatrix.toRadian(180);
import {vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat} from "./gl-matrix";
var out: GLM.IArray;
var outVal: number;
var outBool: boolean;
var outStr: string;
let vecArray = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
let vec2A = vec2.fromValues(1, 2);
let vec2B = vec2.fromValues(3, 4);
let vec3A = vec3.fromValues(1, 2, 3);
let vec3B = vec3.fromValues(3, 4, 5);
let vec4A = vec4.fromValues(1, 2, 3, 4);
let vec4B = vec4.fromValues(3, 4, 5, 6);
let mat2A = mat2.fromValues(1, 2, 3, 4);
let mat2B = mat2.fromValues(1, 2, 3, 4);
let mat2dA = mat2d.fromValues(1, 2, 3, 4, 5, 6);
let mat2dB = mat2d.fromValues(1, 2, 3, 4, 5, 6);
let mat3A = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9);
let mat3B = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9);
let mat4A = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
let mat4B = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
let quatA = quat.fromValues(1, 2, 3, 4);
let quatB = quat.fromValues(5, 6, 7, 8);
let outVec2 = vec2.create();
let outVec3 = vec3.create();
let outVec4 = vec4.create();
let outMat2 = mat2.create();
let outMat2d = mat2d.create();
let outMat3 = mat3.create();
let outMat4 = mat4.create();
let outQuat = quat.create();
// vec2
var vecA: GLM.IArray, vecB: GLM.IArray, matA: GLM.IArray;
var vecArray: GLM.IArray;
vecA = [1, 2];
vecB = new Float32Array([3, 4]);
out = [0, 0];
matA = [1, 2, 3, 4, 5, 6];
vecArray = [1, 2, 3, 4, 0, 0];
out = vec2.create();
out = vec2.clone(vecA);
out = vec2.fromValues(1, 2);
out = vec2.copy(out, vecA);
out = vec2.set(out, 1, 2);
out = vec2.add(out, vecA, vecB);
out = vec2.subtract(out, vecA, vecB);
out = vec2.sub(out, vecA, vecB);
out = vec2.multiply(out, vecA, vecB);
out = vec2.mul(out, vecA, vecB);
out = vec2.divide(out, vecA, vecB);
out = vec2.div(out, vecA, vecB);
out = vec2.min(out, vecA, vecB);
out = vec2.max(out, vecA, vecB);
out = vec2.scale(out, vecA, 2);
out = vec2.scaleAndAdd(out, vecA, vecB, 0.5);
outVal = vec2.distance(vecA, vecB);
outVal = vec2.dist(vecA, vecB);
outVal = vec2.squaredDistance(vecA, vecB);
outVal = vec2.sqrDist(vecA, vecB);
outVal = vec2.length(vecA);
outVal = vec2.len(vecA);
outVal = vec2.squaredLength(vecA);
outVal = vec2.sqrLen(vecA);
out = vec2.negate(out, vecA);
out = vec2.inverse(out, vecA);
out = vec2.normalize(out, vecA);
outVal = vec2.dot(vecA, vecB);
out = vec2.cross(out, vecA, vecB);
out = vec2.lerp(out, vecA, vecB, 0.5);
out = vec2.random(out);
out = vec2.random(out, 5.0);
out = vec2.transformMat2(out, vecA, matA);
out = vec2.transformMat2d(out, vecA, matA);
out = vec2.transformMat3(out, vecA, matA);
out = vec2.transformMat4(out, vecA, matA);
out = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize);
outStr = vec2.str(vecA);
outVec2 = vec2.create();
outVec2 = vec2.clone(vec2A);
outVec2 = vec2.fromValues(1, 2);
outVec2 = vec2.copy(outVec2, vec2A);
outVec2 = vec2.set(outVec2, 1, 2);
outVec2 = vec2.add(outVec2, vec2A, vec2B);
outVec2 = vec2.subtract(outVec2, vec2A, vec2B);
outVec2 = vec2.sub(outVec2, vec2A, vec2B);
outVec2 = vec2.multiply(outVec2, vec2A, vec2B);
outVec2 = vec2.mul(outVec2, vec2A, vec2B);
outVec2 = vec2.divide(outVec2, vec2A, vec2B);
outVec2 = vec2.div(outVec2, vec2A, vec2B);
outVec2 = vec2.ceil(outVec2, vec2A);
outVec2 = vec2.floor(outVec2, vec2A);
outVec2 = vec2.min(outVec2, vec2A, vec2B);
outVec2 = vec2.max(outVec2, vec2A, vec2B);
outVec2 = vec2.round(outVec2, vec2A);
outVec2 = vec2.scale(outVec2, vec2A, 2);
outVec2 = vec2.scaleAndAdd(outVec2, vec2A, vec2B, 0.5);
outVal = vec2.distance(vec2A, vec2B);
outVal = vec2.dist(vec2A, vec2B);
outVal = vec2.squaredDistance(vec2A, vec2B);
outVal = vec2.sqrDist(vec2A, vec2B);
outVal = vec2.length(vec2A);
outVal = vec2.len(vec2A);
outVal = vec2.squaredLength(vec2A);
outVal = vec2.sqrLen(vec2A);
outVec2 = vec2.negate(outVec2, vec2A);
outVec2 = vec2.inverse(outVec2, vec2A);
outVec2 = vec2.normalize(outVec2, vec2A);
outVal = vec2.dot(vec2A, vec2B);
outVec2 = vec2.cross(outVec2, vec2A, vec2B);
outVec2 = vec2.lerp(outVec2, vec2A, vec2B, 0.5);
outVec2 = vec2.random(outVec2);
outVec2 = vec2.random(outVec2, 5.0);
outVec2 = vec2.transformMat2(outVec2, vec2A, mat2A);
outVec2 = vec2.transformMat2d(outVec2, vec2A, mat2dA);
outVec2 = vec2.transformMat3(outVec2, vec2A, mat3A);
outVec2 = vec2.transformMat4(outVec2, vec2A, mat4A);
vecArray = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize);
outStr = vec2.str(vec2A);
outBool = vec2.exactEquals(vec2A, vec2B);
outBool = vec2.equals(vec2A, vec2B);
outVec2 = vec2.add(outVec2, [0, 1], [2, 3]); // test one method with number array input
// vec3
var matr: GLM.IArray;
var q: GLM.IArray;
vecA = [1, 2, 3];
vecB = new Float32Array([4, 5, 6]);
out = [0, 0, 0];
vecArray = [1, 2, 3, 4, 5, 6, 0, 0, 0];
matr = [1, 0, 0, 0, 1, 0, 0, 0, 1 ];
out = vec3.create();
out = vec3.clone(vecA);
out = vec3.fromValues(1, 2, 3);
out = vec3.copy(out, vecA);
out = vec3.set(out, 1, 2, 3);
out = vec3.add(out, vecA, vecB);
out = vec3.subtract(out, vecA, vecB);
out = vec3.sub(out, vecA, vecB);
out = vec3.multiply(out, vecA, vecB);
out = vec3.mul(out, vecA, vecB);
out = vec3.divide(out, vecA, vecB);
out = vec3.div(out, vecA, vecB);
out = vec3.min(out, vecA, vecB);
out = vec3.max(out, vecA, vecB);
out = vec3.scale(out, vecA, 2);
out = vec3.scaleAndAdd(out, vecA, vecB, 0.5);
outVal = vec3.distance(vecA, vecB);
outVal = vec3.dist(vecA, vecB);
outVal = vec3.squaredDistance(vecA, vecB);
outVal = vec3.sqrDist(vecA, vecB);
outVal = vec3.length(vecA);
outVal = vec3.len(vecA);
outVal = vec3.squaredLength(vecA);
outVal = vec3.sqrLen(vecA);
out = vec3.negate(out, vecA);
out = vec3.inverse(out, vecA);
out = vec3.normalize(out, vecA);
outVal = vec3.dot(vecA, vecB);
out = vec3.cross(out, vecA, vecB);
out = vec3.lerp(out, vecA, vecB, 0.5);
out = vec3.random(out);
out = vec3.random(out, 5.0);
out = vec3.rotateX(out, vecA, vecB, Math.PI);
out = vec3.rotateY(out, vecA, vecB, Math.PI);
out = vec3.rotateZ(out, vecA, vecB, Math.PI);
out = vec3.transformMat3(out, vecA, matr);
matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ];
out = vec3.transformMat4(out, vecA, matr);
q = [1, 2, 3, 4];
out = vec3.transformQuat(out, vecA, matr);
out = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize);
outVal = vec3.angle(vecA, vecB);
outStr = vec3.str(vecA);
outVec3 = vec3.create();
outVec3 = vec3.clone(vec3A);
outVec3 = vec3.fromValues(1, 2, 3);
outVec3 = vec3.copy(outVec3, vec3A);
outVec3 = vec3.set(outVec3, 1, 2, 3);
outVec3 = vec3.add(outVec3, vec3A, vec3B);
outVec3 = vec3.subtract(outVec3, vec3A, vec3B);
outVec3 = vec3.sub(outVec3, vec3A, vec3B);
outVec3 = vec3.multiply(outVec3, vec3A, vec3B);
outVec3 = vec3.mul(outVec3, vec3A, vec3B);
outVec3 = vec3.divide(outVec3, vec3A, vec3B);
outVec3 = vec3.div(outVec3, vec3A, vec3B);
outVec3 = vec3.ceil(outVec3, vec3A);
outVec3 = vec3.floor(outVec3, vec3A);
outVec3 = vec3.min(outVec3, vec3A, vec3B);
outVec3 = vec3.max(outVec3, vec3A, vec3B);
outVec3 = vec3.round(outVec3, vec3A);
outVec3 = vec3.scale(outVec3, vec3A, 2);
outVec3 = vec3.scaleAndAdd(outVec3, vec3A, vec3B, 0.5);
outVal = vec3.distance(vec3A, vec3B);
outVal = vec3.dist(vec3A, vec3B);
outVal = vec3.squaredDistance(vec3A, vec3B);
outVal = vec3.sqrDist(vec3A, vec3B);
outVal = vec3.length(vec3A);
outVal = vec3.len(vec3A);
outVal = vec3.squaredLength(vec3A);
outVal = vec3.sqrLen(vec3A);
outVec3 = vec3.negate(outVec3, vec3A);
outVec3 = vec3.inverse(outVec3, vec3A);
outVec3 = vec3.normalize(outVec3, vec3A);
outVal = vec3.dot(vec3A, vec3B);
outVec3 = vec3.cross(outVec3, vec3A, vec3B);
outVec3 = vec3.lerp(outVec3, vec3A, vec3B, 0.5);
outVec3 = vec3.hermite(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5);
outVec3 = vec3.bezier(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5);
outVec3 = vec3.random(outVec3);
outVec3 = vec3.random(outVec3, 5.0);
outVec3 = vec3.transformMat3(outVec3, vec3A, mat3A);
outVec3 = vec3.transformMat4(outVec3, vec3A, mat4A);
outVec3 = vec3.transformQuat(outVec3, vec3A, quatA);
outVec3 = vec3.rotateX(outVec3, vec3A, vec3B, Math.PI);
outVec3 = vec3.rotateY(outVec3, vec3A, vec3B, Math.PI);
outVec3 = vec3.rotateZ(outVec3, vec3A, vec3B, Math.PI);
vecArray = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize);
outVal = vec3.angle(vec3A, vec3B);
outStr = vec3.str(vec3A);
outBool = vec3.exactEquals(vec3A, vec3B);
outBool = vec3.equals(vec3A, vec3B);
outVec3 = vec3.add(outVec3, [0, 1, 2], [3, 4, 5]); // test one method with number array input
// vec4
var q: GLM.IArray;
vecA = [1, 2, 3, 4];
vecB = new Float32Array([5, 6, 7, 8]);
out = [0, 0, 0, 0];
q = [1, 2, 3, 4];
out = vec4.create();
out = vec4.clone(vecA);
out = vec4.fromValues(1, 2, 3, 4);
out = vec4.copy(out, vecA);
out = vec4.set(out, 1, 2, 3, 4);
out = vec4.add(out, vecA, vecB);
out = vec4.subtract(out, vecA, vecB);
out = vec4.sub(out, vecA, vecB);
out = vec4.multiply(out, vecA, vecB);
out = vec4.mul(out, vecA, vecB);
out = vec4.divide(out, vecA, vecB);
out = vec4.div(out, vecA, vecB);
out = vec4.min(out, vecA, vecB);
out = vec4.max(out, vecA, vecB);
out = vec4.scale(out, vecA, 2);
out = vec4.scaleAndAdd(out, vecA, vecB, 0.5);
outVal = vec4.distance(vecA, vecB);
outVal = vec4.dist(vecA, vecB);
outVal = vec4.squaredDistance(vecA, vecB);
outVal = vec4.sqrDist(vecA, vecB);
outVal = vec4.length(vecA);
outVal = vec4.len(vecA);
outVal = vec4.squaredLength(vecA);
outVal = vec4.sqrLen(vecA);
out = vec4.negate(out, vecA);
out = vec4.inverse(out, vecA);
out = vec4.normalize(out, vecA);
outVal = vec4.dot(vecA, vecB);
out = vec4.lerp(out, vecA, vecB, 0.5);
out = vec4.random(out);
out = vec4.random(out, 5.0);
matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]
out = vec4.transformMat4(out, vecA, matr);
out = vec4.transformQuat(out, vecA, q);
vecArray = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0];
out = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize);
outStr = vec4.str(vecA);
outVec4 = vec4.create();
outVec4 = vec4.clone(vec4A);
outVec4 = vec4.fromValues(1, 2, 3, 4);
outVec4 = vec4.copy(outVec4, vec4A);
outVec4 = vec4.set(outVec4, 1, 2, 3, 4);
outVec4 = vec4.add(outVec4, vec4A, vec4B);
outVec4 = vec4.subtract(outVec4, vec4A, vec4B);
outVec4 = vec4.sub(outVec4, vec4A, vec4B);
outVec4 = vec4.multiply(outVec4, vec4A, vec4B);
outVec4 = vec4.mul(outVec4, vec4A, vec4B);
outVec4 = vec4.divide(outVec4, vec4A, vec4B);
outVec4 = vec4.div(outVec4, vec4A, vec4B);
outVec4 = vec4.ceil(outVec4, vec4A);
outVec4 = vec4.floor(outVec4, vec4A);
outVec4 = vec4.min(outVec4, vec4A, vec4B);
outVec4 = vec4.max(outVec4, vec4A, vec4B);
outVec4 = vec4.scale(outVec4, vec4A, 2);
outVec4 = vec4.scaleAndAdd(outVec4, vec4A, vec4B, 0.5);
outVal = vec4.distance(vec4A, vec4B);
outVal = vec4.dist(vec4A, vec4B);
outVal = vec4.squaredDistance(vec4A, vec4B);
outVal = vec4.sqrDist(vec4A, vec4B);
outVal = vec4.length(vec4A);
outVal = vec4.len(vec4A);
outVal = vec4.squaredLength(vec4A);
outVal = vec4.sqrLen(vec4A);
outVec4 = vec4.negate(outVec4, vec4A);
outVec4 = vec4.inverse(outVec4, vec4A);
outVec4 = vec4.normalize(outVec4, vec4A);
outVal = vec4.dot(vec4A, vec4B);
outVec4 = vec4.lerp(outVec4, vec4A, vec4B, 0.5);
outVec4 = vec4.random(outVec4);
outVec4 = vec4.random(outVec4, 5.0);
outVec4 = vec4.transformMat4(outVec4, vec4A, mat4A);
outVec4 = vec4.transformQuat(outVec4, vec4A, quatA);
vecArray = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize);
outStr = vec4.str(vec4A);
outBool = vec4.exactEquals(vec4A, vec4B);
outBool = vec4.equals(vec4A, vec4B);
outVec4 = vec4.add(outVec4, [0, 1, 2, 3], [4, 5, 6, 7]); // test one method with number array input
// mat2
var matB: GLM.IArray, identity: GLM.IArray;
matA = [1, 2, 3, 4];
matB = new Float32Array([5, 6, 7, 8]);
out = [0, 0, 0, 0];
identity = [1, 0, 0, 1];
out = mat2.create();
out = mat2.clone(matA);
out = mat2.copy(out, matA);
out = mat2.identity(out);
out = mat2.transpose(out, matA);
out = mat2.invert(out, matA);
out = mat2.adjoint(out, matA);
outVal = mat2.determinant(matA);
out = mat2.multiply(out, matA, matB);
out = mat2.mul(out, matA, matB);
out = mat2.rotate(out, matA, Math.PI * 0.5);
vecA = [2, 3];
out = mat2.scale(out, matA, vecA);
outStr = mat2.str(matA);
outVal = mat2.frob(matA);
var L = mat2.create();
var D = mat2.create();
outMat2 = mat2.create();
outMat2 = mat2.clone(mat2A);
outMat2 = mat2.copy(outMat2, mat2A);
outMat2 = mat2.identity(outMat2);
outMat2 = mat2.fromValues(1, 2, 3, 4);
outMat2 = mat2.set(outMat2, 1, 2, 3, 4);
outMat2 = mat2.transpose(outMat2, mat2A);
outMat2 = mat2.invert(outMat2, mat2A);
outMat2 = mat2.adjoint(outMat2, mat2A);
outVal = mat2.determinant(mat2A);
outMat2 = mat2.multiply(outMat2, mat2A, mat2B);
outMat2 = mat2.mul(outMat2, mat2A, mat2B);
outMat2 = mat2.rotate(outMat2, mat2A, Math.PI * 0.5);
outMat2 = mat2.scale(outMat2, mat2A, vec2A);
outMat2 = mat2.fromRotation(outMat2, 0.5);
outMat2 = mat2.fromScaling(outMat2, vec2A);
outStr = mat2.str(mat2A);
outVal = mat2.frob(mat2A);
var L = mat2.create();
var D = mat2.create();
var U = mat2.create();
out = mat2.LDU(L, D, U, [4,3,6,3]);
outMat2 = mat2.LDU(L, D, U, mat2A);
outMat2 = mat2.add(outMat2, mat2A, mat2B);
outMat2 = mat2.subtract(outMat2, mat2A, mat2B);
outMat2 = mat2.sub(outMat2, mat2A, mat2B);
outBool = mat2.exactEquals(mat2A, mat2B);
outBool = mat2.equals(mat2A, mat2B);
outMat2 = mat2.multiplyScalar (outMat2, mat2A, 2);
outMat2 = mat2.multiplyScalarAndAdd (outMat2, mat2A, mat2B, 2);
// mat2d
matA = [1, 2, 3, 4, 5, 6];
matB = [7, 8, 9, 10, 11, 12];
out = [0, 0, 0, 0, 0, 0];
identity = [1, 0, 0, 1, 0, 0];
out = mat2d.create();
out = mat2d.clone(matA);
out = mat2d.copy(out, matA);
out = mat2d.identity(out);
out = mat2d.invert(out, matA);
outVal = mat2d.determinant(matA);
out = mat2d.multiply(out, matA, matB);
out = mat2d.mul(out, matA, matB);
out = mat2d.rotate(out, matA, Math.PI * 0.5);
vecA = [2, 3];
out = mat2d.scale(out, matA, vecA);
out = mat2d.translate(out, matA, vecA);
outStr = mat2d.str(matA);
outVal = mat2d.frob(matA);
outMat2d = mat2d.create();
outMat2d = mat2d.clone(mat2dA);
outMat2d = mat2d.copy(outMat2d, mat2dA);
outMat2d = mat2d.identity(outMat2d);
outMat2d = mat2d.fromValues(1, 2, 3, 4, 5, 6);
outMat2d = mat2d.set(outMat2d, 1, 2, 3, 4, 5, 6);
outMat2d = mat2d.invert(outMat2d, mat2dA);
outVal = mat2d.determinant(mat2dA);
outMat2d = mat2d.multiply(outMat2d, mat2dA, mat2dB);
outMat2d = mat2d.mul(outMat2d, mat2dA, mat2dB);
outMat2d = mat2d.rotate(outMat2d, mat2dA, Math.PI * 0.5);
outMat2d = mat2d.scale(outMat2d, mat2dA, vec2A);
outMat2d = mat2d.translate(outMat2d, mat2dA, vec2A);
outMat2d = mat2d.fromRotation(outMat2d, 0.5);
outMat2d = mat2d.fromScaling(outMat2d, vec2A);
outMat2d = mat2d.fromTranslation(outMat2d, vec2A);
outStr = mat2d.str(mat2dA);
outVal = mat2d.frob(mat2dA);
outMat2d = mat2d.add(outMat2d, mat2dA, mat2dB);
outMat2d = mat2d.subtract(outMat2d, mat2dA, mat2dB);
outMat2d = mat2d.sub(outMat2d, mat2dA, mat2dB);
outMat2d = mat2d.multiplyScalar (outMat2d, mat2dA, 2);
outMat2d = mat2d.multiplyScalarAndAdd (outMat2d, mat2dA, mat2dB, 2);
outBool = mat2d.exactEquals(mat2dA, mat2dB);
outBool = mat2d.equals(mat2dA, mat2dB);
// mat3
matA = [1, 0, 0, 0, 1, 0, 1, 2, 1];
matB = [1, 0, 0, 0, 1, 0, 3, 4, 1];
out = [0, 0, 0, 0, 0, 0, 0, 0, 0];
identity = [1, 0, 0, 0, 1, 0, 0, 0, 1];
out = mat3.create();
out = mat3.clone(matA);
out = mat3.copy(out, matA);
out = mat3.identity(out);
out = mat3.transpose(out, matA);
out = mat3.invert(out, matA);
out = mat3.adjoint(out, matA);
outVal = mat3.determinant(matA);
out = mat3.multiply(out, matA, matB);
out = mat3.mul(out, matA, matB);
outStr = mat3.str(matA);
outVal = mat3.frob(matA);
matA = [1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1];
out = mat3.normalFromMat4(out, matA);
q = [ 0, -0.7071067811865475, 0, 0.7071067811865475 ];
out = mat3.fromQuat(out, q);
out = mat3.normalFromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]);
out = mat3.fromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]);
out = mat3.scale(out, matA, [2,2]);
out = mat3.fromMat2d(out, [1, 2, 3, 4, 5, 6]);
out = mat3.translate(out, matA, [1, 2, 3]);
out = mat3.rotate(out, matA, Math.PI/2);
// mat4
matA = [1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
1, 2, 3, 1];
matB = [1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
4, 5, 6, 1];
out = [0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0];
identity = [1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1];
out = mat4.create();
out = mat4.clone(matA);
out = mat4.copy(out, matA);
out = mat4.identity(out);
out = mat4.transpose(out, matA);
out = mat4.invert(out, matA);
out = mat4.adjoint(out, matA);
outVal = mat4.determinant(matA);
out = mat4.multiply(out, matA, matB);
out = mat4.mul(out, matA, matB);
out = mat4.translate(out, matA, [4, 5, 6]);
out = mat4.scale(out, matA, [4, 5, 6]);
var rad = Math.PI * 0.5;
var axis = [1, 0, 0];
out = mat4.rotate(out, matA, rad, axis);
out = mat4.rotateX(out, matA, rad);
out = mat4.rotateY(out, matA, rad);
out = mat4.rotateZ(out, matA, rad);
out = mat4.frustum(out, -1, 1, -1, 1, -1, 1);
var fovy = Math.PI * 0.5;
out = mat4.perspective(out, fovy, 1, 0, 1);
out = mat4.ortho(out, -1, 1, -1, 1, -1, 1);
var eye = [0, 0, 1];
var center = [0, 0, -1];
var up = [0, 1, 0];
out = mat4.lookAt(out, eye, center, up);
outStr = mat4.str(matA);
outVal = mat4.frob(matA);
q = [0, 0, 0, 1];
out = mat4.fromRotationTranslation(out, q, [1, 2, 3]);
out = mat4.fromQuat(out, q);
q = [0, 0, 0, 1];
out = mat4.fromRotationTranslationScale(out, q, [1, 2, 3], [1, 2, 3]);
out = mat4.fromQuat(out, q);
outMat3 = mat3.create();
outMat3 = mat3.fromMat4(outMat3, mat4A);
outMat3 = mat3.clone(mat3A);
outMat3 = mat3.copy(outMat3, mat3A);
outMat3 = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9);
outMat3 = mat3.set(outMat3, 1, 2, 3, 4, 5, 6, 7, 8, 9);
outMat3 = mat3.identity(outMat3);
outMat3 = mat3.transpose(outMat3, mat3A);
outMat3 = mat3.invert(outMat3, mat3A);
outMat3 = mat3.adjoint(outMat3, mat3A);
outVal = mat3.determinant(mat3A);
outMat3 = mat3.multiply(outMat3, mat3A, mat3B);
outMat3 = mat3.mul(outMat3, mat3A, mat3B);
outMat3 = mat3.translate(outMat3, mat3A, vec3A);
outMat3 = mat3.rotate(outMat3, mat3A, Math.PI/2);
outMat3 = mat3.scale(outMat3, mat3A, vec2A);
outMat3 = mat3.fromTranslation(outMat3, vec2A);
outMat3 = mat3.fromRotation(outMat3, Math.PI);
outMat3 = mat3.fromScaling(outMat3, vec2A);
outMat3 = mat3.fromMat2d(outMat3, mat2dA);
outMat3 = mat3.fromQuat(outMat3, quatA);
outMat3 = mat3.normalFromMat4(outMat3, mat4A);
outStr = mat3.str(mat3A);
outVal = mat3.frob(mat3A);
outMat3 = mat3.add(outMat3, mat3A, mat3B);
outMat3 = mat3.subtract(outMat3, mat3A, mat3B);
outMat3 = mat3.sub(outMat3, mat3A, mat3B);
outMat3 = mat3.multiplyScalar (outMat3, mat3A, 2);
outMat3 = mat3.multiplyScalarAndAdd (outMat3, mat3A, mat3B, 2);
outBool = mat3.exactEquals(mat3A, mat3B);
outBool = mat3.equals(mat3A, mat3B);
//mat4
outMat4 = mat4.create();
outMat4 = mat4.clone(mat4A);
outMat4 = mat4.copy(outMat4, mat4A);
outMat4 = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
outMat4 = mat4.set(outMat4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
outMat4 = mat4.identity(outMat4);
outMat4 = mat4.transpose(outMat4, mat4A);
outMat4 = mat4.invert(outMat4, mat4A);
outMat4 = mat4.adjoint(outMat4, mat4A);
outVal = mat4.determinant(mat4A);
outMat4 = mat4.multiply(outMat4, mat4A, mat4B);
outMat4 = mat4.mul(outMat4, mat4A, mat4B);
outMat4 = mat4.translate(outMat4, mat4A, vec3A);
outMat4 = mat4.scale(outMat4, mat4A, vec3A);
outMat4 = mat4.rotate(outMat4, mat4A, Math.PI, vec3A);
outMat4 = mat4.rotateX(outMat4, mat4A, Math.PI);
outMat4 = mat4.rotateY(outMat4, mat4A, Math.PI);
outMat4 = mat4.rotateZ(outMat4, mat4A, Math.PI);
outMat4 = mat4.fromTranslation(outMat4, vec3A);
outMat4 = mat4.fromRotation(outMat4, Math.PI, vec3A);
outMat4 = mat4.fromScaling(outMat4, vec3A);
outMat4 = mat4.fromXRotation(outMat4, Math.PI);
outMat4 = mat4.fromYRotation(outMat4, Math.PI);
outMat4 = mat4.fromZRotation(outMat4, Math.PI);
outMat4 = mat4.fromRotationTranslation(outMat4, quatA, vec3A);
outVec3 = mat4.getTranslation(outVec3, mat4A)
outQuat = mat4.getRotation(outQuat, mat4A)
outMat4 = mat4.fromRotationTranslationScale(outMat4, quatA, vec3A, vec3B);
outMat4 = mat4.fromRotationTranslationScaleOrigin(outMat4, quatA, vec3A, vec3B, vec3A);
outMat4 = mat4.fromQuat(outMat4, quatB);
outMat4 = mat4.frustum(outMat4, -1, 1, -1, 1, -1, 1);
outMat4 = mat4.perspective(outMat4, Math.PI, 1, 0, 1);
outMat4 = mat4.perspectiveFromFieldOfView(outMat4, {upDegrees:Math.PI, downDegrees:-Math.PI, leftDegrees:-Math.PI, rightDegrees:Math.PI}, 1, 0);
outMat4 = mat4.ortho(outMat4, -1, 1, -1, 1, -1, 1);
outMat4 = mat4.lookAt(outMat4, vec3A, vec3B, vec3A);
outStr = mat4.str(mat4A);
outVal = mat4.frob(mat4A);
outMat4 = mat4.add(outMat4, mat4A, mat4B);
outMat4 = mat4.subtract(outMat4, mat4A, mat4B);
outMat4 = mat4.sub(outMat4, mat4A, mat4B);
outMat4 = mat4.multiplyScalar (outMat4, mat4A, 2);
outMat4 = mat4.multiplyScalarAndAdd (outMat4, mat4A, mat4B, 2);
outBool = mat4.exactEquals(mat4A, mat4B);
outBool = mat4.equals(mat4A, mat4B);
// quat
var quatA = [1, 2, 3, 4];
var quatB = [5, 6, 7, 8];
out = [0, 0, 0, 0];
var vec = [1, 1, -1];
var id = [0, 0, 0, 1];
var deg90 = Math.PI / 2;
out = quat.create();
out = quat.clone(quatA);
out = quat.fromValues(1, 2, 3, 4);
out = quat.copy(out, quatA);
out = quat.set(out, 1, 2, 3, 4);
out = quat.identity(out);
out = quat.setAxisAngle(out, [1, 0, 0], Math.PI * 0.5);
out = quat.add(out, quatA, quatB);
out = quat.multiply(out, quatA, quatB);
out = quat.mul(out, quatA, quatB);
out = quat.scale(out, quatA, 2);
outQuat = quat.create();
outQuat = quat.clone(quatA);
outQuat = quat.fromValues(1, 2, 3, 4);
outQuat = quat.copy(outQuat, quatA);
outQuat = quat.set(outQuat, 1, 2, 3, 4);
outQuat = quat.identity(outQuat);
outQuat = quat.rotationTo(outQuat, vec3A, vec3B);
outQuat = quat.setAxes(outQuat, vec3A, vec3B, vec3A);
outQuat = quat.setAxisAngle(outQuat, vec3A, Math.PI * 0.5);
outVal = quat.getAxisAngle (outVec3, quatA);
outQuat = quat.add(outQuat, quatA, quatB);
outQuat = quat.multiply(outQuat, quatA, quatB);
outQuat = quat.mul(outQuat, quatA, quatB);
outQuat = quat.scale(outQuat, quatA, 2);
outVal = quat.length(quatA);
outVal = quat.len(quatA);
outVal = quat.squaredLength(quatA);
outVal = quat.sqrLen(quatA);
out = quat.normalize(out, quatA);
outVal = quat.dot(out, quatA, quatB);
out = quat.lerp(out, quatA, quatB, 0.5);
out = quat.slerp(out, quatA, quatB, 0.5);
out = quat.invert(out, quatA);
out = quat.conjugate(out, quatA);
outQuat = quat.normalize(outQuat, quatA);
outVal = quat.dot(quatA, quatB);
outQuat = quat.lerp(outQuat, quatA, quatB, 0.5);
outQuat = quat.slerp(outQuat, quatA, quatB, 0.5);
outQuat = quat.invert(outQuat, quatA);
outQuat = quat.conjugate(outQuat, quatA);
outStr = quat.str(quatA);
out = quat.rotateX(out, id, deg90);
out = quat.rotateY(out, id, deg90);
out = quat.rotateZ(out, id, deg90);
matr = [ 1, 0, 0,
0, 0, -1,
0, 1, 0 ];
out = quat.fromMat3(out, matr);
var view = [-1, 0, 0];
up = [ 0, 1, 0];
var right= [ 0, 0,-1];
out = quat.setAxes([], view, right, up);
out = quat.rotationTo(out, [0, 1, 0], [1, 0, 0]);
out = quat.calculateW(out, quatA);
outQuat = quat.rotateX(outQuat, quatA, deg90);
outQuat = quat.rotateY(outQuat, quatA, deg90);
outQuat = quat.rotateZ(outQuat, quatA, deg90);
outQuat = quat.fromMat3(outQuat, mat3A);
outQuat = quat.calculateW(outQuat, quatA);
outBool = quat.exactEquals(quatA, quatB);
outBool = quat.equals(quatA, quatB);
-346
View File
@@ -1,346 +0,0 @@
/// <reference path="gl-matrix-typed.d.ts" />
// common
import {vec2, mat2, mat3, mat4, vec3, vec4, glMatrix, mat2d, quat} from "./gl-matrix-typed";
var result: number = glMatrix.toRadian(180);
var outVal: number;
var outBool: boolean;
var outStr: string;
let vecArray = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
let vec2A = vec2.fromValues(1, 2);
let vec2B = vec2.fromValues(3, 4);
let vec3A = vec3.fromValues(1, 2, 3);
let vec3B = vec3.fromValues(3, 4, 5);
let vec4A = vec4.fromValues(1, 2, 3, 4);
let vec4B = vec4.fromValues(3, 4, 5, 6);
let mat2A = mat2.fromValues(1, 2, 3, 4);
let mat2B = mat2.fromValues(1, 2, 3, 4);
let mat2dA = mat2d.fromValues(1, 2, 3, 4, 5, 6);
let mat2dB = mat2d.fromValues(1, 2, 3, 4, 5, 6);
let mat3A = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9);
let mat3B = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9);
let mat4A = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
let mat4B = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
let quatA = quat.fromValues(1, 2, 3, 4);
let quatB = quat.fromValues(5, 6, 7, 8);
let outVec2 = vec2.create();
let outVec3 = vec3.create();
let outVec4 = vec4.create();
let outMat2 = mat2.create();
let outMat2d = mat2d.create();
let outMat3 = mat3.create();
let outMat4 = mat4.create();
let outQuat = quat.create();
// vec2
outVec2 = vec2.create();
outVec2 = vec2.clone(vec2A);
outVec2 = vec2.fromValues(1, 2);
outVec2 = vec2.copy(outVec2, vec2A);
outVec2 = vec2.set(outVec2, 1, 2);
outVec2 = vec2.add(outVec2, vec2A, vec2B);
outVec2 = vec2.subtract(outVec2, vec2A, vec2B);
outVec2 = vec2.sub(outVec2, vec2A, vec2B);
outVec2 = vec2.multiply(outVec2, vec2A, vec2B);
outVec2 = vec2.mul(outVec2, vec2A, vec2B);
outVec2 = vec2.divide(outVec2, vec2A, vec2B);
outVec2 = vec2.div(outVec2, vec2A, vec2B);
outVec2 = vec2.ceil(outVec2, vec2A);
outVec2 = vec2.floor(outVec2, vec2A);
outVec2 = vec2.min(outVec2, vec2A, vec2B);
outVec2 = vec2.max(outVec2, vec2A, vec2B);
outVec2 = vec2.round(outVec2, vec2A);
outVec2 = vec2.scale(outVec2, vec2A, 2);
outVec2 = vec2.scaleAndAdd(outVec2, vec2A, vec2B, 0.5);
outVal = vec2.distance(vec2A, vec2B);
outVal = vec2.dist(vec2A, vec2B);
outVal = vec2.squaredDistance(vec2A, vec2B);
outVal = vec2.sqrDist(vec2A, vec2B);
outVal = vec2.length(vec2A);
outVal = vec2.len(vec2A);
outVal = vec2.squaredLength(vec2A);
outVal = vec2.sqrLen(vec2A);
outVec2 = vec2.negate(outVec2, vec2A);
outVec2 = vec2.inverse(outVec2, vec2A);
outVec2 = vec2.normalize(outVec2, vec2A);
outVal = vec2.dot(vec2A, vec2B);
outVec2 = vec2.cross(outVec2, vec2A, vec2B);
outVec2 = vec2.lerp(outVec2, vec2A, vec2B, 0.5);
outVec2 = vec2.random(outVec2);
outVec2 = vec2.random(outVec2, 5.0);
outVec2 = vec2.transformMat2(outVec2, vec2A, mat2A);
outVec2 = vec2.transformMat2d(outVec2, vec2A, mat2dA);
outVec2 = vec2.transformMat3(outVec2, vec2A, mat3A);
outVec2 = vec2.transformMat4(outVec2, vec2A, mat4A);
vecArray = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize);
outStr = vec2.str(vec2A);
outBool = vec2.exactEquals(vec2A, vec2B);
outBool = vec2.equals(vec2A, vec2B);
// vec3
outVec3 = vec3.create();
outVec3 = vec3.clone(vec3A);
outVec3 = vec3.fromValues(1, 2, 3);
outVec3 = vec3.copy(outVec3, vec3A);
outVec3 = vec3.set(outVec3, 1, 2, 3);
outVec3 = vec3.add(outVec3, vec3A, vec3B);
outVec3 = vec3.subtract(outVec3, vec3A, vec3B);
outVec3 = vec3.sub(outVec3, vec3A, vec3B);
outVec3 = vec3.multiply(outVec3, vec3A, vec3B);
outVec3 = vec3.mul(outVec3, vec3A, vec3B);
outVec3 = vec3.divide(outVec3, vec3A, vec3B);
outVec3 = vec3.div(outVec3, vec3A, vec3B);
outVec3 = vec3.ceil(outVec3, vec3A);
outVec3 = vec3.floor(outVec3, vec3A);
outVec3 = vec3.min(outVec3, vec3A, vec3B);
outVec3 = vec3.max(outVec3, vec3A, vec3B);
outVec3 = vec3.round(outVec3, vec3A);
outVec3 = vec3.scale(outVec3, vec3A, 2);
outVec3 = vec3.scaleAndAdd(outVec3, vec3A, vec3B, 0.5);
outVal = vec3.distance(vec3A, vec3B);
outVal = vec3.dist(vec3A, vec3B);
outVal = vec3.squaredDistance(vec3A, vec3B);
outVal = vec3.sqrDist(vec3A, vec3B);
outVal = vec3.length(vec3A);
outVal = vec3.len(vec3A);
outVal = vec3.squaredLength(vec3A);
outVal = vec3.sqrLen(vec3A);
outVec3 = vec3.negate(outVec3, vec3A);
outVec3 = vec3.inverse(outVec3, vec3A);
outVec3 = vec3.normalize(outVec3, vec3A);
outVal = vec3.dot(vec3A, vec3B);
outVec3 = vec3.cross(outVec3, vec3A, vec3B);
outVec3 = vec3.lerp(outVec3, vec3A, vec3B, 0.5);
outVec3 = vec3.hermite(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5);
outVec3 = vec3.bezier(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5);
outVec3 = vec3.random(outVec3);
outVec3 = vec3.random(outVec3, 5.0);
outVec3 = vec3.transformMat3(outVec3, vec3A, mat3A);
outVec3 = vec3.transformMat4(outVec3, vec3A, mat4A);
outVec3 = vec3.transformQuat(outVec3, vec3A, quatA);
outVec3 = vec3.rotateX(outVec3, vec3A, vec3B, Math.PI);
outVec3 = vec3.rotateY(outVec3, vec3A, vec3B, Math.PI);
outVec3 = vec3.rotateZ(outVec3, vec3A, vec3B, Math.PI);
vecArray = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize);
outVal = vec3.angle(vec3A, vec3B);
outStr = vec3.str(vec3A);
outBool = vec3.exactEquals(vec3A, vec3B);
outBool = vec3.equals(vec3A, vec3B);
// vec4
outVec4 = vec4.create();
outVec4 = vec4.clone(vec4A);
outVec4 = vec4.fromValues(1, 2, 3, 4);
outVec4 = vec4.copy(outVec4, vec4A);
outVec4 = vec4.set(outVec4, 1, 2, 3, 4);
outVec4 = vec4.add(outVec4, vec4A, vec4B);
outVec4 = vec4.subtract(outVec4, vec4A, vec4B);
outVec4 = vec4.sub(outVec4, vec4A, vec4B);
outVec4 = vec4.multiply(outVec4, vec4A, vec4B);
outVec4 = vec4.mul(outVec4, vec4A, vec4B);
outVec4 = vec4.divide(outVec4, vec4A, vec4B);
outVec4 = vec4.div(outVec4, vec4A, vec4B);
outVec4 = vec4.ceil(outVec4, vec4A);
outVec4 = vec4.floor(outVec4, vec4A);
outVec4 = vec4.min(outVec4, vec4A, vec4B);
outVec4 = vec4.max(outVec4, vec4A, vec4B);
outVec4 = vec4.scale(outVec4, vec4A, 2);
outVec4 = vec4.scaleAndAdd(outVec4, vec4A, vec4B, 0.5);
outVal = vec4.distance(vec4A, vec4B);
outVal = vec4.dist(vec4A, vec4B);
outVal = vec4.squaredDistance(vec4A, vec4B);
outVal = vec4.sqrDist(vec4A, vec4B);
outVal = vec4.length(vec4A);
outVal = vec4.len(vec4A);
outVal = vec4.squaredLength(vec4A);
outVal = vec4.sqrLen(vec4A);
outVec4 = vec4.negate(outVec4, vec4A);
outVec4 = vec4.inverse(outVec4, vec4A);
outVec4 = vec4.normalize(outVec4, vec4A);
outVal = vec4.dot(vec4A, vec4B);
outVec4 = vec4.lerp(outVec4, vec4A, vec4B, 0.5);
outVec4 = vec4.random(outVec4);
outVec4 = vec4.random(outVec4, 5.0);
outVec4 = vec4.transformMat4(outVec4, vec4A, mat4A);
outVec4 = vec4.transformQuat(outVec4, vec4A, quatA);
vecArray = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize);
outStr = vec4.str(vec4A);
outBool = vec4.exactEquals(vec4A, vec4B);
outBool = vec4.equals(vec4A, vec4B);
// mat2
outMat2 = mat2.create();
outMat2 = mat2.clone(mat2A);
outMat2 = mat2.copy(outMat2, mat2A);
outMat2 = mat2.identity(outMat2);
outMat2 = mat2.fromValues(1, 2, 3, 4);
outMat2 = mat2.set(outMat2, 1, 2, 3, 4);
outMat2 = mat2.transpose(outMat2, mat2A);
outMat2 = mat2.invert(outMat2, mat2A);
outMat2 = mat2.adjoint(outMat2, mat2A);
outVal = mat2.determinant(mat2A);
outMat2 = mat2.multiply(outMat2, mat2A, mat2B);
outMat2 = mat2.mul(outMat2, mat2A, mat2B);
outMat2 = mat2.rotate(outMat2, mat2A, Math.PI * 0.5);
outMat2 = mat2.scale(outMat2, mat2A, vec2A);
outMat2 = mat2.fromRotation(outMat2, 0.5);
outMat2 = mat2.fromScaling(outMat2, vec2A);
outStr = mat2.str(mat2A);
outVal = mat2.frob(mat2A);
var L = mat2.create();
var D = mat2.create();
var U = mat2.create();
outMat2 = mat2.LDU(L, D, U, mat2A);
outMat2 = mat2.add(outMat2, mat2A, mat2B);
outMat2 = mat2.subtract(outMat2, mat2A, mat2B);
outMat2 = mat2.sub(outMat2, mat2A, mat2B);
outBool = mat2.exactEquals(mat2A, mat2B);
outBool = mat2.equals(mat2A, mat2B);
outMat2 = mat2.multiplyScalar (outMat2, mat2A, 2);
outMat2 = mat2.multiplyScalarAndAdd (outMat2, mat2A, mat2B, 2);
// mat2d
outMat2d = mat2d.create();
outMat2d = mat2d.clone(mat2dA);
outMat2d = mat2d.copy(outMat2d, mat2dA);
outMat2d = mat2d.identity(outMat2d);
outMat2d = mat2d.fromValues(1, 2, 3, 4, 5, 6);
outMat2d = mat2d.set(outMat2d, 1, 2, 3, 4, 5, 6);
outMat2d = mat2d.invert(outMat2d, mat2dA);
outVal = mat2d.determinant(mat2dA);
outMat2d = mat2d.multiply(outMat2d, mat2dA, mat2dB);
outMat2d = mat2d.mul(outMat2d, mat2dA, mat2dB);
outMat2d = mat2d.rotate(outMat2d, mat2dA, Math.PI * 0.5);
outMat2d = mat2d.scale(outMat2d, mat2dA, vec2A);
outMat2d = mat2d.translate(outMat2d, mat2dA, vec2A);
outMat2d = mat2d.fromRotation(outMat2d, 0.5);
outMat2d = mat2d.fromScaling(outMat2d, vec2A);
outMat2d = mat2d.fromTranslation(outMat2d, vec2A);
outStr = mat2d.str(mat2dA);
outVal = mat2d.frob(mat2dA);
outMat2d = mat2d.add(outMat2d, mat2dA, mat2dB);
outMat2d = mat2d.subtract(outMat2d, mat2dA, mat2dB);
outMat2d = mat2d.sub(outMat2d, mat2dA, mat2dB);
outMat2d = mat2d.multiplyScalar (outMat2d, mat2dA, 2);
outMat2d = mat2d.multiplyScalarAndAdd (outMat2d, mat2dA, mat2dB, 2);
outBool = mat2d.exactEquals(mat2dA, mat2dB);
outBool = mat2d.equals(mat2dA, mat2dB);
// mat3
outMat3 = mat3.create();
outMat3 = mat3.fromMat4(outMat3, mat4A);
outMat3 = mat3.clone(mat3A);
outMat3 = mat3.copy(outMat3, mat3A);
outMat3 = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9);
outMat3 = mat3.set(outMat3, 1, 2, 3, 4, 5, 6, 7, 8, 9);
outMat3 = mat3.identity(outMat3);
outMat3 = mat3.transpose(outMat3, mat3A);
outMat3 = mat3.invert(outMat3, mat3A);
outMat3 = mat3.adjoint(outMat3, mat3A);
outVal = mat3.determinant(mat3A);
outMat3 = mat3.multiply(outMat3, mat3A, mat3B);
outMat3 = mat3.mul(outMat3, mat3A, mat3B);
outMat3 = mat3.translate(outMat3, mat3A, vec3A);
outMat3 = mat3.rotate(outMat3, mat3A, Math.PI/2);
outMat3 = mat3.scale(outMat3, mat3A, vec2A);
outMat3 = mat3.fromTranslation(outMat3, vec2A);
outMat3 = mat3.fromRotation(outMat3, Math.PI);
outMat3 = mat3.fromScaling(outMat3, vec2A);
outMat3 = mat3.fromMat2d(outMat3, mat2dA);
outMat3 = mat3.fromQuat(outMat3, quatA);
outMat3 = mat3.normalFromMat4(outMat3, mat4A);
outStr = mat3.str(mat3A);
outVal = mat3.frob(mat3A);
outMat3 = mat3.add(outMat3, mat3A, mat3B);
outMat3 = mat3.subtract(outMat3, mat3A, mat3B);
outMat3 = mat3.sub(outMat3, mat3A, mat3B);
outMat3 = mat3.multiplyScalar (outMat3, mat3A, 2);
outMat3 = mat3.multiplyScalarAndAdd (outMat3, mat3A, mat3B, 2);
outBool = mat3.exactEquals(mat3A, mat3B);
outBool = mat3.equals(mat3A, mat3B);
//mat4
outMat4 = mat4.create();
outMat4 = mat4.clone(mat4A);
outMat4 = mat4.copy(outMat4, mat4A);
outMat4 = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
outMat4 = mat4.set(outMat4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
outMat4 = mat4.identity(outMat4);
outMat4 = mat4.transpose(outMat4, mat4A);
outMat4 = mat4.invert(outMat4, mat4A);
outMat4 = mat4.adjoint(outMat4, mat4A);
outVal = mat4.determinant(mat4A);
outMat4 = mat4.multiply(outMat4, mat4A, mat4B);
outMat4 = mat4.mul(outMat4, mat4A, mat4B);
outMat4 = mat4.translate(outMat4, mat4A, vec3A);
outMat4 = mat4.scale(outMat4, mat4A, vec3A);
outMat4 = mat4.rotate(outMat4, mat4A, Math.PI, vec3A);
outMat4 = mat4.rotateX(outMat4, mat4A, Math.PI);
outMat4 = mat4.rotateY(outMat4, mat4A, Math.PI);
outMat4 = mat4.rotateZ(outMat4, mat4A, Math.PI);
outMat4 = mat4.fromTranslation(outMat4, vec3A);
outMat4 = mat4.fromRotation(outMat4, Math.PI, vec3A);
outMat4 = mat4.fromScaling(outMat4, vec3A);
outMat4 = mat4.fromXRotation(outMat4, Math.PI);
outMat4 = mat4.fromYRotation(outMat4, Math.PI);
outMat4 = mat4.fromZRotation(outMat4, Math.PI);
outMat4 = mat4.fromRotationTranslation(outMat4, quatA, vec3A);
outVec3 = mat4.getTranslation(outVec3, mat4A)
outQuat = mat4.getRotation(outQuat, mat4A)
outMat4 = mat4.fromRotationTranslationScale(outMat4, quatA, vec3A, vec3B);
outMat4 = mat4.fromRotationTranslationScaleOrigin(outMat4, quatA, vec3A, vec3B, vec3A);
outMat4 = mat4.fromQuat(outMat4, quatB);
outMat4 = mat4.frustum(outMat4, -1, 1, -1, 1, -1, 1);
outMat4 = mat4.perspective(outMat4, Math.PI, 1, 0, 1);
outMat4 = mat4.perspectiveFromFieldOfView(outMat4, {upDegrees:Math.PI, downDegrees:-Math.PI, leftDegrees:-Math.PI, rightDegrees:Math.PI}, 1, 0);
outMat4 = mat4.ortho(outMat4, -1, 1, -1, 1, -1, 1);
outMat4 = mat4.lookAt(outMat4, vec3A, vec3B, vec3A);
outStr = mat4.str(mat4A);
outVal = mat4.frob(mat4A);
outMat4 = mat4.add(outMat4, mat4A, mat4B);
outMat4 = mat4.subtract(outMat4, mat4A, mat4B);
outMat4 = mat4.sub(outMat4, mat4A, mat4B);
outMat4 = mat4.multiplyScalar (outMat4, mat4A, 2);
outMat4 = mat4.multiplyScalarAndAdd (outMat4, mat4A, mat4B, 2);
outBool = mat4.exactEquals(mat4A, mat4B);
outBool = mat4.equals(mat4A, mat4B);
// quat
var deg90 = Math.PI / 2;
outQuat = quat.create();
outQuat = quat.clone(quatA);
outQuat = quat.fromValues(1, 2, 3, 4);
outQuat = quat.copy(outQuat, quatA);
outQuat = quat.set(outQuat, 1, 2, 3, 4);
outQuat = quat.identity(outQuat);
outQuat = quat.rotationTo(outQuat, vec3A, vec3B);
outQuat = quat.setAxes(outQuat, vec3A, vec3B, vec3A);
outQuat = quat.setAxisAngle(outQuat, vec3A, Math.PI * 0.5);
outVal = quat.getAxisAngle (outVec3, quatA);
outQuat = quat.add(outQuat, quatA, quatB);
outQuat = quat.multiply(outQuat, quatA, quatB);
outQuat = quat.mul(outQuat, quatA, quatB);
outQuat = quat.scale(outQuat, quatA, 2);
outVal = quat.length(quatA);
outVal = quat.len(quatA);
outVal = quat.squaredLength(quatA);
outVal = quat.sqrLen(quatA);
outQuat = quat.normalize(outQuat, quatA);
outVal = quat.dot(quatA, quatB);
outQuat = quat.lerp(outQuat, quatA, quatB, 0.5);
outQuat = quat.slerp(outQuat, quatA, quatB, 0.5);
outQuat = quat.invert(outQuat, quatA);
outQuat = quat.conjugate(outQuat, quatA);
outStr = quat.str(quatA);
outQuat = quat.rotateX(outQuat, quatA, deg90);
outQuat = quat.rotateY(outQuat, quatA, deg90);
outQuat = quat.rotateZ(outQuat, quatA, deg90);
outQuat = quat.fromMat3(outQuat, mat3A);
outQuat = quat.calculateW(outQuat, quatA);
outBool = quat.exactEquals(quatA, quatB);
outBool = quat.equals(quatA, quatB);
-3054
View File
File diff suppressed because it is too large Load Diff
+1289 -408
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -756,7 +756,7 @@ declare namespace google.maps {
zIndex?: number;
}
export interface PolyMouseEvent {
export interface PolyMouseEvent extends MouseEvent {
edge?: number;
path?: number;
vertex?: number;
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Yang Guan <https://github.com/lookuptable>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
/*
* Configuration object of a heatmap
+312 -3
View File
@@ -1073,6 +1073,125 @@ declare namespace H {
*/
resizeToCenter(center: H.geo.IPoint, opt_out?: H.geo.Rect): H.geo.Rect;
}
/**
* A strip is a flat list of latitude, longitude, altitude tuples in a fixed order.
*/
export class Strip {
/**
* Constructor
* @param opt_latLngAlts {Array<number>=} - An optional array of latitude, longitude and altitude triples to initialize the strip with.
* @param opt_ctx {H.geo.AltitudeContext=} - An optional altitude context for all altitudes contained in this strip.
*/
constructor(opt_latLngAlts?: Array<number>, opt_ctx?: H.geo.AltitudeContext);
/**
* This method pushes a lat, lng, alt to the end of this strip.
* @param lat {H.geo.Latitude}
* @param lng {H.geo.Longitude}
* @param alt {H.geo.Altitude}
*/
pushLatLngAlt(lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude): void;
/**
* This method splices the strip at the provided index, removing the specified number of items at that index and inserting the lat, lng, alt array.
* @param index {number} - The index at which to splice
* @param opt_nRemove {number=} - The number of lat, lng, alt values to remove
* @param opt_latLngAlts {Array<number>=} - The lat, lng, alt values to add
* @returns {Array<number>} - an array of removed elements
*/
spliceLatLngAlts(index: number, opt_nRemove?: number, opt_latLngAlts?: Array<number>): Array<number>;
/**
* This method inserts one set of lat, lng, alt values into the strip at the specified index.
* @param index {number} - the index at which to add the element
* @param lat {H.geo.Latitude} - the latitude to insert
* @param lng {H.geo.Longitude} - the longitude to insert
* @param alt {H.geo.Altitude} - the altitude to insert
*/
insertLatLngAlt(index: number, lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude): void;
/**
* This method removes one set of lat, lng, alt values from the strip at the specified index.
* @param index {number}
*/
removeLatLngAlt(index: number): void;
/**
* This method pushes the lat, lng, alt values of a H.geo.Point to the end of this strip.
* @param geoPoint {H.geo.IPoint}
*/
pushPoint(geoPoint: H.geo.IPoint): void;
/**
* This method inserts the lat, lng, alt values of a H.geo.Point into the list at the specified index.
* @param pointIndex {number}
* @param geoPoint {H.geo.IPoint}
*/
insertPoint(pointIndex: number, geoPoint: H.geo.IPoint): void;
/**
* This method removes one set of lat, lng, alt values from this strip at the virtual point index specified.
* @param pointIndex {number} - the virtual point index
*/
removePoint(pointIndex: number): void;
/**
* This method extracts a H.geo.Point from this strip at the virtual point index. If the extracted point has an alt value, the strip's altitude context will be supplied to the point.
* @param pointIndex {number} - the virtual point index in the strip
* @param opt_out {H.geo.Point=} - an optional point object to store the lat, lng, alt values
* @returns {H.geo.Point} - returns either the 'opt_out' point object or a new point object.
*/
extractPoint(pointIndex: number, opt_out?: H.geo.Point): H.geo.Point;
/**
* This method is a utility method that iterates over the lat, lng, alt array and calls the provided function for each 3 elements passing lat, lng and alt and the virtual point index as arguments.
* @param eachFn {function(H.geo.Latitude, H.geo.Longitude, H.geo.Altitude, number)} - the function to be called for each 3 elements
* @param opt_start {number=} - an optional start index to iterate from
* @param opt_end {number=} - an optional end index to iterate to
*/
eachLatLngAlt(eachFn: (lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude, n: number) => void, opt_start?: number, opt_end?: number): void;
/**
* This method returns the number of times that legs in this strip cross the date border.
* @param opt_closed {boolean=} - indicates whether the strip is closed (i.e. whether the strip's last and first coordinates form the closing leg of a polygon)
* @returns {number} - the amount of times this strip crosses the date border.
*/
getDBCs(opt_closed?: boolean): number;
/**
* This method return the number of points stored in this strip.
* @returns {number} - the number of points in this strip
*/
getPointCount(): number;
/**
* This method returns the internal array keeping the lat, lng, alt values. Modifying this array directly can destroy the integrity of this strip. Use it only for read access.
* @returns {Array<number>} - returns the raw lat, lng, alt values of this strip
*/
getLatLngAltArray(): Array<number>;
/**
* This method returns the bounding box of this strip.
* @returns {?H.geo.Rect} - this strip's bounding rectangle
*/
getBounds(): H.geo.Rect;
/**
* This method checks whether two longitudes form a leg which crosses the date border.
* @param lng1 {H.geo.Longitude} - the start longitude of the leg
* @param lng2 {H.geo.Longitude} - the end longitude of the leg
* @returns {boolean} - true if the leg crosses the date border, otherwise false
*/
static isDBC(lng1: H.geo.Longitude, lng2: H.geo.Longitude): boolean;
/**
* This method initializes a new strip with an array of lat, lng values. Arrays are expected to have an even length with the format [lat, lng, lat, lng, ...].
* @param latLngs {Array<number>} - the array of lat, lng value.
* @returns {H.geo.Strip} - the strip containing the lat, lng values
*/
static fromLatLngArray(latLngs: Array<number>): H.geo.Strip;
}
}
/***** lang *****/
@@ -1173,6 +1292,78 @@ declare namespace H {
}
}
/**
* A Polygon with a circular shape.
*/
export class Circle extends H.map.Polygon {
/**
* Constructor
* @param center {H.geo.IPoint} - The geographical coordinates of the circle's center
* @param radius {number} - The radius of the circle in meters
* @param opt_options {H.map.Circle.Options=} - An object that specifies circle options and their initial values (among these, precision has a significant impact on the shape of the circle - please see
*/
constructor(center: H.geo.IPoint, radius: number, opt_options?: H.map.Circle.Options);
/**
* To set the geographical center point of this circle. If the specified center is an instance of H.geo.Point you must not modify this Point instance without calling setCenter immediately afterwards.
* @param center {H.geo.IPoint}
*/
setCenter(center: H.geo.IPoint): void;
/**
* To get the center point of this circle You must not modify the returned Point instance without calling setCenter immediately afterwards.
* @returns {H.geo.Point}
*/
getCenter(): H.geo.Point;
/**
* To set the length of the radius of the circle in meters. The value is clamped to the of {@code[0 ... 20015089.27787877]} (half WGS84 mean circumference)
* @param radius {number}
*/
setRadius(radius: number): void;
/**
* To get the length of the radius of the circle in meters.
* @returns {number}
*/
getRadius(): number;
/**
* To set the precision of this circle {@see H.map.Circle.Options#precision}
* @param precision {number}
*/
setPrecision(precision: number): void;
/**
* To get the precision value of this circle
* @returns {number}
*/
getPrecision(): number;
}
export module Circle {
/**
* @property style {H.map.SpatialStyle=} - the style to be used when tracing the polyline
* @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true
* @property precision {number=} - The precision of a circle as a number of segments to be used when rendering the circle. The value is clamped to the range between [4 ... 360], where 60 is the default. Note that the lower the value the more angular and the less circle-like the shape appears and, conversely, the higher the value the smoother and more rounded the result. Thus, starting at the extreme low end of the possible values, 4 produces a square, 6 a hexagon, while 30 results in a circle-like shape, although it appears increasingly angular as the zoom level increases (as you zoom in), and finally 360 produces a smooth circle.
* @property zIndex {number=} - The z-index value of the circle, default is 0
* @property min {number=} - The minimum zoom level for which the circle is visible, default is -Infinity
* @property max {number=} - The maximum zoom level for which the circle is visible, default is Infinity
* @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object.
* @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData
*/
export interface Options {
style?: H.map.SpatialStyle | H.map.SpatialStyle.Options;
visibility?: boolean;
precision?: number;
zIndex?: number;
min?: number;
max?: number;
provider?: H.map.provider.Provider;
data?: any;
}
}
/**
* The class represents data model of the map. It holds list of layers that are rendered by map's RenderEngine. The class listens to 'update' events from layers and dispatches them to the RenderEngine.
*/
@@ -1242,6 +1433,38 @@ declare namespace H {
}
}
/**
* This class represents a spatial shape in geographic space. It is defined by a path containing the vertices of the shape (lat, lng, alt values).
*/
export class GeoShape extends H.map.Spatial {
/**
* Constructor
* @param isClosed {boolean} - Indicates whether this geographical shape is closed (a polygon)
* @param strip {H.geo.Strip} - The strip describing the shape of the spatial object
* @param options {H.map.Spatial.Options} - The options to apply
*/
constructor(isClosed: boolean, strip: H.geo.Strip, options: H.map.Spatial.Options);
/**
* This method returns the strip which represents the shape of the spatial object.
* @returns {H.geo.Strip} - the strip
*/
getStrip(): H.geo.Strip;
/**
* This method sets the geo-information for the spatial object
* @param strip {?H.geo.Strip} - The strip which represents the shape of the spatial object.
* @returns {H.map.GeoShape} - the Spatial instance itself
*/
setStrip(strip: H.geo.Strip): H.map.GeoShape;
/**
* This method returns the bounding rectangle for this object. The rectangle is the smallest rectangle which encloses all points of the spatial object.
* @returns {H.geo.Rect}
*/
getBounds(): H.geo.Rect;
}
/**
* This class represents a map object which can contain other map objects. It's visibility, zIndex and object-order influences the contained map objects
*/
@@ -1855,6 +2078,92 @@ declare namespace H {
}
}
/**
* This class represents a polygon in geo-space. It is defined by a strip containing the vertices of a geo shape object (lat, lng, alt values) and a pen to use when rendering the polyline. Polygon represents a closed plane defined by the list of verticies, projected on the map display. List of vericies which define the polygon are is a list of geo coordinates encapsulated by the strip object H.geo.Strip
*/
export class Polygon extends H.map.GeoShape {
/**
* Constructor
* @param strip {H.geo.Strip} - the strip describing this polygon's vertices
* @param opt_options {H.map.Spatial.Options=} - optional initialization parameters
*/
constructor(strip: H.geo.Strip, opt_options?: H.map.Spatial.Options);
/**
* To set the indicator whether this polygon covers the north pole. It's needed for Polygons whose strip is defined as lines arround the world on longitude axis (for example a circle whose center is one of the poles). In this case a additional information is needed to know if the southern or northern part of the world should be covered by the poygon.
* @param flag {boolean} - A value of true means it covers the north pole, false means south pole
* @returns {H.map.Polygon} - the Polygon instance itself
*/
setNorthPoleCovering(flag: boolean): H.map.Polygon;
/**
* See H.map.Polygon#setNorthPoleCovering
* @returns {boolean}
*/
getNorthPoleCovering(): boolean;
}
/**
* This class represents a polyline in geo-space. It is defined by a path containing the vertices of a polyline (lat, lng, alt values) and a pen to use when tracing the path on the map.
*/
export class Polyline extends H.map.GeoShape {
/**
* Constructor
* @param strip {H.geo.Strip} - the strip describing this polygon's vertices
* @param opt_options {H.map.Polyline.Options=} - optional initialization parameters
*/
constructor(strip: H.geo.Strip, opt_options?: H.map.Polyline.Options);
/**
* This method clips this polyline against a rectangular area and returns the intersecting sub-lines.
* @param geoRect {H.geo.Rect}
* @returns {Array<Array<number>>}
*/
clip(geoRect: H.geo.Rect): Array<Array<number>>;
}
export module Polyline {
/**
* Options which are used to initialize a polyline
* @property style {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - the style to be used when tracing the polyline
* @property arrows {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} - The arrows style to be used when rendering the polyline.
* @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true
* @property zIndex {number=} - The z-index value of the map object, default is 0
* @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity
* @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity
* @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object.
* @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData
*/
export interface Options {
style?: (H.map.SpatialStyle | H.map.SpatialStyle.Options);
arrows?: (H.map.ArrowStyle | H.map.ArrowStyle.Options);
visibility?: boolean;
zIndex?: number;
min?: number;
max?: number;
provider?: H.map.provider.Provider;
data?: any;
}
}
/**
* A Polygon with a rectangular shape.
*/
export class Rect extends H.map.Polygon {
/**
* Constructor
* @param bounds {H.geo.Rect} - The geographical bounding box for this rectangle
* @param opt_options {H.map.Spatial.Options=}
*/
constructor(bounds: H.geo.Rect, opt_options?: H.map.Spatial.Options);
/**
* To set the bounds of this rectangle.
* @param bounds {H.geo.Rect}
*/
setBounds(bounds: H.geo.Rect): void;
}
/**
* This class represents a spatial map object which provides its projected geometry.
*/
@@ -1985,8 +2294,8 @@ declare namespace H {
miterLimit: number;
lineDash: Array<number>;
lineDashOffset: number;
MAX_LINE_WIDTH: number;
DEFAULT_STYLE: H.map.SpatialStyle;
static MAX_LINE_WIDTH: number;
static DEFAULT_STYLE: H.map.SpatialStyle;
}
export module SpatialStyle {
@@ -2018,7 +2327,7 @@ declare namespace H {
lineCap?: H.map.SpatialStyle.LineCap;
lineJoin?: H.map.SpatialStyle.LineJoin;
miterLimit?: number;
lineDash: Array<number>;
lineDash?: Array<number>;
lineDashOffset?: number;
}
}
+71
View File
@@ -0,0 +1,71 @@
/// <reference path="humps.d.ts" />
// Tests evaluated from:
// https://github.com/domchristie/humps/blob/master/README.md
import * as humps from "humps";
let someObject = { attr_one: 'foo', attr_two: 'bar' };
let someArray = [{ attr_one: 'foo' }, { attr_one: 'bar' }]
let someOptions: humps.HumpsOptions = {
separator: '-'
};
let someOptions2: humps.HumpsOptions = {
split: /^[A-Z0-9_]+$/
};
let someOptions3: humps.HumpsOptions = {
separator: '-',
process: function (key: string, convert: humps.HumpsProcessorParameter, options: humps.HumpsOptions) {
return /^[A-Z0-9_]+$/.test(key) ? key : convert(key, options);
}
};
humps.camelize('hello_world')
humps.decamelize('fooBar')
humps.decamelize('fooBarBaz', someOptions)
humps.camelizeKeys(someObject);
humps.camelizeKeys(someArray);
humps.camelizeKeys(someObject, function (key, convert) {
return /^[A-Z0-9_]+$/.test(key) ? key : convert(key);
});
humps.decamelizeKeys(someObject, function (key, convert, options) {
return /^[A-Z0-9_]+$/.test(key) ? key : convert(key, options);
});
humps.camelize('hello_world-foo bar');
humps.pascalize('hello_world-foo bar');
humps.decamelize('helloWorldFooBar');
humps.decamelize('helloWorldFooBar', someOptions);
humps.decamelize('helloWorld1', { split: /(?=[A-Z0-9])/ })
humps.depascalize('helloWorldFooBar');
humps.camelizeKeys(someObject);
humps.pascalizeKeys(someObject);
humps.decamelizeKeys(someObject);
humps.depascalizeKeys(someObject);
humps.camelizeKeys(someObject, someOptions);
humps.pascalizeKeys(someObject, someOptions);
humps.decamelizeKeys(someObject, someOptions);
humps.depascalizeKeys(someObject, someOptions);
humps.camelizeKeys(someObject, someOptions2);
humps.pascalizeKeys(someObject, someOptions2);
humps.decamelizeKeys(someObject, someOptions2);
humps.depascalizeKeys(someObject, someOptions2);
humps.camelizeKeys(someObject, someOptions3);
humps.pascalizeKeys(someObject, someOptions3);
humps.decamelizeKeys(someObject, someOptions3);
humps.depascalizeKeys(someObject, someOptions3);
+39
View File
@@ -0,0 +1,39 @@
// Type definitions for humps v1.1.0
// Project: https://github.com/domchristie/humps
// Definitions by: Niklas Mollenhauer <https://github.com/nikeee>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace humps {
function camelize(value: string): string;
function pascalize(value: string): string;
function decamelize(value: string, optionsOrProcessor?: OptionOrProcessor): string;
function depascalize(value: string, optionsOrProcessor?: OptionOrProcessor): string;
function camelizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object;
function pascalizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object;
function decamelizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object;
function depascalizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object;
function camelizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[];
function pascalizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[];
function decamelizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[];
function depascalizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[];
interface HumpsOptions {
separator?: string;
split?: RegExp;
process?: HumpsProcessor;
}
interface HumpsProcessor {
(key: string, convert: HumpsProcessorParameter, options?: HumpsOptions): string;
}
interface HumpsProcessorParameter {
(key: string, options?: HumpsOptions): string;
}
type OptionOrProcessor = HumpsOptions | HumpsProcessor;
}
declare module "humps" {
export = humps;
}
@@ -0,0 +1,21 @@
/// <reference path="../i18next/i18next"/>
/// <reference path="i18next-xhr-backend.d.ts"/>
import * as i18next from 'i18next';
import XHR from 'i18next-xhr-backend';
let options = {
loadPath: '',
addPath: '',
allowMultiLoading: false,
parse: function(data:string) { return data.replace(/a/g, ''); },
crossDomain: false,
withCredentials: false,
ajax: function (url:string, options:Object, callback: Function, data: Object) {}
};
i18next.use(XHR).init({
backend: options
});
let xhr = new XHR(null, options);
+36
View File
@@ -0,0 +1,36 @@
// Type definitions for i18next-xhr-backend 1.2.0
// Project: https://github.com/i18next/i18next-xhr-backend
// Definitions by: Jan Mühlemann <https://github.com/jamuhl>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'i18next-xhr-backend' {
interface Interpolator {
interpolate: () => string
}
interface Services {
interpolator: Interpolator
}
interface BackendOptions {
loadPath?: string | Function,
addPath?: string,
allowMultiLoading?: boolean,
parse?: Function,
crossDomain?: boolean,
withCredentials?: boolean,
ajax?: Function
}
export default class Backend {
type: 'backend';
services: Services;
options: BackendOptions;
constructor(services?: Services, options?: BackendOptions);
init(services?: Services, options?: BackendOptions): void;
readMulti(languages: any[], namespaces: any[], callback: Function): void;
read(language: {}, namespace: {}, callback: Function): void;
loadUrl(url: string, callback: Function): void;
create(languages: any[], namespace: string, key: string, fallbackValue: string): void;
}
}
+25
View File
@@ -0,0 +1,25 @@
/// <reference path="is-plain-object.d.ts" />
import * as isPlainObject from 'is-plain-object';
isPlainObject(Object.create({}));
//=> true
isPlainObject(Object.create(Object.prototype));
//=> true
isPlainObject({foo: 'bar'});
//=> true
isPlainObject({});
isPlainObject(1);
//=> false
isPlainObject(['foo', 'bar']);
//=> false
isPlainObject([]);
//=> false
class Foo {}
isPlainObject(new Foo);
//=> false
isPlainObject(null);
//=> false
isPlainObject(Object.create(null));
//=> false
+10
View File
@@ -0,0 +1,10 @@
// Type definitions for is-plain-object
// Project: https://github.com/jonschlinkert/is-plain-object
// Definitions by: Kevin Zeng <https://github.com/zengfenfei/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "is-plain-object" {
namespace isPlainObject {}
function isPlainObject(obj: any): boolean;
export = isPlainObject;
}
+231 -2
View File
@@ -1,4 +1,5 @@
/// <reference path="jest.d.ts" />
/// <reference path="../node/node.d.ts" />
// Tests based on the Jest website
jest.unmock('../sum');
@@ -37,8 +38,6 @@ describe('fetchCurrentUser', function() {
// unmock is the recommended approach for unmocking...
jest.unmock('../displayUser.js')
// ...but dontMock also still works.
jest.dontMock('jquery');
describe('displayUser', function() {
it('displays a user after a click', function() {
@@ -100,6 +99,157 @@ describe('CheckboxWithLabel', function() {
});
});
jest.runAllTicks();
xdescribe('Hooks and Suits', function () {
let tested: boolean;
beforeEach(function () {
tested = false;
});
afterEach(function () {
tested = true;
});
test('tested', function () {
expect(tested).toBeTruthy();
expect(tested).not.toBeFalsy();
});
fit('tested', function () {
expect(tested).toBeDefined();
expect(tested).not.toBeUndefined();
});
xit('expect null to be null', function () {
expect(null).toBeNull();
});
});
describe('compartion', function () {
var sum: (a: number, b: number) => number = require.requireMock('../sum');
it('compares is 7 + 2 greater than 3', function () {
expect(sum(7, 2)).toBeGreaterThan(3);
});
it('compares is 2 + 7 greater than or equal to 3', function () {
expect(sum(2, 7)).toBeGreaterThanOrEqual(3);
});
it('compares is 3 less than 3 + 4', function () {
expect(3).toBeLessThan(sum(3, 4));
});
it('compares is 3 less than or equal to 4 + 3', function () {
expect(3).toBeLessThanOrEqual(sum(4, 3));
});
it('works sanely with simple decimals', function () {
expect(0.2 + 0.1).toBeCloseTo(0.3, 5);
});
});
describe('toThrow API', function () {
function throwTypeError(): void {
throw new TypeError('toThrow Definition was out of date');
}
it('throws', function () {
expect(throwTypeError()).toThrow();
});
it('throws TypeError', function () {
expect(throwTypeError()).toThrowError(TypeError);
});
it('throws \'Definition was out of date\'', function () {
expect(throwTypeError()).toThrowError(/Definition was out of date/);
});
it('throws \'toThorow Definition was out of date\'', function () {
expect(throwTypeError()).toThrowError('toThrow Definition was out of date');
});
});
describe('missing tests', function () {
it('creates closures', function () {
class Closure<T> {
private arg: T;
public constructor(private fn: (arg: T) => void) {
this.fn = fn;
}
public bind(arg: T): void {
this.arg = arg;
}
public call(): void {
this.fn(this.arg);
}
}
type StringClosure = (arg: string) => void;
let spy: jest.Mock<StringClosure> = jest.fn<StringClosure>();
let closure: Closure<string> = new Closure<string>(spy);
closure.bind('jest');
closure.call();
expect(spy).lastCalledWith('jest');
expect(spy).toBeCalledWith('jest');
expect(jest.isMockFunction(spy)).toBeTruthy();
});
it('tests all mising Mocks functionality', function () {
type FruitsGetter = () => Array<string>;
let mock: jest.Mock<FruitsGetter> = jest.fn<FruitsGetter>();
mock.mockImplementationOnce(() => ['Orange', 'Apple', 'Plum'])
jest.setMock('./../tesks/getFruits', mock);
const getFruits: FruitsGetter = require('./../tesks/getFruits');
expect(getFruits()).toContain('Orange');
mock.mockReturnValueOnce(['Apple', 'Plum']);
expect(mock()).not.toContain('Orange');
mock.mockReturnValue([]); //Deprecated: Use jest.fn(() => value) instead.
mock.mockClear();
let thisMock: jest.Mock<any> = jest.fn<any>().mockReturnThis();
expect(thisMock()).toBe(this);
});
it('creates snapshoter', function () {
jest.disableAutomock();
jest.mock('./render', () => jest.fn((): string => "{Link to: \"facebook\"}"), { virtual: true });
const render: () => string = require('./render');
expect(render()).toMatch(/Link/);
jest.enableAutomock();
});
it('runs only pending timers', function () {
jest.useRealTimers();
setTimeout(() => expect(1).not.toEqual(0), 3000);
jest.runOnlyPendingTimers();
});
it('runs all timers', function () {
jest.clearAllTimers();
jest.useFakeTimers();
setTimeout(() => expect(0).not.toEqual(1), 3000);
jest.runAllTimers();
});
it('cleares cache', function () {
const sum1 = require('../sum');
jest.resetModules();
const sum2 = require('../sum');
expect(sum1).not.toBe(sum2);
})
});
describe('toMatchSnapshot', function () {
it('compares snapshots', function () {
expect({ type: 'a', props: { href: 'https://www.facebook.com/' }, children: [ 'Facebook' ] }).toMatchSnapshot();
});
});
function testInstances() {
var mockFn = jest.fn<Function>();
var a = new mockFn();
@@ -123,3 +273,82 @@ function testMockImplementation() {
mockFn.mock.calls[0][0] === 0; // true
mockFn.mock.calls[1][0] === 1; // true
}
// Test from jest Docs: <http://facebook.github.io/jest/docs/manual-mocks.html#content>
describe('genMockFromModule', function () {
// Interfaces:
interface MockFiles {
[index: string]: string;
}
interface MockedFS {
readdirSync: (dir: string) => string[];
__setMockFiles: (newMockFiles: MockFiles) => void ;
}
// ------------------------------------------------------------------------------------
// FileSummarizer.ts
const fs = require('fs');
function summarizeFilesInDirectorySync(directory: string): string[] {
return fs.readdirSync(directory).map((fileName: string) => ({
fileName,
directory,
}));
}
//export default summarizeFilesInDirectorySync; // For sake of compilation
// ------------------------------------------------------------------------------------
// __mocks__/fs.js
const path = require('path');
const mockedFS: MockedFS = jest.genMockFromModule<MockedFS>('fs');
let mockFiles: any = Object.create(null);
function __setMockFiles(newMockFiles: MockFiles): void {
mockFiles = Object.create(null);
for(const file in newMockFiles) {
const dir: string = path.dirname(file);
if (!mockFiles[dir]) {
mockFiles[dir] = [];
}
mockFiles[dir].push(path.basename(file));
}
}
function readdirSync(directoryPath: string): string[] {
return mockFiles[directoryPath] || [];
}
mockedFS.readdirSync = readdirSync;
mockedFS.__setMockFiles = __setMockFiles;
//export = mockedFS; // For sake of compilation
// ------------------------------------------------------------------------------------
// __tests__/FileSummarizer-test.js
jest.mock('fs');
describe('listFilesInDirectorySync', () => {
const MOCK_FILE_INFO: MockFiles = {
'/path/to/file1.js': 'console.log("file1 contents");',
'/path/to/file2.txt': 'file2 contents',
};
beforeEach(() => {
// Set up some mocked out file info before each test
(require('fs') as MockedFS).__setMockFiles(MOCK_FILE_INFO);
});
it('includes all files in the directory in the summary', () => {
const FileSummarizer: (dir: string) => string[] = require('../FileSummarizer');
const fileSummary = FileSummarizer('/path/to');
expect(fileSummary.length).toBe(2);
});
});
});
+215 -47
View File
@@ -1,78 +1,150 @@
// Type definitions for Jest 0.9.0
// Type definitions for Jest 15.1.1
// Project: http://facebook.github.io/jest/
// Definitions by: Asana <https://asana.com>
// Definitions by: Asana <https://asana.com>, Ivo Stratev <https://github.com/NoHomey>, jwbay <https://github.com/jwbay>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare function afterEach(fn: jest.EmptyFunction): void;
declare function beforeEach(fn: jest.EmptyFunction): void;
declare function describe(name: string, fn: jest.EmptyFunction): void;
declare var beforeAll: jest.Lifecycle;
declare var beforeEach: jest.Lifecycle;
declare var afterAll: jest.Lifecycle;
declare var afterEach: jest.Lifecycle;
declare var describe: jest.Describe;
declare var fdescribe: jest.Describe;
declare var xdescribe: jest.Describe;
declare var it: jest.It;
declare function pit(name: string, fn: jest.EmptyFunction): void;
declare function xdescribe(name: string, fn: jest.EmptyFunction): void;
declare function xit(name: string, fn: jest.EmptyFunction): void;
declare var fit: jest.It;
declare var xit: jest.It;
declare var test: jest.It;
declare var xtest: jest.It;
declare function expect(actual: any): jest.Matchers;
interface NodeRequire {
/** Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. */
requireActual(moduleName: string): any;
/** Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not. */
requireMock(moduleName: string): any;
}
declare namespace jest {
function addMatchers(matchers: CustomMatcherFactories): void;
function addMatchers(matchers: jasmine.CustomMatcherFactories): void;
/** Disables automatic mocking in the module loader. */
function autoMockOff(): void;
/** Enables automatic mocking in the module loader. */
function autoMockOn(): void;
/** Removes any pending timers from the timer system. If any timers have been scheduled, they will be cleared and will never have the opportunity to execute in the future. */
function clearAllTimers(): void;
function currentTestPath(): string;
/** Indicates that the module system should never return a mocked version of the specified module, including all of the specificied module's dependencies. */
function deepUnmock(moduleName: string): void;
/** Disables automatic mocking in the module loader. */
function disableAutomock(): void;
function fn<T>(implementation?: Function): Mock<T>;
/** Mocks a module with an auto-mocked version when it is being required. */
function doMock(moduleName: string): void;
/** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */
function dontMock(moduleName: string): void;
function genMockFromModule<T>(moduleName: string): Mock<T>;
function mock(moduleName: string, factory?: Function): void;
/** Enables automatic mocking in the module loader. */
function enableAutomock(): void;
/** Creates a mock function. Optionally takes a mock implementation. */
function fn<T>(implementation?: Function): Mock<T>;
/** Use the automatic mocking system to generate a mocked version of the given module. */
function genMockFromModule<T>(moduleName: string): T;
/** Returns whether the given function is a mock function. */
function isMockFunction(fn: any): fn is Mock<any>;
/** Mocks a module with an auto-mocked version when it is being required. */
function mock(moduleName: string, factory?: any, options?: MockOptions): void;
/** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */
function resetModuleRegistry(): void;
/** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */
function resetModules(): void;
/** Exhausts tasks queued by setImmediate(). */
function runAllImmediates(): void;
/** Exhausts the micro-task queue (usually interfaced in node via process.nextTick). */
function runAllTicks(): void;
/** Exhausts the macro-task queue (i.e., all tasks queued by setTimeout() and setInterval()). */
function runAllTimers(): void;
/** Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by setTimeout() or setInterval() up to this point).
* If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call. */
function runOnlyPendingTimers(): void;
/** Explicitly supplies the mock object that the module system should return for the specified module. */
function setMock<T>(moduleName: string, moduleExports: T): void;
/** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */
function unmock(moduleName: string): void;
/** Instructs Jest to use fake versions of the standard timer functions. */
function useFakeTimers(): void;
/** Instructs Jest to use the real versions of the standard timer functions. */
function useRealTimers(): void;
interface MockOptions {
virtual?: boolean;
}
interface EmptyFunction {
(): void;
}
interface Matchers {
not: Matchers;
toThrow(expected?: any): boolean;
toBe(expected: any): boolean;
toEqual(expected: any): boolean;
toBeFalsy(): boolean;
toBeTruthy(): boolean;
toBeNull(): boolean;
toBeDefined(): boolean;
toBeUndefined(): boolean;
toMatch(expected: RegExp): boolean;
toContain(expected: string): boolean;
toBeCloseTo(expected: number, delta: number): boolean;
toBeGreaterThan(expected: number): boolean;
toBeLessThan(expected: number): boolean;
toBeCalled(): boolean;
toBeCalledWith(...args: any[]): boolean;
lastCalledWith(...args: any[]): boolean;
interface DoneCallback {
(...args: any[]): any
fail(error?: string | { message: string }): any;
}
interface ProvidesCallback {
(cb?: DoneCallback): any;
}
interface Lifecycle {
(fn: ProvidesCallback): any;
}
interface It {
(name: string, fn: EmptyFunction): void;
only(name: string, fn: EmptyFunction): void;
(name: string, fn: ProvidesCallback): void;
only: It;
skip: It;
}
interface Mock<T> {
interface Describe {
(name: string, fn: EmptyFunction): void
only: Describe;
skip: Describe;
}
interface Matchers {
not: Matchers;
lastCalledWith(...args: any[]): void;
toBe(expected: any): void;
toBeCalled(): void;
toBeCalledWith(...args: any[]): void;
toBeCloseTo(expected: number, delta: number): void;
toBeDefined(): void;
toBeFalsy(): void;
toBeGreaterThan(expected: number): void;
toBeGreaterThanOrEqual(expected: number): void;
toBeInstanceOf(expected: any): void
toBeLessThan(expected: number): void;
toBeLessThanOrEqual(expected: number): void;
toBeNull(): void;
toBeTruthy(): void;
toBeUndefined(): void;
toContain(expected: any): void;
toEqual(expected: any): void;
toHaveBeenCalled(): boolean;
toHaveBeenCalledTimes(expected: number): boolean;
toHaveBeenCalledWith(...params: any[]): boolean;
toMatch(expected: string | RegExp): void;
toMatchSnapshot(): void;
toThrow(): void;
toThrowError(error?: string | Constructable | RegExp): void;
}
interface Constructable {
new (...args: any[]): any
}
interface Mock<T> extends Function {
new (): T;
(...args: any[]): any; // TODO please fix this line! added for TypeScript 1.1.0-1 https://github.com/DefinitelyTyped/DefinitelyTyped/pull/2932
(...args: any[]): any;
mock: MockContext<T>;
mockClear(): void;
mockImplementation(fn: Function): Mock<T>;
mockImpl(fn: Function): Mock<T>;
mockImplementationOnce(fn: Function): Mock<T>;
mockReturnThis(): Mock<T>;
mockReturnValue(value: any): Mock<T>;
mockReturnValueOnce(value: any): Mock<T>;
@@ -82,42 +154,138 @@ declare namespace jest {
calls: any[][];
instances: T[];
}
}
//Jest ships with a copy of Jasmine. They monkey-patch its APIs and divergence/deprecation are expected.
//Relevant parts of Jasmine's API are below so they can be changed and removed over time.
//This file can't reference jasmine.d.ts since the globals aren't compatible.
declare function spyOn(object: any, method: string): jasmine.Spy;
/** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */
declare function pending(reason?: string): void;
/** Fails a test when called within one. */
declare function fail(error?: any): void;
declare namespace jasmine {
var clock: () => Clock;
function any(aclass: any): Any;
function anything(): Any;
function arrayContaining(sample: any[]): ArrayContaining;
function objectContaining(sample: any): ObjectContaining;
function createSpy(name: string, originalFn?: Function): Spy;
function createSpyObj(baseName: string, methodNames: any[]): any;
function createSpyObj<T>(baseName: string, methodNames: any[]): T;
function pp(value: any): string;
function addCustomEqualityTester(equalityTester: CustomEqualityTester): void;
function addMatchers(matchers: CustomMatcherFactories): void;
function stringMatching(value: string | RegExp): Any;
interface Clock {
install(): void;
uninstall(): void;
/** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */
tick(ms: number): void;
mockDate(date?: Date): void;
}
interface Any {
new (expectedClass: any): any;
jasmineMatches(other: any): boolean;
jasmineToString(): string;
}
interface ArrayContaining {
new (sample: any[]): any;
asymmetricMatch(other: any): boolean;
jasmineToString(): string;
}
interface ObjectContaining {
new (sample: any): any;
jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean;
jasmineToString(): string;
}
interface Spy {
(...params: any[]): any;
identity: string;
and: SpyAnd;
calls: Calls;
mostRecentCall: { args: any[]; };
argsForCall: any[];
wasCalled: boolean;
}
interface SpyAnd {
/** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */
callThrough(): Spy;
/** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */
returnValue(val: any): Spy;
/** By chaining the spy with and.returnValues, all calls to the function will return specific values in order until it reaches the end of the return values list. */
returnValues(...values: any[]): Spy;
/** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */
callFake(fn: Function): Spy;
/** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */
throwError(msg: string): Spy;
/** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */
stub(): Spy;
}
interface Calls {
/** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. */
any(): boolean;
/** By chaining the spy with calls.count(), will return the number of times the spy was called */
count(): number;
/** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index */
argsFor(index: number): any[];
/** By chaining the spy with calls.allArgs(), will return the arguments to all calls */
allArgs(): any[];
/** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls */
all(): CallInfo[];
/** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call */
mostRecent(): CallInfo;
/** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call */
first(): CallInfo;
/** By chaining the spy with calls.reset(), will clears all tracking for a spy */
reset(): void;
}
interface CallInfo {
/** The context (the this) for the call */
object: any;
/** All arguments passed to the call */
args: any[];
/** The return value of the call */
returnValue: any;
}
// taken from Jasmine since addMatchers calls into the jasmine api
interface CustomMatcherFactories {
[index: string]: CustomMatcherFactory;
}
// taken from Jasmine since addMatchers calls into the jasmine api
interface CustomMatcherFactory {
(util: MatchersUtil, customEqualityTesters: Array<CustomEqualityTester>): CustomMatcher;
}
// taken from Jasmine since addMatchers calls into the jasmine api
interface MatchersUtil {
equals(a: any, b: any, customTesters?: Array<CustomEqualityTester>): boolean;
contains<T>(haystack: ArrayLike<T> | string, needle: any, customTesters?: Array<CustomEqualityTester>): boolean;
buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array<any>): string;
}
// taken from Jasmine since addMatchers calls into the jasmine api
interface CustomEqualityTester {
(first: any, second: any): boolean;
}
// taken from Jasmine since addMatchers calls into the jasmine api
interface CustomMatcher {
compare<T>(actual: T, expected: T): CustomMatcherResult;
compare(actual: any, expected: any): CustomMatcherResult;
}
// taken from Jasmine since addMatchers calls into the jasmine api
interface CustomMatcherResult {
pass: boolean;
message: string;
message: string | (() => string);
}
// taken from Jasmine which takes from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains()
interface ArrayLike<T> {
length: number;
[n: number]: T;
+103 -93
View File
@@ -82,21 +82,21 @@ $(document).ready(function () {
width: "200px"
}
col =
{
data: "",
orderData: [10, 11, 20],
render: "",
}
{
data: "",
orderData: [10, 11, 20],
render: "",
}
col =
{
data: colDataObject,
render: colRenderObject,
}
{
data: colDataObject,
render: colRenderObject,
}
col =
{
data: colDataFunc,
render: colRenderFunc,
}
{
data: colDataFunc,
render: colRenderFunc,
}
//#endregion "Column"
@@ -124,16 +124,16 @@ $(document).ready(function () {
};
colDef =
{
targets: "2",
cellType: "th",
};
{
targets: "2",
cellType: "th",
};
colDef =
{
targets: ["2", 5],
cellType: "th",
};
{
targets: ["2", 5],
cellType: "th",
};
//#endregion "ColumnDef"
@@ -159,7 +159,7 @@ $(document).ready(function () {
var ajaxFunc: DataTables.FunctionAjax = function (data, callback, settings) { };
var ajaxDataFunc: DataTables.FunctionAjaxData = function (data) {
var ajaxDataFunc: DataTables.FunctionAjaxData = function (data, settings) {
return data;
};
@@ -229,41 +229,41 @@ $(document).ready(function () {
config =
{
ajax: ajaxFunc,
deferLoading: [10, 100],
lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
order: [0, 'asc'],
orderFixed: [[0, 'asc'], [1, 'asc']],
renderer: {
header: "bootstrap",
pageButton: "jqueryui"
},
search: { "search": "", "smart": true, "regex": false, "caseInsensitive": true },
searchCols: [
null,
{ "search": "", "smart": true, "regex": false, "caseInsensitive": true },
{ "search": "" },
{ "search": "", "smart": true },
null
],
};
{
ajax: ajaxFunc,
deferLoading: [10, 100],
lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
order: [0, 'asc'],
orderFixed: [[0, 'asc'], [1, 'asc']],
renderer: {
header: "bootstrap",
pageButton: "jqueryui"
},
search: { "search": "", "smart": true, "regex": false, "caseInsensitive": true },
searchCols: [
null,
{ "search": "", "smart": true, "regex": false, "caseInsensitive": true },
{ "search": "" },
{ "search": "", "smart": true },
null
],
};
config =
{
ajax: {
data: {},
dataSrc: "",
},
};
{
ajax: {
data: {},
dataSrc: "",
},
};
config =
{
ajax: {
data: ajaxDataFunc,
dataSrc: function (data) { },
},
};
{
ajax: {
data: ajaxDataFunc,
dataSrc: function (data) { },
},
};
//#endregion "Settings"
@@ -309,6 +309,8 @@ $(document).ready(function () {
draw = dt.draw(true);
draw.$("");
var initSettings = dt.init();
var off = dt.off("event");
off = dt.off("event", function () { });
off.$("");
@@ -385,11 +387,11 @@ $(document).ready(function () {
var select = $('<select />')
.appendTo('body')
.on('change', function () {
dt
.column(0)
.search($(this).val())
.draw();
});
dt
.column(0)
.search($(this).val())
.draw();
});
// Get the search data for the first column and add to the select list
var data = dt
.cells('', 0)
@@ -397,8 +399,8 @@ $(document).ready(function () {
.sort()
.unique()
.each(function (d) {
select.append($('<option value="' + d + '">' + d + '</option>'));
});
select.append($('<option value="' + d + '">' + d + '</option>'));
});
var cells_data = cells.data();
var data = dt
@@ -438,6 +440,9 @@ $(document).ready(function () {
console.log(data);
});
cells.every(function () { });
cells.every(function (cellRowIdx, cellColIdx, tableLoop, cellLoop) { });
var cell = dt.cell(":contains('Not shipped')");
cell = dt.cell(function () { });
cell = dt.cell($(""));
@@ -519,12 +524,12 @@ $(document).ready(function () {
dt.column(colIdx).footer()
)
.on('change', function () {
dt
.column(colIdx)
.search($(this).val())
.draw();
});
dt
.column(colIdx)
.search($(this).val())
.draw();
});
// Get the search data for the first column and add to the select list
dt
.column(colIdx)
@@ -532,8 +537,8 @@ $(document).ready(function () {
.sort()
.unique()
.each(function (d) {
select.append($('<option value="' + d + '">' + d + '</option>'));
});
select.append($('<option value="' + d + '">' + d + '</option>'));
});
});
var columns_data = columns.data();
@@ -545,7 +550,7 @@ $(document).ready(function () {
.sort() // Sort data alphabetically
.unique() // Reduce to unique values
.join('<br>')
);
);
//var idx = dt
// .columns('.check')
@@ -603,12 +608,12 @@ $(document).ready(function () {
dt.column(0).footer()
)
.on('change', function () {
dt
.column(0)
.search($(this).val())
.draw();
});
dt
.column(0)
.search($(this).val())
.draw();
});
// Get the search data for the first column and add to the select list
dt
.column(0)
@@ -616,18 +621,18 @@ $(document).ready(function () {
.sort()
.unique()
.each(function (d) {
select.append($('<option value="' + d + '">' + d + '</option>'));
});
select.append($('<option value="' + d + '">' + d + '</option>'));
});
var column_data = column.data();
alert('Column 4 sum: ' +
dt
.column(4)
.data()
.reduce(function (a, b) {
return a + b;
})
);
.reduce(function (a, b) {
return a + b;
})
);
var column_dataSrc = column.dataSrc();
$('#example').on('click', 'tbody td', function () {
@@ -688,11 +693,11 @@ $(document).ready(function () {
)
.on('change', function () {
dt
.column(colIdx)
.search($(this).val())
.draw();
});
.column(colIdx)
.search($(this).val())
.draw();
});
// Get the search data for the first column and add to the select list
dt
.column(colIdx)
@@ -700,8 +705,8 @@ $(document).ready(function () {
.sort()
.unique()
.each(function (d) {
select.append($('<option value="' + d + '">' + d + '</option>'));
});
select.append($('<option value="' + d + '">' + d + '</option>'));
});
});
var column_visible_get = column.visible();
@@ -709,12 +714,15 @@ $(document).ready(function () {
column_visible_set = column.visible(false, true);
alert('Column index 0 is ' +
(dt.column(0).visible() === true ? 'visible' : 'not visible')
);
);
for (var i = 0; i < 4; i++) {
dt.column(i).visible(false, false);
}
dt.columns.adjust().draw(false); // adjust column sizing and redraw
dt.columns().every(function () { });
dt.columns().every(function (colIdx, tableLoop, colLoop) { });
//#endregion "Methods-Column"
//#region "Methods-Row"
@@ -754,6 +762,8 @@ $(document).ready(function () {
var rows_11 = dt.rows("selector").remove();
var rows_12 = dt.rows("selector").nodes();
var rows_13 = dt.rows.add([{}, {}]);
dt.rows().every(function () { });
dt.rows().every(function (rowIdx, tableLoop, rowLoop) { });
var table3 = $('#example').DataTable();
table3.row.add({
@@ -791,9 +801,9 @@ $(document).ready(function () {
pupil,
])
.draw();
//.nodes()
//.to$()
//.addClass('new');
//.nodes()
//.to$()
//.addClass('new');
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).parents('tr');
@@ -829,7 +839,7 @@ $(document).ready(function () {
'<td>' + rowIdx + '.3</td>' +
'<td>' + rowIdx + '.4</td>' +
'</tr>'
)
)
)
.show();
});
+44 -14
View File
@@ -1,4 +1,4 @@
// Type definitions for JQuery DataTables 1.10.5
// Type definitions for JQuery DataTables 1.10.6
// Project: http://www.datatables.net
// Definitions by: Kiarash Ghiaseddin <https://github.com/Silver-Connection/DefinitelyTyped>, Omid Rad <https://github.com/omidkrad>, Armin Sander <https://github.com/pragmatrix/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -159,7 +159,7 @@ declare namespace DataTables {
/**
* Get jquery object
*/
$(selector: string | Node | Node[]| JQuery, modifier?: ObjectSelectorModifier): JQuery;
$(selector: string | Node | Node[] | JQuery, modifier?: ObjectSelectorModifier): JQuery;
///// Almost identical to $ in operation, but in this case returns the data for the matched rows.
//_(selector: string | Node | Node[] | JQuery, modifier?: ObjectSelectorModifier): JQuery;
@@ -188,6 +188,11 @@ declare namespace DataTables {
*/
draw(reset?: boolean): DataTable;
/*
* Get the initialisation options used for the table. Since: DataTables 1.10.6
*/
init(): Settings;
/**
* Table events removal.
*
@@ -628,6 +633,13 @@ declare namespace DataTables {
*/
data(): DataTable;
/**
* Iterate over each selected cell, with the function context set to be the cell in question. Since: DataTables 1.10.6
*
* @param fn Function to execute for every cell selected.
*/
every(fn: (cellRowIdx: number, cellColIdx: number, tableLoop: number, cellLoop: number) => void): DataTable;
/**
* Get index information about the selected cells
*/
@@ -749,6 +761,13 @@ declare namespace DataTables {
*/
dataSrc(): DataTable;
/**
* Iterate over each selected column, with the function context set to be the column in question. Since: DataTables 1.10.6
*
* @param fn Function to execute for every column selected.
*/
every(fn: (colIdx: number, tableLoop: number, colLoop: number) => void): DataTable;
/**
* Get the column indexes of the selected columns.
*
@@ -847,7 +866,7 @@ declare namespace DataTables {
*
* @param data Data to use for the new row. This may be an array, object or Javascript object instance, but must be in the same format as the other data in the table
*/
add(data: any[]| Object): DataTable;
add(data: any[] | Object): DataTable;
}
interface RowMethods extends DataTableCore, CommonRowMethod {
@@ -859,14 +878,14 @@ declare namespace DataTables {
/**
* Get the data for the selected row
*/
data(): any[]| Object;
data(): any[] | Object;
/**
* Set the data for the selected row
*
* @param d Data to use for the row.
*/
data(d: any[]| Object): DataTable;
data(d: any[] | Object): DataTable;
/**
* Get the row index of the row column.
@@ -919,7 +938,14 @@ declare namespace DataTables {
*
* @param d Data to use for the row.
*/
data(d: any[]| Object): DataTable;
data(d: any[] | Object): DataTable;
/**
* Iterate over each selected row, with the function context set to be the row in question. Since: DataTables 1.10.6
*
* @param fn Function to execute for every row selected.
*/
every(fn: (rowIdx: number, tableLoop: number, rowLoop: number) => void): DataTable;
/**
* Get the row indexes of the selected rows.
@@ -1031,7 +1057,7 @@ declare namespace DataTables {
*
* @param table Selector string for table
*/
Api(selector: string | Node | Node[]| JQuery): DataTables.DataTable;
Api(selector: string | Node | Node[] | JQuery): DataTables.DataTable;
}
export interface StaticUtilFunctions {
@@ -1175,7 +1201,7 @@ declare namespace DataTables {
/**
* Change the options in the page length select list. Since: 1.10
*/
lengthMenu?: (number | string)[]| (number | string)[][];
lengthMenu?: (number | string)[] | (number | string)[][];
/**
* Control which cell the order event handler will be applied to in a column. Since: 1.10
@@ -1190,12 +1216,12 @@ declare namespace DataTables {
/**
* Initial order (sort) to apply to the table. Since: 1.10
*/
order?: (string | number)[]| (string | number)[][];
order?: (string | number)[] | (string | number)[][];
/**
* Ordering to always be applied to the table. Since: 1.10
*/
orderFixed?: (string | number)[]| (string | number)[][]| Object;
orderFixed?: (string | number)[] | (string | number)[][] | Object;
/**
* Multiple column ordering ability control. Since: 1.10
@@ -1395,7 +1421,11 @@ declare namespace DataTables {
}
interface FunctionAjaxData {
(data: Object): string | Object;
/*
* @param data Data that DataTables has constructed for the request.
* @param settings DataTables settings object. Since 1.10.6
*/
(data: Object, settings: Settings): string | Object;
}
//#endregion "ajax-settings"
@@ -1558,7 +1588,7 @@ declare namespace DataTables {
//#region "callback-functions"
interface FunctionCreateRow {
(row: Node, data: any[]| Object, dataIndex: number): void;
(row: Node, data: any[] | Object, dataIndex: number): void;
}
interface FunctionDrawCallback {
@@ -1590,7 +1620,7 @@ declare namespace DataTables {
}
interface FunctionRowCallback {
(row: Node, data: any[]| Object): void;
(row: Node, data: any[] | Object): void;
}
interface FunctionStateLoadCallback {
@@ -1617,7 +1647,7 @@ declare namespace DataTables {
//#region "language-settings"
// these are all optional
// these are all optional
interface LanguageSettings {
emptyTable?: string;
info?: string;
+4 -2
View File
@@ -2780,8 +2780,9 @@ interface JQuery {
/**
* Retrieve all the elements contained in the jQuery set, as an array.
* @name toArray
*/
toArray(): any[];
toArray(): HTMLElement[];
/**
* Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.
@@ -2837,8 +2838,9 @@ interface JQuery {
get(index: number): HTMLElement;
/**
* Retrieve the elements matched by the jQuery object.
* @alias toArray
*/
get(): any[];
get(): HTMLElement[];
/**
* Search for a given element from among the matched elements.
+1 -1
View File
@@ -15,7 +15,7 @@ declare namespace JSData {
catch<U>(onRejected?:(error:any) => U | JSDataPromise<U>): JSDataPromise<U>;
// enhanced with finally
finally<U>(finallyCb?:() => U):JSDataPromise<U>;
finally(finallyCb?:() => any): JSDataPromise<R>;
}
interface DSConfiguration extends IDSResourceLifecycleEventHandlers {
+1 -1
View File
@@ -42,7 +42,7 @@ declare module 'jspdf' {
'getPageInfo'(pageNumberOneBased:number):any;
'getCurrentPageInfo'():any;
};
addPage():jsPDF;
addPage(sizes?: number[]):jsPDF;
setPage(n:number):jsPDF;
insertPage(beforePage:number):jsPDF;
movePage(targetPage:number, beforePage:number):jsPDF;
+6 -1
View File
@@ -619,7 +619,12 @@ knex.select('*')
//
// Migrations
//
var config = { };
var config = {
directory: "./migrations",
extension: "js",
tableName: "knex_migrations",
disableTransactions: false
};
knex.migrate.make(name, config);
knex.migrate.make(name);
+1 -1
View File
@@ -532,10 +532,10 @@ declare module "knex" {
}
interface MigratorConfig {
database?: string;
directory?: string;
extension?: string;
tableName?: string;
disableTransactions?: boolean;
}
interface Migrator {
+9 -2
View File
@@ -61,8 +61,10 @@ interface KnockoutSubscription {
}
interface KnockoutSubscribable<T> extends KnockoutSubscribableFunctions<T> {
subscribe(callback: (newValue: T) => void, target?: any, event?: string): KnockoutSubscription;
subscribe(callback: (newValue: T) => void, target: any, event: "beforeChange"): KnockoutSubscription;
subscribe(callback: (newValue: T) => void, target?: any, event?: "change"): KnockoutSubscription;
subscribe<TEvent>(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription;
extend(requestedExtenders: { [key: string]: any; }): KnockoutSubscribable<T>;
getSubscriptionsCount(): number;
}
@@ -91,6 +93,11 @@ interface KnockoutObservableArrayStatic {
}
interface KnockoutObservableArray<T> extends KnockoutObservable<T[]>, KnockoutObservableArrayFunctions<T> {
subscribe(callback: (newValue: KnockoutArrayChange<T>[]) => void, target: any, event: "arrayChange"): KnockoutSubscription;
subscribe(callback: (newValue: T[]) => void, target: any, event: "beforeChange"): KnockoutSubscription;
subscribe(callback: (newValue: T[]) => void, target?: any, event?: "change"): KnockoutSubscription;
subscribe<TEvent>(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription;
extend(requestedExtenders: { [key: string]: any; }): KnockoutObservableArray<T>;
}
@@ -325,7 +332,7 @@ interface KnockoutUtils {
}
interface KnockoutArrayChange<T> {
status: string;
status: "added" | "deleted";
value: T;
index: number;
moved?: number;
+1 -1
View File
@@ -1,6 +1,6 @@
/// <reference path="./knockout.d.ts" />
import ko = require("knockout");
import ko = require("knockout");
var myArray = ko.observableArray([1, 2, 3]);
+35
View File
@@ -680,3 +680,38 @@ function test_tasks() {
setTimeout(callback, 0);
};
}
function observableEventsTests() {
var observable = ko.observable(1);
observable.subscribe(value => {
var num: number = value;
});
observable.subscribe(value => {
var num: number = value;
}, null, "change");
observable.subscribe(value => {
var num: number = value;
}, null, "beforeChange");
}
function observableArrayEventsTests() {
var observableArray = ko.observableArray([1, 2, 3, 4]);
observableArray.subscribe(array => {
var arr: number[] = array;
});
observableArray.subscribe(array => {
var arr: number[] = array;
}, null, "change");
observableArray.subscribe(array => {
var arr: number[] = array;
}, null, "beforeChange");
var count = 0;
observableArray.subscribe(changes => {
changes.forEach(change => {
if (change.status == "added")
count++;
else if (change.status == "deleted")
count--;
});
}, null, "arrayChange");
}
+1 -1
View File
@@ -1,4 +1,4 @@
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
/// <reference path="leaflet-curve.d.ts" />
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Onikiienko <https://github.com/onikiienko>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
declare namespace L {
/**
+2 -2
View File
@@ -1,4 +1,4 @@
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
/// <reference path="leaflet-draw.d.ts" />
@@ -44,4 +44,4 @@ map.on('draw:created', function (e: L.DrawEvents.Created) {
layer = e.layer;
drawnItems.addLayer(layer);
});
});
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Matt Guest <https://github.com/matt-guest>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="../leaflet/leaflet-0.7.d.ts" />
declare namespace L {
export interface MapOptions {

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